Sometimes you need to search for a specific text string in very large code bases (I am looking at you, Linux kernel). Opening those large code bases in your preferred IDE and using the usually "Find in files" tools requires a lot of patience, as it usually takes quite a long time to even load such a large codebase. Here comes grep
to the rescue.
Source: Stack Overflow
grep -rnw '/path/to/somewhere/' -e 'pattern'
-r
or -R
is recursive,-n
is line number, and-w
stands for match the whole word.-l
can be added to just give the file name of matching files.-e
is the pattern used during the searchAlong with these, --exclude
, --include
, --exclude-dir
flags could be used for efficient searching:
This will only search through those files which have .c or .h extensions:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
This will exclude searching all the files ending with .o extension:
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
For directories it's possible to exclude one or more directories using the --exclude-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/search/' -e "pattern"
linux-fslc$ grep --include=\*.{c,h} -rnw . -e "Phy link never came up"
./drivers/pci/controller/dwc/pcie-designware.c:451: dev_err(pci->dev, "Phy link never came up\n");