Search code examples
bashshellgrep

use grep to count the number of times a word got repeated in a file


For instance, I have a file "a.xml". Inside this file it is just one line as

<queue><item><cause><item>

I want to find how many times <item> occurs, and in this case it is 2.

However, if I run:

grep -c "<item>" a.xml 

It will only give me 1 because grep stops as soon as it matches the first <item>.

So the problem is how to use a simple shell/bash command that returns the number of times <item> occurs?


Solution

  • You may try something like:

    grep -o "<item>" a.xml | wc -l