Warm tip: This article is reproduced from stackoverflow.com, please click
awk bash grep perl sed

If line and the next line starts with a number, append text to the matching line

发布于 2020-04-11 22:40:55

How can I add a string to the start of a line if the line and the next line start with numbers?

From:

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

To:

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

Adding to all lines that start with numbers is as simple as

$ printf "hello\n123\n" | sed 's/^[0-9]/appended text &/'
hello
appended text 123

No idea how to do what I am trying to do though.

"random text" might end in a number

Any ideas?

Questioner
Chris
Viewed
46
William Pursell 2020-02-03 22:47

This sort of thing is best done with awk. Something like:

awk 'prev ~ /^[0-9]/ && /^[0-9]/ { prev = "prepended text " prev} 
    NR>1 {print prev} 
    {prev=$0}
    END {print prev}' input 

Actually, it's probably "best" done in perl, but that seems to be unfashionable these days:

perl -0777 -pe '1 while s/(?<=^)(\d.*\n\d)/prepended text $1/cm' input