Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed help: matching and replacing a literal "\n" (not the newline)

i have a file which contains several instances of \n.

i would like to replace them with actual newlines, but sed doesn't recognize the \n.

i tried

sed -r -e 's/\n/\n/'
sed -r -e 's/\\n/\n/'
sed -r -e 's/[\n]/\n/'

and many other ways of escaping it.

is sed able to recognize a literal \n? if so, how?

is there another program that can read the file interpreting the \n's as real newlines?

like image 635
sam h Avatar asked Nov 04 '13 05:11

sam h


People also ask

How do I add a carriage return in sed?

In this script, the '$' regular expression will match the end of the line, and the '\r' tells sed to insert a carriage return right before it. Insert a carriage return before a line feed, and presto, a CR/LF ends each line. Please note that the '\r' will be replaced with a CR only when using GNU sed 3.02.

How do you use sed to substitute a new line?

Using `sed` to replace \n with a comma By default, every line ends with \n when creating a file. The `sed` command can easily split on \n and replace the newline with any character. Another delimiter can be used in place of \n, but only when GNU sed is used.


2 Answers

Can you please try this

sed -i 's/\\n/\n/g' input_filename
like image 63
Ashish Avatar answered Nov 14 '22 23:11

Ashish


What exactly works depends on your sed implementation. This is poorly specified in POSIX so you see all kinds of behaviors.

The -r option is also not part of the POSIX standard; but your script doesn't use any of the -r features, so let's just take it out. (For what it's worth, it changes the regex dialect supported in the match expression from POSIX "basic" to "extended" regular expressions; some sed variants have an -E option which does the same thing. In brief, things like capturing parentheses and repeating braces are "extended" features.)

On BSD platforms (including MacOS), you will generally want to backslash the literal newline, like this:

sed 's/\\n/\
/g' file

On some other systems, like Linux (also depending on the precise sed version installed -- some distros use GNU sed, others favor something more traditional, still others let you choose) you might be able to use a literal \n in the replacement string to represent an actual newline character; but again, this is nonstandard and thus not portable.

If you need a properly portable solution, probably go with Awk or (gasp) Perl.

perl -pe 's/\\n/\n/g' file

In case you don't have access to the manuals, the /g flag says to replace every occurrence on a line; the default behavior of the s/// command is to only replace the first match on every line.

like image 33
tripleee Avatar answered Nov 14 '22 23:11

tripleee