vendredi 27 mars 2015

Bash: count the occurrence of a string within a sentence

I just wanted to count the occurrence of a particular string. This is my code:



count=0
output="hai how are you ? my-code is incorrect. Do you have a new my-code ?"
echo $output

for word in $output
do
if ["$word" == "my-code"];then
count=$((count + 1))
fi
done

echo $count


Sadly, this is my output :



hai how are you ? my-code is incorrect. Do you have a new my-code ?
./test.sh: line 7: [hai: command not found
./test.sh: line 7: [how: command not found
./test.sh: line 7: [are: command not found
./test.sh: line 7: [you: command not found
./test.sh: line 7: [?: command not found
./test.sh: line 7: [my-code: command not found
./test.sh: line 7: [is: command not found
./test.sh: line 7: [incorrect.: command not found
./test.sh: line 7: [Do: command not found
./test.sh: line 7: [you: command not found
./test.sh: line 7: [have: command not found
./test.sh: line 7: [a: command not found
./test.sh: line 7: [new: command not found
./test.sh: line 7: [my-code: command not found
./test.sh: line 7: [?: command not found
0


I am getting error at the string comparison step. I just searched and came across this. I believe I have done the same. What's the bug here?


Aucun commentaire:

Enregistrer un commentaire