Tuesday, March 15, 2022

[SOLVED] How to not conflict with filename when combining grep commands?

Issue

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?


Solution

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}' {} +


Answered By - Sundeep
Answer Checked By - Mildred Charles (WPSolving Admin)