≡ Menu

Grep Recursively in a directory to find a string in a file

Question – I need to find a string in lots of files in lots of sub-directories. How do I use the Linux command grep to recursively search files in a directory and all sub-directories to find a string?

The command grep is a very useful command to search for strings in a file. By default, grep will print the lines that match the pattern passed in. But by passing the -l parameter, it will print the full path to the file instead of a snippet from that file.

For example, the following Linux command will search files for the string wordpress:

grep -Rli wordpress wp-content/*

The -R option instructs grep to do the search in a recursive manner
The -i option means that grep should search case-insensitively
The -l option asks grep to print the file name instead of a snippet from the file

Another way to do the same thing is by using the find command:

find wp-content/ -exec grep -il wordpress {} \;

Instead of grep doing the recursion, tbe above command uses find to to list files recursively, and then execute grep on each file!

Comments on this entry are closed.