grep -r 'pattern' <directory path>
To also list line numbers of matches use -n
option
grep -rn 'pattern' <directory path>
To search only files with particular glob pattern
grep --include='*.txt' -r 'pattern' <directory path>
Exclude file patterns or directories
grep -R --exclude=*.log 'pattern' <directory path>
grep -R --exclude={*.log,*.class} 'pattern' <directory path>
grep -R --exclude-dir=tmp 'pattern' <directory path>
grep -R --exclude-dir={tmp,lib} 'pattern' <directory path>
Notes and other useful options
<directory path>
can be skipped if searching in current directory-R
options follows all symbolic links, unlike -r
which follows symbolic links only if they are on the
command line-l
to only list matching files-h
to suppress filename prefix--color=auto
to highlight matched patterns-m <num>
to specify maximum number of matches for each file inputfind <directory path> -type f -exec grep -l 'pattern' {} +
-n
, -l
, etc can be used as required{} +
is not supported, use {} \;
insteadfind
command like how to include/exclude file types, directories etc