How to insert newline character after comma in `),(` with sed?

15,262

Solution 1

OK, I know this question is old but I just had to wade trough this to make sed accept a \n character. I found a solution that works in bash and I am noting it here for others who run into the same problem.

To restate the problem: Get sed to accept the backslash escaped newline (or other backslash escaped characters for that matter).

The workaround in bash is to use:

$'\n'

In bash a $'\n' string is replaced with a real newline.

The only other thing you need to do is double escape the \n as you have to escape the slash itself.

To put it all together:

sed $'s/),(/),\\\n(/g' temp.txt
(foo),
(bar)
(foobar),
(foofoobar)

If you want it actually changed instead of being printed out use the -i

sed -i $'s/),(/),\\\n(/g' temp.txt

Solution 2

sed does not support the \n escape sequence in its substitution command, however, it does support a real newline character if you escape it (because sed commands should only use a single line, and the escape is here to tell sed that you really want a newline character):

$ sed 's/),(/),\\
(/g' temp.txt
(foo),
(bar)
(foobar),
(foofoobar)

You can also use a shell variable to store the newline character.

$ NL='
'
$ sed "s/),(/,\\$NL(/g" temp.txt
(foo),
(bar)
(foobar),
(foofoobar)

Tested on Mac OS X Lion, using bash as shell.

Solution 3

You just have to escape with a backslash character and press the enter key while typing:

$ sed 's/),(/),\
(/g' temp.txt
(foo),
(bar)
(foobar),
(foofoobar)

Solution 4

This works for me:

$ echo "(foo),(bar)" | sed s/')','('/')',\\n'('/g
(foo),
(bar)

I am using:

  • GNU sed 4.2.2
  • GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
Share:
15,262
qazwsx
Author by

qazwsx

Updated on June 09, 2022

Comments

  • qazwsx
    qazwsx almost 2 years

    How to insert newline character after comma in ),( with sed?

    $ more temp.txt
    (foo),(bar)
    (foobar),(foofoobar)
    
    $ sed 's/),(/),\n(/g' temp.txt 
    (foo),n(bar)
    (foobar),n(foofoobar)
    

    Why this doesn't work?