Reputation: 1105
I'm new to sed
and I have the following question. In this example:
some text here
blah blah 123
another new line
some other text as well
another line
I want to delete all lines except those that contain either string 'text' and or string 'blah', so my output file looks like this:
some text here
blah blah 123
some other text as well
Any hints how this can be done using sed
?
Upvotes: 90
Views: 108232
Reputation: 21
Are you looking for the grep
?
Here is an example to look for different texts.
cat yourfile.txt | grep "text\|blah"
Upvotes: 1
Reputation: 753525
You want to print only those lines which match either 'text' or 'blah' (or both), where the distinction between 'and' and 'or' is rather crucial.
sed -n -e '/text/{p;n;}' -e '/blah/{p;n;}' your_data_file
The -n
means don't print by default. The first pattern searches for 'text', prints it if matched and skips to the next line; the second pattern does the same for 'blah'. If the 'n' was not there then a line containing 'text and blah' would be printed twice. Although I could have use just -e '/blah/p'
, the symmetry is better, especially if you need to extend the list of matched words.
If your version of sed
supports extended regular expressions (for example, GNU sed
does, with -r
), then you can simplify that to:
sed -r -n -e '/text|blah/p' your_data_file
Upvotes: 18
Reputation: 174696
You could simply do it through awk,
$ awk '/blah|text/' file
some text here
blah blah 123
some other text as well
Upvotes: 11
Reputation: 58371
This might work for you:
sed '/text\|blah/!d' file
some text here
blah blah 123
some other text as well
Upvotes: 127