Javier Salas Javier Salas - 2 years ago 72
Bash Question

Count of matching word, pattern or value from unix korn shell scripting is returning just 1 as count

I'm trying to get the count of a matching pattern from a variable to check the count of it, but it's only returning 1 as the results, here is what I'm trying to do:

echo $x | grep -c "|"

Expected result: 3

Actual Result: 1

Do you know why is returning 1 instead of 3?


Answer Source

grep -c counts lines not matches within a line.

You can use awk to get a count:


echo "$x" | awk -F '|' '{print NF-1}'


Alternatively you can use tr and wc:

echo "$x" | tr -dc '|' | wc -c

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download