How to find all files containing a text string on Linux

  • 20 May 2016
  • ADM

 

How to find all files containing a text string on Linux - images/logos/linux.jpg

 

In Linux, when you want to find all files that contains a specific text you can use grep command.

Parameters

Here are the most useful parameters for grep command.

  • -r or -R is recursive;
  • -n is line number;
  • -w stands match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.
  • --exclude or --include parameters could be used to exclude/include files to search in.
  • --exclude-dir or --include-dir parameters could be used to exclude/include folders to search in.

Example 1

$ grep -rnw '/path/to/search/in/' -e "text to find"

This command will search in all files from /path/to/search/in/ folder for text: text to find.

Example 2

$ grep --include=\*.{php,inc} -rnw '/path/to/search/in/' -e "text to find"

This will only search through the files which have .php or .inc extensions.

Example 3

$ grep --exclude=\*.{php,inc} -rnw '/path/to/search/in/' -e "text to find"

This will ignore the files which have .php or .inc extensions.

Example 4

Just like exclude/include file it's possible to exclude/include directories from the search.

$ grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/search/in/' -e "text to find"

or

$ grep --include-dir={dir1,dir2,*.dst} -rnw '/path/to/search/in/' -e "text to find"

 

References

For more options on the grep command run the command:

$ man grep