If you’re using Linux, performing a recursive grep is very easy. For example:
grep -r "text_to_find" .
- -r means to recurse
- “text_to_find” is the string to search for
- The dot simply means start the search from the current working directory. You could easily replace that with “/etc” for example:
grep -r "text_to_find" /etc
- I always like to use grep -rn because it shows the line number also:
- To search within particular file types:
grep -rn "eth0" --include="*.conf" /etc/
This is all very easy because Linux includes GNU grep. But older releases of Unix do not have GNU grep and do not have any option to grep recursively.
Recursive grep on Unix without GNU grep
If you do not have GNU grep on your Unix system, you can still grep recursively, by combining the find command with grep:
find . | xargs grep "text_to_find"
The above command is fine if you don’t have many files to search though, but it will search all files types, including binaries, so may be very slow. You can narrow down the selection criteria:
find . -name '*.c' | xargs grep -n "text_to_find"
If you don’t know what file type to narrow the search by, you make use of the “file” command to restrict the search to text files only:
find . -type f -print | xargs file | grep -i text | cut -d ':' -f 1 | xargs grep text_to_find
If you have filenames with spaces in them, the commands above will not work properly, another alternative is:
find . -type f -exec grep -n "text_to_find" {} \; -print
These commands should work on:
- IBM Aix
- Solaris
- SCO Openserver
- HP-UX
If you found this post interesting, I’ve also written up some examples of how to grep using Windows Powershell here.
Roger B says
Thanks, this is easier than figuring out the ‘-d ACTION’ where action can be ‘recurse’ syntax, at least i see that when i run `man egrep`. Gracias!