2

以下を含むテキスト ファイルsport.txtを読み込もうとしています。ユーザー入力をテキスト ファイルにあるスポーツ名と一致させようとしています。

見つかった場合は「スポーツが見つかりました」と出力され、見つからなかった場合は「スポーツが見つかりません」と出力されます。

最初に示した例は、ランダムな単語をキー入力しようとしてエラーが表示されるまでは、ほぼ完璧に見えます。

[: ==: 単項演算子が必要です

2 番目の例の変数にも を使用して""みましたが、テキスト ファイルのスポーツ名と正確に一致するスポーツ名を入力したにもかかわらず、「スポーツが見つかりません」と出力されます。

ファイル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

上記のコードで「水泳」ベースをキー入力すると、出力は次のようになります。

スポーツファウンド

「swim」とキー入力すると、出力は次のようになります。

スポーツが見つかりません

そして、ランダムな単語「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

上記のコードに基づいて「水泳」ベースをキー入力すると、出力は次のようになります。

スポーツが見つかりません

「swim」とキー入力すると、出力は次のようになります。

スポーツが見つかりません

コード (例 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

上記のコードで「水泳」ベースをキー入力すると、出力は次のようになります。

スポーツが見つかりません

「swim」とキー入力すると、出力は次のようになります。

スポーツが見つかりません

前述のように、最初の例は予想にほぼ近いものです。エラーメッセージを取り除くにはどうすればよいですか?

4

2 に答える 2

2

私のやり方でやってみてください:

 #!/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"
 fi

grep の「-c」は発生回数をカウントし、発生回数が 0 でない場合は、 elseループの発生回数を示します。

grep コマンドでチルド記号「`」を使用することを忘れないでください

正確な単語を探していて、他の単語の部分文字列ではない場合-w -cは、grep コマンドで使用します。

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.
于 2013-10-28T09:07:30.533 に答える