Deleting one or two lines with sed

Viewed 48

I have a file containing one function that can start either like this

function f1 () {

... or

function f1 ()
{  

...

I'm trying to find a sed command that deletes one line in the first case and two lines in the second case. I tried using:

 sed /function/,/{/d $file 

but It's not working, how can I do it?

1 Answers

This might work for you (GNU sed):

sed '/^function f1 ()\s*{/d;N;//d;P;D' file

If a line contains the first required string, delete it.

Otherwise, append the following line and test it again.

If the match is true, delete both lines, otherwise print/delete the first and repeat.

N.B. The // match uses the last regexp entered and as \s* matches zero or more white space (which also includes newlines) the regexp is good for the deletion of either of the two required strings.

An alternative:

sed '/^function f1 ()[ \n]*{/d;N;//d;P;D' file
Related