我只想计算特定字符串的出现次数。这是我的代码:
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
可悲的是,这是我的输出:
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
我在字符串比较步骤中遇到错误。我只是搜索并遇到了this。我相信我也做了同样的事情。这里的错误是什么?
答案 0 :(得分:1)
[
是一个普通的shell命令。与所有命令一样,您需要在命令名称和参数之间放置一个空格:
if [ "$word" == my-code ]; then
它还要求]
是一个单独的参数,以便在最后忽略它。
答案 1 :(得分:1)
您有许多语法错误,例如[
之后和]
之前以及==
之后的空格等。
但是,您可以使用tr
来完成工作来避免循环:
tr ' ' '\n' <<< "$output" | grep -c 'my-code'
2