Using sed to add a newline on Mac OS X

As a quick note today, I have been converting parts of the Scala Cookbook from a plain text format to a Markdown format, and as part of that I needed to add some newline characters to add spacing to the document. This wouldn’t be bad if it was a few pages, but it’s hundreds of pages, so I decided to use the Unix sed command to do the work.

Note: What I gloss over in this example is that trying to use the newline character (\n) as a replacement string doesn’t work with sed on Mac OS X, at least not in Mac OS X 10.9 or 10.10.

Solution

Skipping right to the solution, this sed command did the trick of (a) converting the word “Problem” that’s on a line by itself to being a Markdown “Header 2” tag, with a newline added before and after the word “Problem”:

s/^Problem$/\
## Problem\
/

The \ characters at the end of each line let you continue the replacement text onto multiple lines, and that’s what inserts the newline characters into the sed output.

My full Mac OS X sed script

If it helps to see this in the context of the complete sed script, here’s the source code for the full script:

s/^Problem$/\
## Problem\
/

s/^Solution$/\
## Solution\
/

s/^Discussion$/\
## Discussion\
/

s/^See Also$/\
## See Also\
/

# add a newline to a trailing ':' character
s/^\(.*\)\:$/\1:\
/

# add a newline after '}' on a line by itself
s/^}$/}\
/

# add newline before 'scala>'
s/^\(scala> .*\)/\
\1/

# replace bullets
s/•/*/

If you know sed, you can see that I add several newline characters in that script.

I run this sed script on my Mac OS X system like this:

sed -f sed.cmds Chapter12.md > Ch12.txt

The result

The “Problem” line ends up converting text that looks like this:

foo
Problem
bar

to this:

foo

## Problem

bar

As shown, it adds a newline character before and after the “Problem” line.

In summary, if you wanted to see how to add a newline character to some text when using sed on Mac OS X, I hope this helps.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.