Home > Blockchain >  Deleting one or two lines with sed
Deleting one or two lines with sed

Time:02-23

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?

CodePudding user response:

Not sure what you mean by the 'right way to do it', but here is one potential option (works with GNU sed):

cat test.txt
# some text
command 1
function f1 () {aljghwbelqbnqerlbn}
function f1 ()
{sgjlnswbjnepbn}
command 2

sed '/function f1 () {/d; /function f1 ()/, 1 d' test.txt
# some text
command 1
command 2

With each file containing only a single style:

cat test1.txt
# some text
command 1
function f1 () {aljghwbelqbnqerlbn}
function f1 () {sgjlnswbjnepbn}
command 2

sed '/function f1 () {/d; /function f1 ()/, 1 d' test1.txt
# some text
command 1
command 2
cat test2.txt
# some text
command 1
function f1 ()
{aljghwbelqbnqerlbn}
function f1 ()
{sgjlnswbjnepbn}
command 2

sed '/function f1 () {/d; /function f1 ()/, 1 d' test2.txt
# some text
command 1
command 2

CodePudding user response:

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