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.