Search only text files with 'find' command?

Discussion in 'Command Line' started by airStar, Sep 8, 2012.

  1. airStar

    airStar New Member

    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    I've been using this to search an entire directory recursively for a specific phrase in my code (html, css, php, javascript, etc.):


    Code:
    find dir_name -type f -exec grep -l "phrase" {} \;
    The problem is that it searches ALL files in the directory 'dir_name', even binary ones such as large JPEG images. With a directory also containing large number of images dispersed everywhere, it dramatically reduces the efficiency. Sometimes it takes very long to get a response.

    Is there any parameter I can easily use to make it only search text files?
  2. eyal_tst

    eyal_tst New Member

    Messages:
    15
    Likes Received:
    3
    Trophy Points:
    3
    You could use the 'file' command.
    It tells you what kind of file is any particular file.
    So, if you add it to your find, and then grep the kind of files you want (or grep -v those that you don't), you can filter your list.

    Or you could first get a list of those files that you want (with 'file') and then grep the text only from those.
  3. KenJackson

    KenJackson Active Member

    Messages:
    129
    Likes Received:
    28
    Trophy Points:
    28
    If the text files all have the same extension, you can easily add the -name switch, like this:
    Code:
    find dir_name -type f -name \*.txt -exec grep -l "phrase" {} \;
    If they they're not so conveniently named, you could do messy stuff like this:
    Code:
    find dir_name -type f \( -name \*.txt -o -name '*some-name*' -o '*other*' \) -exec grep -l "phrase" {} \;
    I got so tired of messing with the find that I wrote a wrapper script, findls, that I use instead.
    To use it, you would do something like this:
    Code:
    findls dir_name \*.txt -gl "phrase"

Share This Page