How to remove a line containing specific string from file with sed command

I have the following file :

#!example
#!toto
example
#example
;example
toto
example

I want to remove the lines containing the string "example" except the lines start with "#!".

So the result file should be:

#!example
#!toto
toto

How to do it with only sed command?

Upvotes: 2

Views: 4114

Answers (3)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed '/#!/b;/example/d' file

This prints all lines containing #! and all other lines except those containing example.

Upvotes: 2

Kent
Kent

Reputation: 195059

how about this line:

 sed '/^#!/n;/example/d' file

test with your example text:

kent$  cat file
#!example
#!toto
example
#example
;example
toto
example

kent$  sed '/^#!/n;/example/d' file
#!example
#!toto
toto

if you like, awk could do it too:

kent$  awk '/^#!/ || !/example/' file                                                                                                                 
#!example
#!toto
toto

EDIT

sed:

  • if line matches starting with #!, stop processing, go to next line (n)
  • if above checking failed (doesn't match #!), check if containing example, if yes, d delete (do not print in output)

awk

  • print all lines with:
    • starting with #! or (||) not containing example.

performance:

I cannot really tell. because the requirement is simple enough. You could build a huge file, and use time to compare by yourself.

Upvotes: 4

Zombo
Zombo

Reputation: 1

If you want to keep only lines starting with #!

$ sed '/#!/!d' foo.sh
#!example
#!toto

Upvotes: 2

Related Questions