'Counting the number of occurrences of the word [error] and [notice] in a log file

I am facing a small problem over here in Linux Ubuntu trying to count the number of occurrences of the words [error] and [notice] in a log file that I have over here. Here is what I have tried so far :

grep -o -i '[error]' apache.log | wc -l

Using grep and these options to count as if lines don't matter, and :

grep -o -i '[notice]' apache.log | wc -l

However, I don't arrive to the given answer, and I am not sure what is wrong with my command line, if someone could give me an input on all of this.

Thanks!



Solution 1:[1]

You need

grep -oi '\[notice]' apache.log | wc -l

Details:

  • -o - output matched texts only
  • -i - case insensitive matching
  • \[notice] - a literal [notice] string (since the pattern is parsed as a POSIX BRE pattern, you need to escape [).

Or, to match a fixed string pattern:

grep -oiF '[notice]' apache.log | wc -l

where -F will force grep to search for a fixed [notice] string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew