How to perform grep operation on all files in a directory? How to perform grep operation on all files in a directory? linux linux

How to perform grep operation on all files in a directory?


grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.


In Linux, I normally use this command to recursively grep for a particular text within a directory:

grep -rni "string" *

where

  • r = recursive i.e, search subdirectories within the current directory
  • n = to print the line numbers to stdout
  • i = case insensitive search


Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.