I've created a text file with 1000 random uppercase and lowercase letters:

cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 1000 > file1

How many times does the word 'cat' appear in this file, using grep and wc?

I did it this way:

grep -ic cat file1

But it counts lines in which it appears, while I want to check how many times it appears in that one line. Any idea?

  • fyi, tr can use [:alnum:] instead of the a-z... And you want to count how many times it appears in the whole file, not just on each line , or in just one particular line (you said "in that one line" at the end)? – Xen2050 Oct 21 '18 at 12:46

Work I have to do is find how many times in this file, appears world 'cat' using command grep and wc.


grep -oi cat file1 | wc -l


$ cat file1 
foo cat bar zoo cat
random text cat dog
foobar cat

^We have four occurances of cat above.

grep -oi cat file1 | wc -l

From man grep (my emphasis):

       -o, --only-matching
              Print  only  the  matched  (non-empty) parts of a matching line,
              with each such part on a separate output line.
  • The command above will find all substring cat even if they are part of other word like bobcat and catalougue. But the file is created so that it contains no space, nither word brake nither line break. Hence this is just a note. – schweik Oct 21 '18 at 19:02
  • @schweik Yes, that is true. I did not add any word boundaries to my answer. – maulinglawns Oct 22 '18 at 5:26

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.