Romonov
Romonov

Reputation: 8605

grep in all directories

I have a directory named XYZ which has directories ABC, DEF, GHI inside it. I want to search for a pattern 'writeText' in all *.c in all directories (i.e XYZ, XYZ/ABC, XYZ/DEF and XYZ/GHI) What grep command can I use?

Also if I want to search only in XYZ, XYZ/ABC, XYZ/GHI and not XYZ/DEF, what grep command can I use?

Thank you!

Upvotes: 21

Views: 57666

Answers (2)

wkl
wkl

Reputation: 79921

grep -R --include="*.c" --exclude-dir={DEF} writeFile /path/to/XYZ
  • -R means recursive, so it will go into subdirectories of the directory you're grepping through
  • --include="*.c" means "look for files ending in .c"
  • --exclude-dir={DEF} means "exclude directories named DEF. If you want to exclude multiple directories, do this: --exclude-dir={DEF,GBA,XYZ}
  • writeFile is the pattern you're grepping for
  • /path/to/XYZ is the path to the directory you want to grep through.

Note that these flags apply to GNU grep, might be different if you're using BSD/SysV/AIX grep. If you're using Linux/GNU grep utils you should be fine.

Upvotes: 44

Hakan Serce
Hakan Serce

Reputation: 11256

You can use the following command to answer at least the first part of your question.

find . -name *.c | xargs grep "writeText"

Upvotes: 4

Related Questions