Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed delete lines not containing specific string

Tags:

sed

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?

like image 466
user1246172 Avatar asked Mar 02 '12 23:03

user1246172


People also ask

How do you delete a line in a file using sed?

To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.

How do I remove a specific pattern from a Unix file?

Sed Command to Delete Lines – Based on Pattern Match. In the following examples, the sed command deletes the lines in file which match the given pattern. ^ is to specify the starting of the line. Above sed command removes all the lines that start with character 'u'.

How do I delete a range of lines in Linux?

The sed command can remove the lines of any range. For this, we just have to enter 'minimum' and 'maximum' line numbers. In this example, we will remove the lines ranging from 4 to 7 numbers. After removing these ranges of lines, our file will look like this.

How do you use sed command to replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.


1 Answers

This might work for you:

sed '/text\|blah/!d' file some text here blah blah 123 some other text as well 
like image 85
potong Avatar answered Sep 18 '22 18:09

potong