grep, but only certain file extensions

前端 未结 12 2470
野性不改
野性不改 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

    ag (the silver searcher) has pretty simple syntax for this

           -G --file-search-regex PATTERN
              Only search files whose names match PATTERN.
    

    so

    ag -G *.h -G *.cpp CP_Image <path>
    
    0 讨论(0)
  • 2020-12-02 03:59

    Should write "-exec grep " for each "-o -name "

    find . -name '*.h' -exec grep -Hn "CP_Image" {} \; -o -name '*.cpp' -exec grep -Hn "CP_Image" {} \;
    

    Or group them by ( )

    find . \( -name '*.h' -o -name '*.cpp' \) -exec grep -Hn "CP_Image" {} \;
    

    option '-Hn' show the file name and line.

    0 讨论(0)
  • 2020-12-02 04:00

    Just use the --include parameter, like this:

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

    that should do what you want.

    To take the explanation from HoldOffHunger's answer below:

    • grep: command

    • -r: recursively

    • -i: ignore-case

    • -n: each output line is preceded by its relative line number in the file

    • --include \*.cpp: all *.cpp: C++ files (escape with \ just in case you have a directory with asterisks in the filenames)

    • ./: Start at current directory.

    0 讨论(0)
  • 2020-12-02 04:04

    Some of these answers seemed too syntax-heavy, or they produced issues on my Debian Server. This worked perfectly for me:

    grep -r --include=\*.txt 'searchterm' ./
    

    ...or case-insensitive version...

    grep -r -i --include=\*.txt 'searchterm' ./
    
    • grep: command

    • -r: recursively

    • -i: ignore-case

    • --include: all *.txt: text files (escape with \ just in case you have a directory with asterisks in the filenames)

    • 'searchterm': What to search

    • ./: Start at current directory.

    Source: PHP Revolution: How to Grep files in Linux, but only certain file extensions?

    0 讨论(0)
  • 2020-12-02 04:04

    How about:

    find . -name '*.h' -o -name '*.cpp' -exec grep "CP_Image" {} \; -print
    
    0 讨论(0)
  • 2020-12-02 04:04

    The easiest way is

    find . -type  f -name '*.extension' | xargs grep -i string 
    
    0 讨论(0)
提交回复
热议问题