Search code examples
unixgrepwc

Unix: How can I count all lines containing a string in all files in a directory and see the output for each file separately


In UNIX I can do the following:

grep -o 'string' myFile.txt | wc -l

which will count the number of lines in myFile.txt containing the string. Or I can use :

grep -o 'string' *.txt | wc -l

which will count the number of lines in all .txt extension files in my folder containing the string. I am looking for a way to do the count for all files in the folder but to see the output separated for each file, something like:

myFile.txt 10000

myFile2.txt 20000

myFile3.txt 30000

I hope I have made my self clear, if not you can see a somewhat close example in the output of :

wc -l *.txt

Solution

  • Why not simply use grep -c which counts matching lines? According to the GNU grep manual it's even in POSIX, so should work pretty much anywhere.

    Incidentally, your use of -o makes your commands count every occurence of the string, not every line with any occurences:

    $ cat > testfile
    hello hello
    goodbye
    $ grep -o hello testfile
    hello
    hello
    

    And you're doing a regular expression search, which may differ from a string search (see the -F flag for string searching).