shin shin - 5 months ago 7
Bash Question

How to insert an empty line before and after #, ##, ### through terminal

I am using OSX El Capitan. I have a series of md files, file1.md, file2.md, file3.md etc. Some of

# ## ###
has no line before or after. This breaks when I convert to epub files.

Sample:

<a name="introduction"></a>
## Introduction
...
some texts
### Next topic
...
some texts
### Topic 3
some texts

pandoc -S -o Laravel-doc-5.2.epub *.md


Outputs do not have h1 or h2 tag.

## Introduction


So I want to insert an empty line before and after
# or ## or ###
a line if there is no line.

What I want is:

<a name="introduction"></a>

## Introduction

...
some texts

### Next topic

...
some texts

### Topic 3

some texts


How can I achieve this through the terminal or any method?

Answer

Using the following pattern might work as expected for OS X:

sed '/^#/{x;p;x;G;}' file.md

The command does an exchange, print, exchange, then get to add newlines above/below # lines.

https://www.gnu.org/software/sed/manual/sed.txt