i have variable such as "1,2,3,4"
i want to count of commas in this text in bash
any idea ?
thanks for help
i have variable such as "1,2,3,4"
i want to count of commas in this text in bash
any idea ?
thanks for help
Isolate commas per line, count lines:
echo "$VAR"|grep -o ,|wc -l
Off the top of my head using pure bash:
var="1,2,3,4"
temp=${var//[^,]/}
echo ${#temp}
A purely bash solution with no external programs:
$ X=1,2,3,4
$ count=$(( $(IFS=,; set -- $X; echo $#) - 1 ))
$ echo $count
3
$
Note: This destroys your positional parameters.
Another pure Bash solution:
var="bbb,1,2,3,4,a,b,qwerty,,,"
saveIFS="$IFS"
IFS=','
var=($var)x
IFS="$saveIFS"
echo $((${#var[@]} - 1))
will output "10" with the string shown.
very simply with awk
$ echo 1,2,3,4 | awk -F"," '{print NF-1}'
3
with just the shell
$ s="1,2,3,4"
$ IFS=","
$ set -- $s
$ echo $(($#-1))
3