1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Search File Content Recursively

Discussion in 'General' started by Ronaldr, Aug 21, 2009.

  1. Ronaldr

    Ronaldr New Member

    Messages:
    37
    Thanks Received:
    0
    Hello All,

    I'm looking for a particular string or phrase in a wide group of files.

    is there a way to search the content of all files for a particular string/phrase match ?
     
  2. jrick

    jrick New Member

    Messages:
    84
    Thanks Received:
    5
    Yes. Want you want to use is a tool called grep(1).

    I'll leave it up to you to read the manpage, but generally you should be able to do something like:

    % grep -r 'your search here' *
     
  3. DutchDaemon

    DutchDaemon Administrator Staff Member Administrator Moderator

    Messages:
    10,725
    Thanks Received:
    2,137
    If you expect a lot of hits, use grep -rli. This will recurse into a directory tree, show only a list of files that contain the string, and use case-insensitive matching.
     
  4. SirDice

    SirDice Moderator Staff Member Moderator

    Messages:
    17,526
    Thanks Received:
    2,351
    Or, if you only want to search in .txt files, combine it with find(1).

    $ find /some/dir -name '*.txt' -exec grep -li 'searchstring' {} \;
     
  5. speed

    speed New Member

    Messages:
    8
    Thanks Received:
    1
    You could try the following command to add line-number and color to grep's result.

    find /some/dir -name '*.txt' -exec grep --color -n 'searchstring' {} /dev/null \;
     
  6. Carpetsmoker

    Carpetsmoker Member

    Messages:
    938
    Thanks Received:
    136
  7. tankist02

    tankist02 Member

    Messages:
    102
    Thanks Received:
    1
    To speed up this command:

    find /some/dir -name '*.txt' -exec grep -li 'searchstring' {} \;

    I use xargs:

    find /some/dir -name '*.txt' | xargs grep -li 'searchstring'
     
  8. bb

    bb New Member

    Messages:
    42
    Thanks Received:
    9
    Even faster:

    Code:
    grep -lr --include "*.txt" 'searchstring' /some/dir
    


    Also, be aware that the grep tool uses a pattern for the search string. Make sure to understand the section REGULAR EXPRESSIONS of the grep manual page.

    If you want to avoid using patterns all together, use the -F switch like this:

    Code:
    grep -Flr --include "*.txt" 'searchstring' /some/dir