Reputation: 1009
I have this associative array:
lettres['A']=0
…(from 'A' to 'Z')…
lettres['Z']=0
My question is simple: How to take the value of one element and increment it? I have tried the following:
lettres[$char]=${lettres[$char]}++
But it fails, as the result is «0++++++++». How can I easily increment the value?
EDIT: More code:
while (( i++ < ${#word} )); do
#$char current char
char=$(expr substr "$word" $i 1)
if [[ "${mot[@]}" =~ "${char} " || "${mot[${#mot[@]}-1]}" == "${char}" ]]; then
#char is currently in array $mot -> skipping
echo 'SKIPPING'
else
#Char is not in array $mot -> adding + incrementing lettres
((lettres[char]++))
echo ${lettres[$char]}
#Adding to $mot
mot[${#mot[@]}]=$char
fi
echo "<$char>"
done
Upvotes: 3
Views: 5622
Reputation: 74685
Using bash version 4 and up, this would work:
$ declare -A lettres
$ char=B
$ ((lettres[$char]++))
$ echo "${lettres['A']}"
0
$ echo "${lettres['B']}"
1
The (( ))
force an arithmetic context, in which you can increment the value of the array element. Note that it is also recommended to use declare -A
to guarantee maximum backward compatibility with standard indexed arrays.
Upvotes: 10