如果行和下一行以数字开头,如何在行首添加字符串?
从:
random text
random text
65345
234
random text
random text
random text
random text
random text
random text
9875
789709
random text
random text
random text
至:
random text
random text
appended text 65345
234
random text
random text
random text
random text
random text
random text
appended text 9875
789709
random text
random text
random text
添加到所有以数字开头的行很简单
$ printf "hello\n123\n" | sed 's/^[0-9]/appended text &/'
hello
appended text 123
不知道如何做我想做的事情。
“随机文本”可能以数字结尾
有任何想法吗?
最好用awk完成这种事情。就像是:
awk 'prev ~ /^[0-9]/ && /^[0-9]/ { prev = "prepended text " prev}
NR>1 {print prev}
{prev=$0}
END {print prev}' input
实际上,这可能是“中”的“最佳做法” perl
,但这几天似乎不合时宜:
perl -0777 -pe '1 while s/(?<=^)(\d.*\n\d)/prepended text $1/cm' input
您的Perl程序不处理
printf "123\n456\n"
(前两行中的数字)或printf "abc\n123\n456\n789\n"
(连续两行以上的数字)的输出第一个很容易处理:
perl -0777 -pe 's/(^[0-9].*\n[0-9])/prepended text $1/g'
awk似乎工作得很好。我已经在我的文件上对其进行了测试,但是还没有发现问题。谢谢