Quantcast
Channel: Tachytelic.net
Viewing all articles
Browse latest Browse all 210

How to grep recursively through sub-directories

$
0
0

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

These commands should work on:

If you found this post helpful, I’d be most grateful if you rated it.

The post How to grep recursively through sub-directories appeared first on Tachytelic.net.


Viewing all articles
Browse latest Browse all 210

Trending Articles