Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

sed

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?

like image 891
qazwsx Avatar asked Feb 27 '12 22:02

qazwsx


People also ask

How do you use a new line character in sed?

If using a sed script, "i\" immediately followed by a literal newline will work on all versions of sed. Furthermore, the command "s/$/This line is new/" will only work if the hold space is already empty (which it is by default).

How do you insert a new line after a specific character in a script?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.

How do you escape a new line in sed?

The backslash (\) in the replacement string of the sed substitution command is generally used to escape other metacharacters, but it is also used to include a newline in a replacement string.

How do I add a new line to the end of a string?

Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


2 Answers

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.

like image 129
Sylvain Defresne Avatar answered Sep 28 '22 02:09

Sylvain Defresne


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
like image 39
Dom Avatar answered Sep 28 '22 01:09

Dom