Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

bash

shell

The problem is like this:

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 my problem is how do I use a simple shell/bash command that returns the number of times <item> occurs?

It looks simple but I just cannot find a good way around. Any ideas?

like image 932
linbianxiaocao Avatar asked Dec 07 '22 03:12

linbianxiaocao


1 Answers

You may try something like:

grep -o "<item>" a.xml | wc -l
like image 104
MillaresRoo Avatar answered Jun 07 '23 07:06

MillaresRoo