Monday, March 7, 2016

Finding all files containing a text string on Linux

http://stackoverflow.com/questions/16956810/finding-all-files-containing-a-text-string-on-linux


I'm trying to find a way to scan my entire Linux system for all files containing a specific string of text. Just to clarify, I'm looking for text within the file, not in the file name.
When I was looking up how to do this, I came across this solution twice:
find / -type f -exec grep -H 'text-to-find-here' {} \;
However, it doesn't work. It seems to display every single file in the system.
Is this close to the proper way to do it? If not, how should I? This ability to find text strings in files would be extraordinary useful for me for some programming projects I'm doing.
shareimprove this question
4 
remember that grep will interpret any . as a single-character wildcard, among others. My advice is to alway use either fgrep or egrep. – Walter Tross Oct 28 '13 at 11:54
3 
anyway, you were almost there! Just replace -H with -l (and maybe grep with fgrep). To exclude files with certain patterns of names you would use find in a more advanced way. It's worthwile to learn to use find, though. Just man find. – Walter Tross Oct 28 '13 at 12:01 
6 
reading again your question, it seems like you didn't notice that you should replace the / in your command with a directory of your choice, quite often . – Walter Tross Oct 29 '13 at 13:32
3 
Freak that. Will copy over to the Windows side and use Total Commander :) Tired of this 70-ies ... -gxn --i stuff. – mlvljr Feb 5 '15 at 22:37
   
find … -exec <cmd> + is easier to type and faster than find … -exec <cmd> \;. It works only if<cmd> accepts any number of file name arguments. The saving in execution time is especially big if<cmd> is slow to start like Python or Ruby scripts. – hagello Jan 28 at 5:16

24 Answers

up vote1965down voteaccepted
Do the following:
grep -rnw '/path/to/somewhere/' -e "pattern"
-r or -R is recursive, -n is line number and -w stands match the whole word. -l (lower-case L) can be added to just give the file name of matching files.
Along with these, --exclude or --include parameter could be used for efficient searching. Something like below:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
This will only search through the files which have .c or .h extensions. Similarly a sample use of --exclude:
grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
Above will exclude searching all the files ending with .o extension. Just like exclude file it's possible to exclude/include directories through --exclude-dir and --include-dir parameter; for example, the following shows how to integrate --exclude-dir:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"
This works very well for me, to achieve almost the same purpose like yours.
For more options :
man grep