Chris
Chris

Reputation: 1229

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

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?

Upvotes: 0

Views: 241

Answers (3)

William Pursell
William Pursell

Reputation: 212414

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

Upvotes: 1

potong
potong

Reputation: 58473

This might work for you (GNU sed):

sed -E ':a;N;s/\n/&/2;Ta;s/\n([0-9]+\n[0-9]+)$/ \1/;ta;P;D' file

Open a window of 3 lines in the pattern space. If the 2nd and 3rd lines are numbers only, replace the 1st newline with a space and refill the window. Otherwise print/delete the first line in the pattern space and repeat.

Upvotes: 0

ikegami
ikegami

Reputation: 386371

Just read in the whole file

perl -0777pe's/^(?=\d.*\n\d)/prepended text /mg'

You could also work with a two-line rolling window.

perl -ne'
   push @buf, $_;
   next if @buf < 2;
   $buf[0] = "prepended text $buf[0]" if $buf[0] =~ /^\d/ && $buf[1] =~ /^\d/;
   print(shift(@buf));
   END { print @buf; }
'

See Specifying file to process to Perl one-liner.

Upvotes: 1

Related Questions