How do we exactly count the occurrence of a particular character in a string in bash scripting? Well, there’s quite a number of ways of doing this. Here’s the simplest that I know of.

no_fields=`echo "a|b|c " |awk -F"|" '{print NF}' `
echo $no_fields

What the hell this means? Here’s the simple explanation.
1. echo "a|b|c" – output the string
2. -F"|" – change the field separator into pipe
3. '{print NF}' – prints the number of files in the string based on the separator set by -F.

Source :
http://www.unix.com/unix-advanced-expert-users/25978-how-count-no-occurences-character-string-unix.html

Comments are closed.

Post Navigation