How do I find files that do not contain a given string pattern?

后端 未结 16 1314
半阙折子戏
半阙折子戏 2020-11-28 17:42

How do I find out the files in the current directory which do not contain the word foo (using grep)?

16条回答
  •  佛祖请我去吃肉
    2020-11-28 17:54

    Problem

    I need to refactor a large project which uses .phtml files to write out HTML using inline PHP code. I want to use Mustache templates instead. I want to find any .phtml giles which do not contain the string new Mustache as these still need to be rewritten.

    Solution

    find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'

    Explanation

    Before the pipes:

    Find

    find . Find files recursively, starting in this directory

    -iname '*.phtml' Filename must contain .phtml (the i makes it case-insensitive)

    -exec 'grep -H -E -o -c 'new Mustache' {}' Run the grep command on each of the matched paths

    Grep

    -H Always print filename headers with output lines.

    -E Interpret pattern as an extended regular expression (i.e. force grep to behave as egrep).

    -o Prints only the matching part of the lines.

    -c Only a count of selected lines is written to standard output.


    This will give me a list of all file paths ending in .phtml, with a count of the number of times the string new Mustache occurs in each of them.

    $> find . -iname '*.phtml$' -exec 'grep -H -E -o -c 'new Mustache' {}'\;
    
    ./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
    ./app/MyApp/Customer/View/Account/studio.phtml:0
    ./app/MyApp/Customer/View/Account/orders.phtml:1
    ./app/MyApp/Customer/View/Account/banking.phtml:1
    ./app/MyApp/Customer/View/Account/applycomplete.phtml:1
    ./app/MyApp/Customer/View/Account/catalogue.phtml:1
    ./app/MyApp/Customer/View/Account/classadd.phtml:0
    ./app/MyApp/Customer/View/Account/orders-trade.phtml:0
    

    The first pipe grep :0$ filters this list to only include lines ending in :0:

    $> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$
    
    ./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml:0
    ./app/MyApp/Customer/View/Account/studio.phtml:0
    ./app/MyApp/Customer/View/Account/classadd.phtml:0
    ./app/MyApp/Customer/View/Account/orders-trade.phtml:0
    

    The second pipe sed 's/..$//' strips off the final two characters of each line, leaving just the file paths.

    $> find . -iname '*.phtml' -exec grep -H -E -o -c 'new Mustache' {} \; | grep :0$ | sed 's/..$//'
    
    ./app/MyApp/Customer/View/Account/quickcodemanagestore.phtml
    ./app/MyApp/Customer/View/Account/studio.phtml
    ./app/MyApp/Customer/View/Account/classadd.phtml
    ./app/MyApp/Customer/View/Account/orders-trade.phtml
    

提交回复
热议问题