Replace "\n" with newline in awk

Using GNU's sed, the solution is pretty simple as @hek2mgl already answered (and that IMHO is the way it should work everywhere, but unfortunately doesn't).

But it's bit tricky when doing it on Mac OS X and other *BSD UNIXes.

The best way looks like this:

sed 's/\\n/\'$'\n''/g' <<< 'ABC\n123'

Then of course there's still AWK, @AvinashRaj has the correct answer if you'd like to use that.


Why use either awk or sed for this? Use perl!

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

By using perl you avoid having to think about posix compliance, and it will typically give better performance, and it will be consistent across all (most) platforms.


How about this?

$ cat file
John\nDoe
Sara\nConnor

$ awk '{gsub(/\\n/,"\n")}1' file
John
Doe
Sara
Connor

This will work with any sed on any system as it is THE portable way to use newlines in sed:

$ sed 's/\\n/\
/' file
John
Doe
Sara
Connor

If it is possible for your input to contain a line like foo\\nbar and the \\ is intended to be an escaped backslash then you cannot use a simple substitution approach like you've asked for.

Tags:

Bash

Awk