简体   繁体   中英

grep exclude on sentence with [ character

I need to do a grep which excludes sentences which contain 'This is a sentence [WARN]' for example:

aaaabbbbccccThis is a sentence [WARN]ccccdddd

but when I do:

grep WARN log/* | grep -v -E 'This is a sentence [WARN]'

it doesnt work. I think this is because of the "[" and "]" because if I do:

grep WARN log/* | grep -v -E 'This is a sentence'

it works. How can I exclude a sentence containing square brackets?

EDIT:

Sorry I should have said- the string is actually a substring. So I may have:

aaaabbbbccccThis is a sentence [WARN]ccccdddd

which needs to be excluded.

-E is for extended regexp. Just escape the [] brackets, and you should be good.

grep WARN log/* | grep -v -E 'This is a sentence \[WARN\]'

[] brackets means character class when not escaped, so what your pattern would actually look for was one of the following substrings:

  • This is a sentence W
  • This is a sentence A
  • This is a sentence R
  • This is a sentence N

You need to tell grep to use the string as fixed string. For this, you can use -F :

grep WARN log/* | grep -v -F 'This is a sentence [WARN]'

From man grep :

-F, --fixed-strings

Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. (-F is specified by POSIX.)

Test

$ cat a
This is a sentence [LOG]
This is a sentence [WARN]
$ grep -v "sentence [LOG]" a   <---- [LOG] is taken as regex
This is a sentence [LOG]
This is a sentence [WARN]
$ grep -Fv "sentence [LOG]" a   <---- [LOG] is taken literally
This is a sentence [WARN]

Or with updated input:

$ cat a
aaaabbbbccccThis is a sentence [WARN]ccccdddd
aaaabbbbccccThis is a sentence [LOG]ccccdddd
hello!
$ grep -vF "sentence [WARN]" a
aaaabbbbccccThis is a sentence [LOG]ccccdddd
hello!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM