Showing posts with label find all files containing specific text. Show all posts
Showing posts with label find all files containing specific text. Show all posts

Wednesday, August 16, 2017

Linux : Find all files containing specific text on Linux


The most common requirement these days is to find something that you have saved sometime ago in some file in a discrete folder, most importantly he one which you dont remember currently.Windows is pretty staright forward that everyone knows how to serach a file and I will not bore you with details.

However Linux is a different game when it comes to searching files and its contents. We will see a command that will let us do that work in simple and easy to remember manner.
            grep -rnw '/path/to/folder/' -e 'string'               
-r or -R is recursive,
-n is line number, and
-w stands for match the whole word.
-l (lower-case L) can be added to just give the file name of matching files.

Along with above options a few others like , --exclude, --include, --exclude-dir or --include-dir flags could be used for more efficient searching:


This below command will only search through the files which have .properties or .sh extensions:

           grep --include=\*.{properties,sh} -rnw '/path/to/folder/' -e "string"       

This below command will exclude searching all the files ending with .txt extension:

            grep --exclude=*.txt -rnw '/path/to/folder/' -e "string"                           

Just like exclude files, it's possible to exclude/include directories through --exclude-dir and --include-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.ext/:

            grep --exclude-dir={dir1,dir2,*.ext} -rnw '/path/to/folder/' -e "string"     

Hope you got what you came for.