1

我想比较用户在这个文本文件中输入的内容,以确定他们输入的内容是否在文本文件中,然后告诉他们。

file1: color_readme.txt 在这个文件中是:

red
red
orange
blue

代码:

echo Please enter a color:
cat color_readme.txt (printing the colors to screen)
read userinput (read what the user enters)
variable1 = grep $userinput (a random variable = what is found in the file according to what the user typed)
if userinput = variable1 (SAY THIS)
else (SAY THIS)

对于初学者来说,最好的方法是什么?我的老师只希望我使用基本的 ifelse 和 else 条件。

4

3 回答 3

4
echo "Pick one of the colours below:"
cat colour_readme.txt
read i
if x=$(grep "$i" colour_readme.txt)
then echo "You picked $i and it appears in colour_readme.txt as $x"
else echo "You picked $i but it does not appear in colour_readme.txt"
fi

您可以在不使用test(或[[[)运算符的情况下测试命令的状态;它们只是返回退出状态的特殊命令,可以通过if.

于 2012-10-14T21:58:33.800 回答
2
answer="Wrong"
realcolour=`cat ./color_readme.txt`

Until [ $answer = "Correct" ] ; Do
echo -n "Please enter a colour:"
read usercolour

If [ $usercolour = $realcolour ] ; Then
     answer="Correct"
Else
     answer="Wrong"
Fi

echo $answer
Done

编辑:...上面是在 OP 澄清文本文件中的多种颜色之前编写的...

于 2012-10-14T21:58:28.227 回答
2
echo "name a color"
read i
grep -q $i color.txt
if [ $? == 0 ]
then
echo "$i is in the file"
else
echo "$i is not in the file"
fi

"if [ $? == 0 ]" 测试前一个命令的退出状态,在本例中是 grep。如果 grep 找到了某些东西,它的退出状态将为 0,如果没有,则退出状态为 1。

于 2012-10-14T22:10:52.177 回答