tags:

views:

165

answers:

6

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

+1  A: 

Isolate commas per line, count lines:

echo "$VAR"|grep -o ,|wc -l
soulmerge
+4  A: 

This will do what you want:

echo "1,2,3" | tr -cd ',' | wc -c
Alok
thanks exactly what i want ;)
soField
Did not know of that tr -c usage, nice
Alberto Zaccagni
actually tr -cd is doing this job well :)
soField
+1  A: 

Off the top of my head using pure bash:

var="1,2,3,4"
temp=${var//[^,]/}
echo ${#temp}
SiegeX
Change the second line to: `temp=${var//[^,]/}` then it removes any non-comma.
Dennis Williamson
Good call, thanks for the reminder
SiegeX
A: 

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.

camh
The eval and single quotes are unnecessary.
Dennis Williamson
@Dennis: Ok. I got rid of them.
camh
A: 

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.

Dennis Williamson
Doesn't work with `var="1,2,3"` (seems to work only if there's a trailing comma).
Alok
@Alok: Thanks for pointing that out. It's now fixed. I like **SiegeX's** version better, though.
Dennis Williamson
A: 

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
ghostdog74