1

The Unix sed command doesn't recognize a backslash escaped n \n as a newline character. For instance, the command sed "s!,!\n!g" is replacing commas in the input text with the letter n and not a newline character.

How can I make sed interpret \n as a newline character?

1
  • What shell are you using?
    – fd0
    Oct 13, 2015 at 19:20

5 Answers 5

4

If you are using bash, you can insert the newline character by hitting the enter key as

sed 's!,!\
!g'
2
  • 1
    That dint work either
    – hemanth
    Oct 13, 2015 at 19:05
  • oops my appologies . This is working :
    – hemanth
    Oct 13, 2015 at 19:35
2

sed "s/,/\n/g" works here, in bash

2

The Mac version of sed has this difficulty. Try installing the GNU version of sed with brew install coreutils and then

gsed "s/,/\\n/g"

should work. Alternatively, tr ',' \\n should work if the search string is only a single character.

1
  • 1
    This worked on my Mac (Catalina), but I had to install gnu-sed, not coreutils using brew.
    – challinan
    Feb 6, 2022 at 18:15
1

You may need to escape it with a second \

sed 's!,!\\n!g'

You may also need to replace out some white space, depending on what you are looking to do.

in my tests as well sed took issue to using "'s instead of ''s

2
  • Then it replaces a , with \n string not character. Not working either :(
    – hemanth
    Oct 13, 2015 at 19:19
  • Hmm this worked for a redhat 6.7 machine, what is your environment?
    – Gravy
    Oct 13, 2015 at 19:20
0

Indeed Unix Echo + Sed not always process \n as new line character. I've solved it by providing carriage return ASCII 0xd with vertical tab ASCII 0xb instead.

For example add new line character with sed command using variable:

eol="\xd\xb"
echo -e "hello" | sed "s/$/$eol/"
1
  • This doesn't really address the question.
    – RalfFriedl
    Mar 19, 2019 at 9:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .