Herr Bischoff

BSD sed: Replace Space With Line Break

Recently, BSD sed caused me much frustration for a very simple replace operation: spaces to line breaks (or newlines).

First, there is the problem that literal spaces are not always understood. You may have to use a character class ([:space:]) but that does not work reliably either. Not to mention, you have to specially escape this for sed, by wrapping it into another set of square brackets ([[:space:]]). Following that, a simple PCRE \n for a newline would be too much. Because it is. So that the final result looks like this:

echo 123 abc xyz | sed 's/[[:space:]]/\\

Yes, that’s right. You have to literally enter the Enter key after a double escape. Shell support is questionable and it’s very unfortunate for scripting, so there must be a better way. And there is: just use tr and skip all the special sauce.

echo 123 abc xyz | tr ' ' '\n'