user2138149
user2138149

Reputation: 17414

How can I used grep to find a file containing 2 strings?

I am searching for the definition of a macro in a project containing hundreds of source code files.

I am fairly sure the macros are all defined in a single file.

If I do a grep -r search for a single macro, over 1000 hits occur.

I would like to search each file, and find those files containing both macro names.

Can this be done with grep?

For example something like this:

grep -r "MACRO1" AND "MACRO2" ./

Upvotes: 0

Views: 146

Answers (3)

Toto
Toto

Reputation: 91518

Use:

grep -Pzrl "(?s)(MACRO1.+MACRO2\|MACRO2.+MACRO1)" ./
  • -P perl regex
  • -z changes newline to null character.
  • -r recursive
  • -l print only filename

  • (?s) makes . matching newlines

  • MACRO1.+MACRO2 find when MACRO1 is before MACRO2
  • MACRO2.+MACRO1 find when MACRO2 is before MACRO1

Upvotes: 1

tso
tso

Reputation: 4934

with gnu grep:

grep -lrZ 'macro1' * |xargs -0 grep -l 'macro2'

it will print files names that contains both macros.

Upvotes: 0

Sundeep
Sundeep

Reputation: 23697

Another way is

grep -rlZ 'MACRO1' ./ | xargs -0 grep -l 'MACRO2'
  • grep -rlZ 'MACRO1' ./ will give filenames containing MACRO1
    • -Z is to separate filenames with null character
  • xargs -0 grep -l 'MACRO2' will give filenames containing MACRO2

Upvotes: 1

Related Questions