soField
soField

Reputation: 2686

count specific word in line in bash

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

Answers (7)

Mingyu
Mingyu

Reputation: 33349

echo '1,2,3' | grep -o ',' | wc -l

Upvotes: 0

Dennis Williamson
Dennis Williamson

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

camh
camh

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

ghostdog74
ghostdog74

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

SiegeX
SiegeX

Reputation: 140257

Off the top of my head using pure bash:

var="1,2,3,4"
temp=${var//[^,]/}
echo ${#temp}

Upvotes: 2

Alok Singhal
Alok Singhal

Reputation: 96111

This will do what you want:

echo "1,2,3" | tr -cd ',' | wc -c

Upvotes: 7

soulmerge
soulmerge

Reputation: 75704

Isolate commas per line, count lines:

echo "$VAR"|grep -o ,|wc -l

Upvotes: 1

Related Questions