Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search multiple pattern in file and delete line if pattern matches

For ex, a file contain contents:

10.45.56.84 raj
10.49.31.81 mum
10.49.31.86 mum
10.81.51.92 guj
10.45.56.116 raj
10.45.56.84 raj

I want to search 10.45.56.84 and 10.81.51.92 in the above file and delete line if pattern matches.

Also i want to do this in single command.

like image 503
Prince Garg Avatar asked Oct 06 '12 14:10

Prince Garg


People also ask

How do you delete a line with a pattern in Linux?

To begin with, if you want to delete a line containing the keyword, you would run sed as shown below. Similarly, you could run the sed command with option -n and negated p , (! p) command. To delete lines containing multiple keywords, for example to delete lines with the keyword green or lines with keyword violet.

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

N command reads the next line in the pattern space. d deletes the entire pattern space which contains the current and the next line. Using the substitution command s, we delete from the newline character till the end, which effective deletes the next line after the line containing the pattern Unix.

How do you put multiple patterns in sed?

Use multiple patterns at once with SedLook out for the semicolon(;) to add more patterns within the single command.


2 Answers

Another solution:

 awk '!/10.45.56.84|10.81.51.92/' file
like image 61
Tedee12345 Avatar answered Sep 22 '22 06:09

Tedee12345


You could do this:

sed -e '/10[.]45[.]56[.]84/d;/10[.]81[.]51[.]92/d' file

This has two sed "d" delete commands separated by a semicolon. However, they are only executed if they match the respective pattern enclosed between slashes that come before eachcommand.

You can also use grep:

grep -Ev '10[.]45[.]56[.]84|10[.]81[.]51[.]92' file

The "-v" flag tell grep to print only the lines that don't match the pattern, and we use the OR operator "|" to match either pattern. The "-E" flag is used so we don't have to escape the OR operator with a backslash.

In both cases we place the period between brackets because otherwise the period is used as an operator that matches any character. You may place more characters inside a single pair of brackets, and they will be interpreted as to match one of the characters specified.

Hope this helps =)

like image 29
Janito Vaqueiro Ferreira Filho Avatar answered Sep 22 '22 06:09

Janito Vaqueiro Ferreira Filho