'escaping newlines in sed replacement string

Here are my attempts to replace a b character with a newline using sed while running bash

$> echo 'abc' | sed 's/b/\n/'
anc

no, that's not it

$> echo 'abc' | sed 's/b/\\n/'
a\nc

no, that's not it either. The output I want is

a
c

HELP!



Solution 1:[1]

Looks like you are on BSD or Solaris. Try this:

[jaypal:~/Temp] echo 'abc' | sed 's/b/\ 
> /'
a
c

Add a black slash and hit enter and complete your sed statement.

Solution 2:[2]

$ echo 'abc' | sed 's/b/\'$'\n''/'
a
c

In Bash, $'\n' expands to a single quoted newline character (see "QUOTING" section of man bash). The three strings are concatenated before being passed into sed as an argument. Sed requires that the newline character be escaped, hence the first backslash in the code I pasted.

Solution 3:[3]

You didn't say you want to globally replace all b. If yes, you want tr instead:

$ echo abcbd | tr b $'\n'
a
c
d

Works for me on Solaris 5.8 and bash 2.03

Solution 4:[4]

In a multiline file I had to pipe through tr on both sides of sed, like so:

echo "$FILE_CONTENTS" | \ tr '\n' ¥ | tr ' ' ? | mySedFunction $1 | tr ¥ '\n' | tr ? ' '

See unix likes to strip out newlines and extra leading spaces and all sorts of things, because I guess that seemed like the thing to do at the time when it was made back in the 1900s. Anyway, this method I show above solves the problem 100%. Wish I would have seen someone post this somewhere because it would have saved me about three hours of my life.

Solution 5:[5]

echo 'abc' | sed 's/b/\'\n'/' 

you are missing '' around \n

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 spraff
Solution 2 tboyce12
Solution 3 glenn jackman
Solution 4 CommaToast
Solution 5 Ravi Bhatt