Moved to new blog: http://nlfiedler.github.io/2010/12/05/newlines-in-sed-on-mac.html
About Me
My name is Nathan Fiedler, and my interests include programming languages and developer tools. I currently work for Perforce in the platform group.Blogroll
Damn it… I encounter this problem too. This is so hard to understand.
Pingback: links for 2011-07-06 « Use You Imagination
I’m having this problem on OsX 10.6 not just with sed but with bash in general. No matter how I try to get a script to output a newline, all it does is print \n.
The issue here is not with OSX per-se as it is with the default version of sed you get with OSX.
/usr/bin/sed is the BSD version from May 10, 2005
Optionally, you can install gnu sed or gsed via ports (currently 4.2.1 from June 2009) that behaves as you are accustomed to on linux.
$ echo “a b c d” | gsed ‘s/ /\n/g’
a
b
c
d
i love you. thank you.
Pingback: You see, yesterday I referred to some work I had to do for university. That wasn’t quite true. - GhostLyrics' Journal
There’s an interesting discussion in superuser about this if it helps. It can be done it seems, it just requires you to get bash to do the escaping: http://superuser.com/questions/307165/newlines-in-sed-on-mac-os-x
These work:
echo ‘foo bar’ | sed $’s/ /\\\n/g’
nl=$’\n’; echo ‘foo bar’ | sed “s/ /\\$nl/g”
Or you can use: tr ‘ ‘ ‘\n’
You are awesome. Thanks!
Yes, this is a pain! I came across your blog when searching to solve the same problem. BTW, the following also works on OS X (the ‘y’ function does a global replace, and allows you to use \n as a replacement string):
echo ‘foo bar baz quux’ | sed “y/ /\n/”
This worked for me to replace the Mac OSX csv line feeds with standard ones. Allowed me to import the .csv file I created from mac excel to mySQL.
awk ‘{gsub(“\r”, “\n”); print $0;}’ file1.csv > file2.csv
If all your sed usage tends to be substitution expressions (as mine tends to be), you can also use perl
$ echo ‘foo bar baz quux’ | perl -pe ‘s/ /\n/g’
foo
bar
baz
quux
Why not use the standard POSIX way? Escaped newline?
echo “a b c” | sed ‘s/ /\
/g’