Sed delete strings not containing a specific string

I am 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 the string 'text' and or the string 'blah', so my output file looks like this:

 some text here blah blah 123 some other text as well 

Any tips on how this can be done with sed ?

+46
sed
Mar 02 2018-12-12T00:
source share
3 answers

This might work for you:

 sed '/text\|blah/!d' file some text here blah blah 123 some other text as well 
+75
Mar 03 2018-12-12T00:
source share
— -

You want to print only those lines that match either “text” or “blah” (or both), where the distinction between “and” and “or” is crucial.

 sed -n -e '/text/{p;n;}' -e '/blah/{p;n;}' your_data_file 

-n means that printing is not performed by default. The first model searches for "text", prints it if it is matched, and proceeds to the next line; the second template does the same for blah. If "n" was not, then a line containing "text and blah" will be printed twice. Although I could only use -e '/blah/p' , symmetry is better, especially if you need to expand the list of matching words.

If your sed version supports extended regular expressions (for example, GNU sed does with -r ), you can simplify this:

 sed -r -n -e '/text|blah/p' your_data_file 
+10
Mar 02 2018-12-12T00:
source share

You can just do it through awk,

 $ awk '/blah|text/' file some text here blah blah 123 some other text as well 
+2
Sep 27 '14 at 7:06
source share



All Articles