Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed- delete line that doesn't contain a pattern

Tags:

bash

sed

I'm surprised that I can't find a question similar to this one on SO.

How do I 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 want a sed command that, when called, will delete all lines that do not contain the word cat:

cat kitty dog
like image 943
buydadip Avatar asked Jan 01 '15 20:01

buydadip


4 Answers

This will do:

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

To force an exact match:

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

or

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

where \<\> & \b\b force an exact match.

like image 66
Amit Verma Avatar answered Oct 21 '22 04:10

Amit Verma


So your requirement would be "give me all lines containing string cat". then why not just simply using grep :

grep cat file
like image 27
Kent Avatar answered Oct 21 '22 05:10

Kent


to see all lines containg word 'cat' (as pointed by Kent):

grep cat file

to see all lines NOT containg word 'cat':

grep -v cat file
like image 37
Denio Mariz Avatar answered Oct 21 '22 05:10

Denio Mariz


You can use this awk

awk '/cat/' file
like image 1
Jotne Avatar answered Oct 21 '22 03:10

Jotne