Sed-delete string that does not contain a pattern

I am surprised that I cannot find a question similar to this one on SO.

How to use sed to delete all lines that do not contain a specific pattern.

For example, I have this file:

cat kitty dog giraffe panda lion tiger 

I need a sed command that, when called, will delete all lines that do not contain the word cat :

 cat kitty dog 
+5
source share
4 answers

This will do:

 sed -i '/cat/!d' file1.txt 

To achieve an exact match:

 sed -i '/\<cat\>/!d' file1.txt 

or

 sed -i '/\bcat\b/!d' file1.txt 

where \<\> and \b\b forced to match.

+8
source

So your requirement would be "give me all the lines containing the cat line". then why just just use grep :

 grep cat file 
+4
source

You can use this awk

 awk '/cat/' file 
+1
source

to see all lines containing the word "cat" (as Kent indicates):

 grep cat file 

to see all lines not containing the word 'cat':

 grep -v cat file 
+1
source

Source: https://habr.com/ru/post/1210225/


All Articles