Reputation: 2686
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
Upvotes: 6
Views: 6511
Reputation: 359955
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.
Upvotes: 0
Reputation: 42438
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.
Upvotes: 0
Reputation: 342323
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
Upvotes: 0
Reputation: 140257
Off the top of my head using pure bash:
var="1,2,3,4"
temp=${var//[^,]/}
echo ${#temp}
Upvotes: 2
Reputation: 96111
This will do what you want:
echo "1,2,3" | tr -cd ',' | wc -c
Upvotes: 7
Reputation: 75704
Isolate commas per line, count lines:
echo "$VAR"|grep -o ,|wc -l
Upvotes: 1