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?
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
Your Perl program doesn't handle the output of
printf "123\n456\n"
(numbers on the first two lines) orprintf "abc\n123\n456\n789\n"
(more than two lines of numbers in a row)The first is easy to deal with:
perl -0777 -pe 's/(^[0-9].*\n[0-9])/prepended text $1/g'
The awk seems to work great. I have tested it on my files and I haven't seen issue yet. Thanks