Insert newline before each line matching a pattern unless the previous line is already empty

sedtext processing

I need to add a new line before any line containing a pattern where we can assume that the pattern is always the first string of the current line. For example

This is a
pattern
This is a
pattern

I can add a new line with the sed command

sed -i 's/pattern\+/\n&/g' file

to get the output

This is a

pattern
This is a

pattern

To prevent multiple new lines being added (in case of multiple execution) I want to check whether the line before the pattern is empty. I know I can do that with

if [ "$line" == "" ]; then

But how do I determine the previous line, of a matching pattern, in the first place?

EDIT: Pattern can occur multiple times.

Best Answer

You could store the previous line in the hold space:

sed '
 /^pattern/{
   x
   /./ {
     x
     s/^/\
/
     x
   }
   x
 }
 h'

It would be more legible with awk though:

awk '!previous_empty && /pattern/ {print ""}
     {previous_empty = $0 == ""; print}'

Like the GNU implementations of sed has a -i option for in-place editing, the GNU implementation of awk as -i inplace for that.

Related Question