Javier Salas Javier Salas - 3 months ago 10
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:

x="HELLO|THIS|IS|TEST"
echo $x | grep -c "|"


Expected result: 3

Actual Result: 1

Do you know why is returning 1 instead of 3?

Thanks.

Answer

grep -c counts lines not matches within a line.

You can use awk to get a count:

x="HELLO|THIS|IS|TEST"

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

3

Alternatively you can use tr and wc:

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

3
Comments