温馨提示:本文翻译自stackoverflow.com,查看原文请点击:bash - If line and the next line starts with a number, append text to the matching line
awk bash grep perl sed

bash - 如果line和next line以数字开头,请将文本附加到匹配的行

发布于 2020-04-12 12:33:33

如果行和下一行以数字开头,如何在行首添加字符串?

从:

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

不知道如何做我想做的事情。

“随机文本”可能以数字结尾

有任何想法吗?

查看更多

提问者
Chris
被浏览
59
William Pursell 2020-02-03 22:47

最好用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