sorin
sorin

Reputation: 170410

How to get list of all files containing one pattern and not containing another one?

I am looking for one CLI that would return me a list of files that contain foo text and that do not contain bar inside.

Please note that I am looking for a portable solution, so keep in mind the differences between GNU and non-GNU versions of awk/grep/...

If it can be don in a single command, even better.

Upvotes: 2

Views: 63

Answers (2)

Stats4224
Stats4224

Reputation: 808

This will stop grep on the first match, but does involve reading the same file twice.

find . -type f -exec bash -c 'if grep -q -m1 foo $0 && ! grep -q -m1 bar $0; then echo $0; fi' {} \;

Upvotes: 1

anubhava
anubhava

Reputation: 785068

You can use this find + awk solution:

find . -maxdepth 1 -type f -exec \
awk '/foo/{m=1} /bar/{n=1} END{if (m && !n) print FILENAME}' {} \;

Upvotes: 3

Related Questions