String Bash:计算一个句子中字符串的出现次数
我只想计算一个特定字符串的出现次数。这是我的代码:String Bash:计算一个句子中字符串的出现次数,string,bash,String,Bash,我只想计算一个特定字符串的出现次数。这是我的代码: 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 不幸的是,这是我的输出:
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
我在字符串比较步骤中出错。我只是搜索了一下,发现了。我相信我也这样做了。这里的错误是什么?
[
是一个普通的shell命令。与所有命令一样,您需要在命令名和参数之间留出一个空格:
if [ "$word" == my-code ]; then
它还要求
]
是一个单独的参数,以便它在结尾处忽略它。您有许多语法错误,如[
之后和]
之前以及==
周围的空格等
但是,您可以通过使用tr
完成工作来避免循环:
tr ' ' '\n' <<< "$output" | grep -c 'my-code'
2
tr''\n'grep-o'my code'input.txt | wc-l