Skip to content
Advertisement

4 lines invert grep search in a directory that contains many files

I have many log files in a directory. In those files, there are many lines. Some of these lines contain ERROR word.

I am using grep ERROR abc.* to get error lines from all the abc1,abc2,abc3,etc files.

Now, there are 4-5 ERROR lines that I want to avoid.

So, I am using

grep ERROR abc* | grep -v 'str1| str2'

This works fine. But when I insert 1 more string,

grep ERROR abc* | grep -v 'str1| str2| str3

it doesn’t get affected.

I need to avoid 4-5 strings.. can anybody suggest a solution?

Advertisement

Answer

You are using multiple search pattern, i.e. in a way a regex expression. -E in grep supports an extended regular expression as you can see from the man page below

   -e PATTERN, --regexp=PATTERN
          Use PATTERN as the pattern.  This can be used to specify multiple search patterns, or to protect a pattern beginning with a hyphen (-).  (-e is specified by POSIX.)

   -E, --extended-regexp
       Interpret PATTERN as an extended regular expression (ERE, see below).  (-E is specified by POSIX.)

So you need to use the -E flag along with the -v invert search

grep ERROR abc* | grep -Ev 'str1|str2|str3|str4|str5'

An example of the usage for your reference:-

$ cat sample.txt
ID    F1    F2    F3    F4      ID    F1    F2    F3    F4
aa aa
bb    1    2    3    4  bb    1    2    3    4
cc    1    2    3    4  cc    1    2    3    4
dd    1    2    3    4  dd    1    2    3    4
xx xx

$ grep -vE "aa|xx|yy|F2|cc|dd" sample.txt
bb    1    2    3    4  bb    1    2    3    4
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement