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?
source to share
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 atbar\n
at the beginning of the line. This effectively adds a newline that precedes the one that containsfoo
.GNU can write
\n
and sed interprets it as a newline. This does not work under BSD sed. Hence another version.
source to share