我正在尝试读取一个文本文件sport.txt,它包含以下内容,并试图将用户输入与文本文件中的体育名称匹配。
如果找到了,就会打印“找到的运动”,如果找不到,就会打印“没有发现的运动”。
显示的第一个示例看起来几乎完美,直到我尝试输入一个随机单词,并显示了一个错误:
[:==:期望的一元运算符
在第二个示例中,我也尝试过使用""作为变量,但它只会打印“没有体育发现”,即使我在文本文件中使用体育名称键入了确切的体育名称。
文件sports.txt
cycling
swimming
batmintion代码(示例1)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [ $existingSports == $sportsName ]; then
echo "Sports Found"
else
echo "No Sports Found"
fi如果我在上述代码的基础上输入“游泳”,输出是:
体育发现
现在,如果我输入‘游泳’,输出是:
无体育发现
如果我随机输入一个单词'asd',输出是:
[:==:期望的一元运算符 无体育发现
代码(示例2)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [ "$existingSports" == "$sportsName" ]; then
echo "Sports Found"
else
echo "No Sports Found"
fi如果我在上述代码的基础上输入“游泳”,输出是:
无体育发现
现在,如果我输入‘游泳’,输出是:
无体育发现
代码(示例3)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [[ "$existingSports" == "$sportsName" ]]; then
echo "Sports Found"
else
echo "No Sports Found"
fi如果我在上述代码的基础上输入“游泳”,输出是:
无体育发现
现在,如果我输入‘游泳’,输出是:
无体育发现
如前所述,第一个例子几乎接近预期。我应该做些什么来消除错误信息?
发布于 2013-10-28 09:13:45
而不是这个块:
existingSports=$(grep $sportsName $file);
if [ $existingSports == $sportsName ]; then
echo "Sports Found"
else
echo "No Sports Found"
fi您只需使用grep -q和单词边界,并将代码简化为单行:
grep -q "\<$sportsName\>" "$file" && echo "Sports Found" || echo "No Sports Found"根据man grep
-q, --quiet, --silentQuiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected.
发布于 2013-10-28 09:07:30
试着用我的方式去做:
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
sportsName=`echo $sportsName | sed -e 's/^ *//g' -e 's/ *$//g'`
# The above sed command will remove all trailing and leading spaces which user can give as input
result=`grep -c $sportsName $file`;
if [ $result -eq 0 ]
then
echo "Sorry No match found"
else
echo "$result matches found"
figrep中的"-c“将计算出出现的次数,如果事件不是0,则会显示其他循环中出现的次数。
记住在grep命令上使用"`“tild签名
如果您正在寻找确切的单词,而不是其他单词的子字符串,那么在grep命令中使用-w -c:
result=`grep -w -c $sportsName $file`;man条目用于-w
-w, --word-regexp
Select only those lines containing matches that form whole
words. The test is that the matching substring must either
be at the beginning of the line, or preceded by a non-word
constituent character. Similarly, it must be either at the
end of the line or followed by a non-word constituent
character. Word-constituent characters are letters,
digits, and the underscore.https://stackoverflow.com/questions/19630619
复制相似问题