简体   繁体   中英

Using grep to recursively search a directory for a pattern while excluding another pattern

I want to search for a pattern in all files within a directory. I know that this can be achieved using

grep -r "<pattern1>"

But I want to display all lines amongst all files that have pattern1 and does not have a second pattern say pattern2.

For example:

grep -r "chrome"

The above command prints all line that have the word "chrome". But i would like to print only those lines that have chrome but do not contain "chrome.storage.sync".

You can use a pipe to filter out the lines as

grep "chrome" inputFile | grep -v "chrome\.storage\.sync"

From man page

   -v, --invert-match
              Invert the sense of matching, to select non-matching lines.

Test

$ cat test
chrome
chrome chrome.storage.sync

$ grep "chrome" test | grep -v "chrome\.storage\.sync"
chrome

If your grep support P then you could use the below regex based grep command.

grep -Pr '^(?=.*chrome)(?!.*chrome\.storage\.sync)'

Regular Expression:

^                        the beginning of the string
(?=                      look ahead to see if there is:
  .*                       any character except \n (0 or more
                           times)
  chrome                   'chrome'
)                        end of look-ahead
(?!                      look ahead to see if there is not:
  .*                       any character except \n (0 or more
                           times)
  chrome                   'chrome'
  \.                       '.'
  storage                  'storage'
  \.                       '.'
  sync                     'sync'
)                        end of look-ahead

Much shorter form,

grep -Pr 'chrome(?!\.storage\.sync)'

(?!\\.storage\\.sync) Negative lookahead asserts that the string following the match would be any but not of .storage.sync

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