grep, but only certain file extensions

前端 未结 12 2469
野性不改
野性不改 2020-12-02 03:18

I am working on writing some scripts to grep certain directories, but these directories contain all sorts of file types.

I want to grep jus

相关标签:
12条回答
  • 2020-12-02 03:41

    There is no -r option on HP and Sun servers, this way worked for me on my HP server

    find . -name "*.c" | xargs grep -i "my great text"
    

    -i is for case insensitive search of string

    0 讨论(0)
  • 2020-12-02 03:48

    If you want to filter out extensions from the output of another command e.g. "git":

    files=$(git diff --name-only --diff-filter=d origin/master... | grep -E '\.cpp$|\.h$')
    
    for file in $files; do
        echo "$file"
    done
    
    0 讨论(0)
  • 2020-12-02 03:49

    The below answer is good:

    grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com
    

    But can be updated to:

    grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] | mailx -s GREP email@domain.com
    

    Which can be more simple.

    0 讨论(0)
  • 2020-12-02 03:51
    grep -rnw "some thing to grep" --include=*.{module,inc,php,js,css,html,htm} ./
    
    0 讨论(0)
  • 2020-12-02 03:52

    I am aware this question is a bit dated, but I would like to share the method I normally use to find .c and .h files:

    tree -if | grep \\.[ch]\\b | xargs -n 1 grep -H "#include"
    

    or if you need the line number as well:

    tree -if | grep \\.[ch]\\b | xargs -n 1 grep -nH "#include"
    
    0 讨论(0)
  • 2020-12-02 03:54

    Since this is a matter of finding files, let's use find!

    Using GNU find you can use the -regex option to find those files in the tree of directories whose extension is either .h or .cpp:

    find -type f -regex ".*\.\(h\|cpp\)"
    #            ^^^^^^^^^^^^^^^^^^^^^^^
    

    Then, it is just a matter of executing grep on each of its results:

    find -type f -regex ".*\.\(h\|cpp\)" -exec grep "your pattern" {} +
    

    If you don't have this distribution of find you have to use an approach like Amir Afghani's, using -o to concatenate options (the name is either ending with .h or with .cpp):

    find -type f \( -name '*.h' -o -name '*.cpp' \) -exec grep "your pattern" {} +
    #            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    And if you really want to use grep, follow the syntax indicated to --include:

    grep "your pattern" -r --include=*.{cpp,h}
    #                      ^^^^^^^^^^^^^^^^^^^
    
    0 讨论(0)
提交回复
热议问题