Sed oneliner to add a line before another line

I need to add a line with bar

in front of each line foo

with a sed

.

I need to do this in the Makefile, and so I cannot use i\

because it needs a newline in the standard sed

(not GNU sed, for example, on Mac OS X) and it cannot be done in the Makefile (at least not very well) ...

I found a solution:

sed '/foo/{h;s/.*/bar/;p;g;}' < in > out

      

This saves the string, replaces its contents with bar

, prints a newline, restores the old string (and prints it by default).

Is there an easier solution?

+3


source to share


2 answers


BSD sed

This will put bar

before every line with foo

:

sed $'/foo/{s/^/bar\\\n/;}' in >out

      

GNU sed



This will put bar

before every line with foo

:

sed '/foo/{s/^/bar\n/;}' in >out

      

How it works

  • /foo/

    This selects lines containing foo

    .

  • s/^/bar\n/

    ^

    matches the beginning of the line. So for the selected lines, this replaces the at bar\n

    at the beginning of the line. This effectively adds a newline that precedes the one that contains foo

    .

    GNU can write \n

    and sed interprets it as a newline. This does not work under BSD sed. Hence another version.

+2


source


This might work for you (GNU sed):

sed '/foo/ibar' file

      



I'm not sure why you are saying you want a newline, but just insert the inserted line longer than one line, you can use bash like so:

sed $'/foo/ibar\\\nbaz' file

      

+1


source







All Articles