Prince Garg
Prince Garg

Reputation: 336

Search exact multiple pattern in file and delete line if pattern matches

For example, a file with content like this, which doesn't contain any duplicate entries:

100
10012
12345
12387
123
123456344

I want to search 100 and 12345 in the above file and delete the line if the pattern matches.

Also I want to do this in a single command.

Upvotes: 3

Views: 11864

Answers (4)

user3565159
user3565159

Reputation: 21

sed '/\(100\|12345\)/d' file.txt

Upvotes: 2

January
January

Reputation: 17090

I would simply do

egrep -v '^(100|12345)$' file.in > file.out

Or, with sed

sed -n '/^\(100\|12345\)$/!p' file.in > file.out

you don't even need a second file:

sed -ni '/^\(100\|12345\)$/!p' file.in

(see the comments; strictly speaking, a temporary file is created which then replaces the input file, however this is transparent for the user)

As you see, the regular expression stays more or less the same (except that you don't need to escape ()| in egrep). If you have more than one word on a line, but only want to match whole words, you can use the following sed regex:

sed -n '/\<\(100\|12345\)\>/!p' file.in > file.out

This will match lines 100, 123 100 123 but not 123 100123.

To get the same behaviour with grep, use the -w option (thanks Janito):

egrep -wv '(100|12345)' file.in > file.out

Upvotes: 7

Steve
Steve

Reputation: 54392

One way using sed:

sed '/^\(100\|12345\)$/d' file.txt 

Results:

10012
12387
123
123456344

Upvotes: 1

Jens
Jens

Reputation: 72639

If the numbers must match exactly, you can use an extended grep pattern like this:

 grep -v -E '^(100|12345)$' inputfile

This says: print all lines which are not 100 or 12345. If the numbers need to match only at the beginning of the line, use

 grep -v -E '^(100|12345)' inputfile

If they can match anywhere, use

 grep -v -E '(100|12345)' inputfile

Upvotes: 1

Related Questions