I want to find out the occurrence of a keyword group by filename inside a directory.

Keyword - TEST (means TEST1, TEST2, etc. can be valid results)
Files - a.txt, b.txt etc. (inside a directory .. /tmp).

Output will be as follows.

a.txt - 4
b.txt - 5
c.txt - 0

I tried with grep -o "TEST" a.txt and this gives only TEST and its occurrences; like if a file has 3 occurrences (like TEST1, TEST_XXX, TESTXYES) the output will be


OR if multiple files search is not possible then OUTPUT should provide all the similar string starting TEST; for example,


I tried the following, too.

grep -c "TEST" a.txt

but this gives only the count; it does not give what was the entire text starting with TEST.

  • For keyword TEST does it count if it's found in RETESTS? What about in Testament?
    – roaima
    Nov 14 '18 at 7:29
  • 1
    I modified your question, tried making it readable, but you should really edit the question by yourself because it is still hard to understand what exactly you are asking for.
    – jimmij
    Nov 14 '18 at 7:29
  • 1
    Thank you for showing us what you’ve tried.   But it doesn’t help much if we don’t understand what result you want.   Your title says “get its count”, and, in the first few lines, you say you want output like a.txt - 4 / b.txt - 5 / c.txt - 0.   But then when you tried grep -c (which should be the right answer), you complain that it gives only the count.   What result do you want?  Please do not respond in comments; edit your question to make it clearer and more complete. Nov 14 '18 at 19:33

The grep -c prints number of matching lines, so you won't get right result in combination with -o option. I would pipe the output of grep -o to uniq -c:

$ echo 'test1 test2 test3' >/tmp/file1
$ echo 'test1 test2 test3 test4' >/tmp/file2
$ grep -o test /tmp/file* | uniq -c
  3 /tmp/file1:test
  4 /tmp/file2:test

You can pipe it further to modify the output with some text-processing tools.

  • It seems like the user wants to see the full names TEST_1, TEST_2, etc. so they may not want the -o option for grep at all.
    – jesse_b
    Nov 15 '18 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.