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

Bill Campbell bill at celestial.com
Fri Mar 21 14:06:20 PDT 2008


On Fri, Mar 21, 2008, Jeremy C. Reed 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?

I may well be wrong, but I don't think that sed can do this as it
processes a line at a time.

I do similar things in python with something like this:

#!/usr/bin/env python

import re, sys

fh = open('filename')
data = fh.read() # slurp it all
fh.close()

pattern1 = re.compile(r'\n(\n%.*?\n)', re.DOTALL) # blank preceeds
pattern2 = re.compile(r'(\n%.*?\n)\n', re.DOTALL) # blank after

data = pattern1.sub(r'\1', data)
data = pattern2.sub(r'\1', data)
print data
sys.exit(0)

-- 
Bill
--
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

Suppose you were an idiot.  And suppose you were a member of Congress.  But
I repeat myself.  -- Mark Twain


More information about the linux-list mailing list