0

I want to find all files, who contains two lines: abc and def. For example,

xxx
111abc
yyy
222def333

This file should be caught by grep because it contains abc and def.

What should I do? I've tried grep -rE 'abc.*def' /dir/ but it doesn't work.

1

On GNU systems, this will do the job for two patterns if the relative order of your matches does not matter:

grep -rlZ abc /dir/ | xargs -r0 grep -l def

You can chain that if you have more patterns than two:

grep -rlZ abc /dir/ | xargs -r0 grep -lZ def | xargs -r0 grep -l xxx

or use find:

find /dir/ -type f -exec grep -q abc {} \; -exec grep -q def {} \; -print

This is not very efficient, and another tool than grep might be better for that task.

1

A much more simplified version of grep in the --null-data mode (-z) would be to use a greedy quantifier to match any number of new lines as

grep -ozP  'abc(.*\n.*){1,}def' file

Or use pcregrep (provided by the PCRE project) which by default uses the PCRE regex capabilities. The -M enables the multi-line match mode.

pcregrep -M 'abc(.*\n.*){1,}def' file
  • The first command gave me grep: exceeded PCRE's backtracking limit – Yves Jul 3 at 9:31
1

Just for the case you may have even more complex conditions, we can use Awk

awk 'BEGIN{RS="\0"} 
     /def/ && /abc/ {print FILENAME}' *

Where:

  • RS="\0" defines a register separator not present in the file (=slurp file) and
  • condition {print FILENAME} outputs files matching the condition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.