• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Tachytelic.net

  • Get in Touch
  • About Me

How to grep recursively

January 17, 2019 by Paulie 1 Comment

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:

    Image showing how to use GNU grep recursively
    Note line numbers are added with -n option
  • 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.

Filed Under: Scripts & Utilities

Reader Interactions

Comments

  1. Roger B says

    December 19, 2020 at 8:55 pm

    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!

Leave a Reply Cancel reply

Primary Sidebar

Link to my LinkedIn Profile
Buy me a coffee

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 245 other subscribers.

Go to mobile version