Ravid Goldenberg
Ravid Goldenberg

Reputation: 2319

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

Upvotes: 4

Views: 6320

Answers (2)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16120

Use a loop over all files, something like

for f in *.txt; do echo -n $f $'\t'; echo grep 'string' "$f" | wc -l; done

But I must admit that @Yann's grep -c is neater :-). The loop can be useful for more complicated things though.

Upvotes: 1

Yann Vernier
Yann Vernier

Reputation: 15887

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).

Upvotes: 6

Related Questions