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
    Likes 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
    Likes Received:
    0
    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,672
    Likes Received:
    26
    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,416
    Likes Received:
    13
    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
    Likes Received:
    0
    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:
    933
    Likes Received:
    5
  7. tankist02

    tankist02 Member

    Messages:
    100
    Likes Received:
    0
    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
    Likes Received:
    0
    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