Awk-将后续行的长度写入行 [英] Awk - Writing length of subsequent line into line
本文介绍了Awk-将后续行的长度写入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假定一个包含交替行的文本文件.具体而言,每个线对的第1行以#"开头,而每个线对的下一行包含字母数字字符串.
Assume a text file that comprises alternating lines. Specifically, line 1 of each line pair starts with a "#", whereas the subsequent line of each line pair contains an alphanumeric string.
$ cat file
#Foo
1234567
#Bar
1234
#Baz
123456789
如何自动将第2行的长度(以及关键字)附加到每对线对的第1行?我相信awk
是执行此操作的正确选择.
How do I automatically append the length of line 2 (as well as a keyword) to line 1 of each line pair? I believe that awk
is the right choice for such an operation.
$ awk 'desired code' file
#Foo_Length7
1234567
#Bar_Length4
1234
#Baz_Length9
123456789
这是我的尝试,但是我不知道用什么替换length($0)
:
Here's my try, but I can't figure out what to substitute the length($0)
with:
awk '{if ($1~/^#/) print $0"_Length"length($0); else print $0}' file
推荐答案
$ awk '!(NR%2){print prev "_Length" length($0) ORS $0} {prev=$0}' file
#Foo_Length7
1234567
#Bar_Length4
1234
#Baz_Length9
123456789
如果愿意,可以将!(NR%2)
替换为!/^#/
或类似名称.
You can replace !(NR%2)
with !/^#/
or similar if you prefer.
这篇关于Awk-将后续行的长度写入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文