[SLL] sed to delete blank line above and after a regex?

Jeremy C. Reed reed at reedmedia.net
Fri Mar 21 16:44:32 PDT 2008


On Fri, 21 Mar 2008, Ted Stern wrote:

> > Can someone share a sed example of deleting a blank line above and after a 
> > regex?
> >
> > (Or just delete one line above and one line after a regex?)
> >
> > file is like this
> >
> > %
> >
> > but I don't want blank lines
> >
> > %
> >
> > before and after each percent sign
> >
> > %
> >
> >
> > Any ideas on how to do that with sed?
> >
> >   Jeremy C. Reed
> >
> 
> Hi Jeremy,
> 
> Yes, you can do it on a single line.  What you want to do is enlarge
> the search space a bit.
> 
>      sed -e '/^$/{N;N;s/^\n\(RE\)\n$/\1/}'
> 
>      /^$/   Search for blank line
>      {      begin multiple operations
>      N;     swallow another line
>      N;     swallow another line
> 
>      s/^\n\(RE\)\n$/\1/     ^      = beginning of multi-line
>                             \n     = first embedded newline
>                             \(RE\) = keep track of the RE you're
>                                      searching for
>                             \n     = 2nd embedded newline
>                             $      = end of the multi-line space
>                             \1     = the RE you found ... put it back in.
>      }  finish up
> 
> Does that make sense?

Yes, thank you Ted. The "N" for appending next line to pattern space is 
what I needed.

I had tried somethings like that after doing some research but kept 
getting sed errors.

I was using a NetBSD sed and with your expression gave me similar error:

sed: 1: "/^$/{N;N;s/^\n\(%\)\n$/ ...": bad flag in substitute command: '}'

So I installed GNU sed and used:

	gsed -e '/^$/{N;N;s/^\n\(%\)\n$/\1/}'

No errors, but it didn't work on every instance -- strange as I checked 
and double-checked to make sure there were empty lines.

I also tried:

	gsed -e '{N;N;s/^\n\(%\)\n$/\1/}'

which had similar output -- didn't work on every instance but different 
places.

Now I can get rid of every blank line above the % with:

  gsed -e '/^$/{N;s/\n\(%\)$/\1/}'

And remove every blank line after the % with:

  gsed -e '/^%$/{N;s/\(%\)\n$/\1/}'

I couldn't combine them with multiple -e expressions in one gsed -- as 
only one would be done.

I got it to work by piping the output into a second gsed:

gsed -e '/^$/{N;s/\n\(%\)$/\1/}' netbsd-tips.new |
   gsed -e '/^%$/{N;s/\(%\)\n$/\1/}' | less

Thanks again!


  Jeremy C. Reed


More information about the linux-list mailing list