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
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.
So your requirement would be "give me all lines containing string cat
". then why not just simply using grep
:
grep cat file
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
You can use this awk
awk '/cat/' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With