grep in all directories

Romonov picture Romonov · May 17, 2012 · Viewed 49.6k times · Source

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!

Answer

wkl picture wkl · May 17, 2012
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.