1

Imagine you want to grep recursively for string1 but not string1_suffix. Trivial approach would be

grep -r string1 | grep -v string1_suffix`

But what if the file names can contain string1_suffix?

A line containing string1_suffix_data.json: blabla string1 would be filtered away by the second grep.

Is it possible to circumvent this somehow? Of course in this trivial example I could just turn around the first and the second part, but what about the general case?

frans
  • 8,868
  • 11
  • 58
  • 132
  • 1
    Use `grep -P 'string1(?!_suffix)'` with GNU `grep`. See [Find 'word' not followed by a certain character](https://stackoverflow.com/questions/31201690/find-word-not-followed-by-a-certain-character). – Wiktor Stribiżew Dec 03 '20 at 12:46

1 Answers1

2

If you have PCRE with -P option, you can use string1(?!_suffix)

For a general case, use ^(?!.*str2).*str1 to match lines containing str1 but not str2


With find+awk (tested on GNU awk, not sure about other implementations)

find -type f -exec awk '/str1/ && !/str2/{print FILENAME ":" $0}' {} +
Sundeep
  • 23,246
  • 2
  • 28
  • 103