Home > other >  Delete line if a pattern is not there
Delete line if a pattern is not there

Time:07-09

I have a text file with MAC addresses and port numbers like this:

aa:bb:cc:dd:ee:ff 1/1
aa:ff:00:55:66:99 1/1
00:11:22:33:44:55 1/1
99:88:77:66:55:44 1/1
ff:ee:dd:cc:bb:aa 1/2

How can I delete all the lines that have the port number 1/1 AND where the MAC is not aa:bb:cc:dd:ee:ff?

CodePudding user response:

If you invert the condition and think of it as matching instead of deleting, you can use awk to print out matching lines:

awk '$1 == "aa:bb:cc:dd:ee:ff" || $2 != "1/1"' file

CodePudding user response:

Consider this sed one-liner:

sed '/aa:bb:cc:dd:ee:ff/b; /1\/1/d' file

CodePudding user response:

The awk and sed solutions are very elegant and efficient. For completeness, if the order does not matter, you could also use two grep:

$ grep '^aa:bb:cc:dd:ee:ff' file; grep -Ev '(^aa:bb:cc:dd:ee:ff| 1/1$)' file
aa:bb:cc:dd:ee:ff 1/1
ff:ee:dd:cc:bb:aa 1/2

CodePudding user response:

{m,g}awk 'NF % 2' FS='^aa:bb:cc:dd:ee:ff |1[/]1$'
aa:bb:cc:dd:ee:ff 1/1
ff:ee:dd:cc:bb:aa 1/2
  • Related