How do I count the number of occurance of '_&#

2019-07-20 00:58发布

问题:

I would like to count the number of time '_' (under score) is appearing in my file name. How do I do that?

回答1:

echo $filename | tr -c -d _ | wc -c


回答2:

I'd use tr.

$ echo "8979858774_/hkjhjkh_kjh.hjghjg/_jhkj/_/" | tr -d _ -c | wc -c
   4


回答3:

Another variation:

echo "$filename" | grep -o _ | wc -l

Or for shells that support this, such as Bash, ksh and zsh:

u=${filename//_}
echo $((${#filename} - ${#u}))


回答4:

Probably not the most elegant or perfect solution, but should do the trick:

echo $filename|split -C 1 - /tmp/foobar
grep -l '_' /tmp/foobar* |wc -l
rm /tmp/foobar*


标签: shell unix