Home > Software engineering >  Linux counting words in random characters
Linux counting words in random characters

Time:10-31

I have generated a file of random characters for A-Z and a-z, the file has different sizes for example 10000 characters or 1000000 I would like to search in them how many times the word 'cat' or 'dog' appeared Would someone be able to provide the command linux grep... | wc... or any other command that can handle this task.

CodePudding user response:

grep has a -c command that will count the number of matches found.

So

grep -c "cat\|dog" <file name>

add -i if you want a case insensitive count

CodePudding user response:

You can use grep with the flag -o. For example:

grep -o "dog\|cat" <filename> | wc -l

About the flag -o, according to man grep: «Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.»

This solution will work in several situations: multiple lines, a single line, the word surrounded with whitespaces or other characters, etc.

  • Related