【问题标题】:#BASH - How can I: read input; var = grep $input; if $input = $var then#BASH - 我如何:读取输入; var = grep $输入;如果 $input = $var 那么
【发布时间】:2012-10-14 21:49:26
【问题描述】:

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

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 条件。

【问题讨论】:

  • 帮助我们和您用伪语言(或英语)解释您想要做什么,而不是编写难以理解的代码。谢谢。
  • 为什么是截图而不是实际代码?
  • 这不是代码,这是 bash 和虚构代码的混合体。
  • 不难理解;很难复制和编辑。如果您正在寻求帮助,您应该让人们轻松地为您提供帮助。
  • 用英语提出真正的问题肯定比显示损坏的代码更好。

标签: bash grep


【解决方案1】:
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 测试的退出状态的特殊命令。

【讨论】:

  • 非常感谢乔纳森!我唯一好奇的是为什么 "$i" 需要在引号中?
  • 在这种情况下,我是$i 不需要用引号引起来。但是,如果您永远不需要在grep 中使用特殊字符,例如()* ?{} 等,那么养成一个好习惯。 (注意那里也有一个空格。如果你有 light red 作为颜色,那么引号是必需的。)因此,许多 shell 脚本编写者会自动放置变量,而不是尝试决定是否需要它们逐案处理。
  • @JeremyJStarcher:如果用户在回答read i 提示时输入“天蓝色粉色”怎么办?
  • 试试看。在bash 提示符下键入read my_input; echo $my_input read 命令逐行运行。
  • 提醒一下,我刚刚意识到如果有人输入“ang”作为颜色,它将匹配“橙色”,因为所有 grep 命令都只进行部分匹配。阅读此内容以了解如何匹配整行:stackoverflow.com/questions/4709912/how-to-grep-the-exact-match
【解决方案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。

【讨论】:

  • 我肯定也会使用这些信息。非常感谢!
【解决方案3】:
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 澄清文本文件中的多种颜色之前编写的...

【讨论】:

  • 使用less 代替cat 甚至只是realcolour=$(<./color_readme.txt) 是不明智的。 less 专为交互使用而设计;当在输出不进入终端的情况下使用时,它会减少到 cat,就像在这个示例中,您将输入捕获在 shell 变量中。
  • 不考虑拼写错误,caPitAliSatIoN 的随机行为等,以上是我认为您要问的基本版本..?提供更多细节...
  • 非常感谢 Richard,我从来不知道 bash 有一个 until 命令!我只有 Windows cmd / 批处理文件的经验。
猜你喜欢
  • 2019-06-18
  • 2017-03-27
  • 2013-10-22
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 2012-02-13
相关资源
最近更新 更多