How do I insert a newline in the replacement part of sed?
This code isn\'t working:
sed \"s/\\(1234\\)/\\n\\1/g\" input.txt > output.txt
>
The newline in the middle of the command can feel a bit clumsy:
$ echo abc | sed 's/b/\
/'
a
c
Here are two solutions to this problem which I think should be quite portable
(should work for any POSIX-compliant sh
, printf
, and sed
):
Solution 1:
Remember to escape any \
and %
characters for printf
here:
$ echo abc | sed "$(printf 's/b/\\\n/')"
a
c
To avoid the need for escaping \
and %
characters for printf
:
$ echo abc | sed "$(printf '%s\n%s' 's/b/\' '/')"
a
c
Solution 2:
Make a variable containing a newline like this:
newline="$(printf '\nx')"; newline="${newline%x}"
Or like this:
newline='
'
Then use it like this:
$ echo abc | sed "s/b/\\${newline}/"
a
c