grep, but only certain file extensions

前端 未结 12 2468
野性不改
野性不改 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: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}
    #                      ^^^^^^^^^^^^^^^^^^^
    

提交回复
热议问题