Can I use the sed command to replace multiple empty line with one empty line?

sed

Solution

Give this a try:

sed '/^$/N;/^\n$/D' inputfile

Explanation:

- `/^$/N` - match an empty line and append it to pattern space.

- `;` - command delimiter, allows multiple commands on one line, can be used instead of separating commands into multiple `-e` clauses for versions of `sed` that support it.

- `/^\n$/D` - if the pattern space contains only a newline in addition to the one at the end of the pattern space, in other words a sequence of more than one newline, then delete the first newline (more generally, the beginning of pattern space up to and including the first included newline)

Problem

I know there is a similar question in SO How can I replace mutliple empty lines with a single empty line in bash?. But my question is can this be implemented by just using the `sed` command? Thanks

Original source

Related problems