petr
petr

Reputation: 51

BASH -How easily determine how much is in a variable number of such characters

how easily determine how much is in a variable number of such characters

VAR="ddfasf♣dsdad ♣ as dsdsd  ♣  sadsd     ♣ df"
echo $VAR # result 4 

VAR="♣♣ as dsd♣sd  ♣  s♣adsd     ♣ df"
echo $VAR # result 5 

I tried this but it does not work :-(

echo "$(echo $VAR | tr -dc ♣ | wc -c)"

thank you very much

Upvotes: 0

Views: 50

Answers (2)

Scrutinizer
Scrutinizer

Reputation: 9926

Try:

chars=${VAR//[!♣]}
echo "${#chars}"

Upvotes: 1

suspectus
suspectus

Reputation: 17258

The option to delete all but the specified chars in tr is -C

  $(echo $VAR | tr -dC ♣ | wc -c)     

Upvotes: 0

Related Questions