Reputation: 736
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".
Upvotes: 1
Views: 502
Reputation: 26667
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
Upvotes: 4
Reputation: 174696
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
Upvotes: 2