[:==:一元运算符expected-bash

时间:2013-10-28 09:02:10

标签: bash shell

我正在尝试阅读文本fiie 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

如果我根据上述代码键入'游泳'

输出

Sports Found

现在如果我输入'swim'

输出

No Sports Found

如果我输入一个随机单词'asd'

输出

[: ==: unary operator expected
No Sports Found

代码(示例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

如果我根据上述代码键入'游泳'

输出

No Sports Found

现在如果我输入'swim'

输出

No Sports Found

代码(示例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

如果我根据上述代码键入'游泳'

输出

No Sports Found

现在如果我输入'swim'

输出

No Sports Found

如前所述,第一个例子几乎接近。我该怎么做才能摆脱错误消息?

2 个答案:

答案 0 :(得分:2)

尝试按我的方式进行

 #!/bin/bash
 file="sports.txt"
read -p "Enter a sports name": sportsName
 sportsName=`echo $sportsName | sed -e 's/^ *//g' -e 's/ *$//g'`
 #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"
 fi 
grep中的

“ - c”将计算出现次数,如果出现次数不为0则显示else循环中出现的次数

记得在grep命令上使用“`”tild登录

如果您正在查找确切的单词而不是其他单词的子字符串,请在grep命令中使用-w -c

result=`grep -w -c $sportsName $file`;

-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  con-
      stituent  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.

答案 1 :(得分:2)

而不是这个块:

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, --silent

     

Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected.