Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String Bash:计算一个句子中字符串的出现次数_String_Bash - Fatal编程技术网

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