Count all occurrences of a string in lots of files with grep

前端 未结 15 1558
广开言路
广开言路 2020-11-28 01:07

I have a bunch of log files. I need to find out how many times a string occurs in all files.

grep -c string *

returns

...
f         


        
相关标签:
15条回答
  • 2020-11-28 01:33

    You can use a simple grep to capture the number of occurrences effectively. I will use the -i option to make sure STRING/StrING/string get captured properly.

    Command line that gives the files' name:

    grep -oci string * | grep -v :0
    

    Command line that removes the file names and prints 0 if there is a file without occurrences:

    grep -ochi string *
    
    0 讨论(0)
  • 2020-11-28 01:37

    Instead of using -c, just pipe it to wc -l.

    grep string * | wc -l
    

    This will list each occurrence on a single line and then count the number of lines.

    This will miss instances where the string occurs 2+ times on one line, though.

    0 讨论(0)
  • 2020-11-28 01:37

    Grep only solution which I tested with grep for windows:

    grep -ro "pattern to find in files" "Directory to recursively search" | grep -c "pattern to find in files"
    

    This solution will count all occurrences even if there are multiple on one line. -r recursively searches the directory, -o will "show only the part of a line matching PATTERN" -- this is what splits up multiple occurences on a single line and makes grep print each match on a new line; then pipe those newline-separated-results back into grep with -c to count the number of occurrences using the same pattern.

    0 讨论(0)
  • 2020-11-28 01:40

    This works for multiple occurrences per line:

    grep -o string * | wc -l
    
    0 讨论(0)
  • 2020-11-28 01:40

    Something different than all the previous answers:

    perl -lne '$count++ for m/<pattern>/g;END{print $count}' *
    
    0 讨论(0)
  • 2020-11-28 01:43

    You can add -R to search recursively (and avoid to use cat) and -I to ignore binary files.

    grep -RIc string .
    
    0 讨论(0)
提交回复
热议问题