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?
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).
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With