linux shell: prepend or append text to next line after matching line linux shell: prepend or append text to next line after matching line shell shell

linux shell: prepend or append text to next line after matching line


Try this command:

sed '/HEADER 1/{n;s/$/ ABCDE/}' input.txt

This is the logic:

for each line in 'input.txt'        if line matches /HEADER 1/        read next line        append string ' ABCDE'    endif    endfor


sed is an excellent tool for simple substitutions on a single line, for anything else just use awk for portability, extensibility, simplicty, readability, etc., etc.:

$ awk 'found{print $0, "ABCDE"; found=0; next} {print} /HEADER 1/{found=1}' fileHEADER 1 12345 ABCDEHEADER 2 12345HEADER 1 12345 ABCDEHEADER 2 12345

and to pre-pend is just the obvious switch the order of "ABCDE" and $0:

$ awk 'found{print "ABCDE", $0; found=0; next} {print} /HEADER 1/{found=1}' fileHEADER 1ABCDE  12345HEADER 2 12345HEADER 1ABCDE  12345HEADER 2 12345

If you are using sed language constructs other than s, g, p (with -n) then you are using the wrong tool as all other sed language constructs became obsolete in the mid-1970s when awk was invented.

If you doubt that, try modifying a sed script that produces the above output to do anything else, e.g. print a count of how many times it's added ABCDE at the end of each line it does that on. Here's awk:

$ awk 'found{print $0, "ABCDE", ++count; found=0; next} {print} /HEADER 1/{found=1}' fileHEADER 1 12345 ABCDE 1HEADER 2 12345HEADER 1 12345 ABCDE 2HEADER 2 12345

I dread to think what the sed would look like to do something that simple.


If you're confused on the general text-piping linux applications, I would recommend going through this exercise on the Learn Linux the Hard Way course. Should take 4-5 minutes and help quite a bit.