Wednesday, January 17, 2018

Find files containing string

Use grep:
-r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line
-R, Read all files under each directory, recursively.  Follow all symbolic links, unlike -r.
-n, --line-number
-w, --word-regexp

   Select  only  those  lines  containing  matches  that  form  whole  words.
-l, --files-with-matches, print file name only
   Suppress normal output; print the name of each input file. The scanning will stop on the first match.
-i, --ignore-case, 
   Ignore case distinctions in both the PATTERN and the input files
-s, --no-messages
--include=GLOB
              Search only files whose base name matches GLOB (using wildcard matching)
--exclude=GLOB

              Skip files whose base name matches GLOB (using wildcard matching)
 --exclude-dir=DIR

grep -R --include="*.java" oraclehomeExistNodeList .

grep -r "string to be searched" /path/to/dir
grep -rnw '/path/to/somewhere/' -e 'pattern'

grep -insrw --include=Makefile "SBS_SCRIPTS" install/
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

Along with these, --exclude, --include, --exclude-dir flags could be used for efficient searching.
For directories it's possible to exclude a particular directory(ies) through --exclude-dirparameter.


if the extension or name is known, and only in the child dir of current folder
grep -insr "SBS_SCRIPTS" **/*mk
grep -insr "SBS_SCRIPTS" **/Makefile
The magic here is by using globbing option (**) which helps you to scan all the files recursively with specific extension. If doesn't work, activate it by shopt -s globstar. You may also use **/*.* for all files (excluding hidden and without extension).

Use find:
-i - case insensitive search
-l - only output the filename where the match was found

-h - only output the line which matched (not the filename)

not a good use of xargs?
find . -name "Makefile" | xargs grep -i "SBS_SCRIPTS"
find . -type f | xargs grep 'text-to-find-here'

find . -type f -exec grep -l "text-to-find-here" {} \;