【问题标题】:BASH shell script searching and displaying a patternBASH shell 脚本搜索和显示模式
【发布时间】:2018-03-25 20:41:28
【问题描述】:

我正在尝试创建一个 BASH shell 脚本,在该脚本中提示用户输入动物,并返回“$animal 有(我在 case 语句中设置的数字)腿”

我为此使用了 case 语句。我目前的陈述如下:

#!/bin/bash

echo -n "Enter an animal: "
read animal

case $animal in
spider|octopus) echo "The $animal has 8 legs";;
horse|dog) echo "The $animal has 4 legs";;
kangaroo|person) echo "The $animal has 2 legs";;
cat|cow) echo "The $ animal has 4 legs";;
*) echo "The $animal has an unknown number of legs"
esac

对于猫或牛,我需要能够回显“(xyz)(猫或牛)有 4 条腿”我正在考虑在某处使用 grep,但不知道这是否是最佳选择这个。有人可以帮忙吗?

谢谢!

【问题讨论】:

  • $ animal 替换为$animal
  • 真的,case 语句只需要为每个类别设置n=8n="an unknown number of" 等内容。之后,你可以有一个语句 `echo "The $animal has $n leg"。
  • @Cyrus 谢谢你 - 没意识到我错过了

标签: bash shell unix grep


【解决方案1】:

chepner's suggestion:

#!/bin/bash

echo -n "Enter an animal: "
read -r animal

case $animal in
  spider|octopus)       n=8;;
  horse|dog)            n=4;;
  kangaroo|person)      n=2;;
  cat|cow)              n=4;;
  *)                    n="an unknown number of"
esac

echo "The $animal has $n legs"

【讨论】:

  • 如果我在提示输入动物时输入“汤姆猫”,目标是能够显示“汤姆猫有 4 条腿”。或者如果我输入brown cow,我应该可以显示“brown cow有4条腿”
【解决方案2】:

似乎添加 *cat|*cow) 而不是 cat|cow) 不需要 grep。谢谢

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-23
    相关资源
    最近更新 更多