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

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


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 > testfilehello hellogoodbye$ grep -o hello testfilehellohello

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


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.