linux - 如何在linux中检查 'if-then-else-fi'中的多个字符串?

标签 linux bash shell unix

我有一个名为“testfile”的文件,其中包含:

Computer Science   123 Congress Street,
Biology            2 New York Ave,
Graduate Center    1 New York Ave

我有一个名为“search”的脚本,如下所示:

grep $* testfile
____________________                 # line 2
then echo "there is a match"         # message 1
else echo "no such department found" # message 2
fi

它应该为“计算机科学”、“生物学”和“研究生中心”部门打印“有匹配项”。如果没有上述部门,则“未找到该部门”。

所以我正在尝试#line2。 我对此有几个问题:

(1) 是否可以在“if”内再次写入“grep”?例如我可以这样写吗

if grep -q Biology "$testfile"

。如果是,我如何测试所有字符串(在本例中为“部门”)?

(2) 我知道我是否只使用 grep 来查找我所说的多个字符串

grep 'string1\|string2\|string3' PATH

或者

egrep -w 'string1|string2' PATH

但是我可以在 if 语句中使用这种格式吗?如果是,怎么办?

(3) 这样可以吗? :

if ["$"=="Computer Science"] || ["$"=="Biology"] || ["$"=="Graduate Center"]

谁能帮我解答一下我的疑问吗?

最佳答案

shell if语句采用任意 shell 命令then如果该命令(无论它是什么)成功退出,则子句将被执行;否则,else条款将被执行。所以你的第一个问题的答案是,是的,你可以写 if grep -q 'pattern' testfile ,你也可以写 if egrep -qw 'string1|string2' testfile ,你甚至可以写 if perl -ne '(hundreds of lines of code here)' testfile如果你真的想要的话。

如果我理解正确,您的脚本将字符串列表作为参数,并且您希望它在所有字符串匹配时打印“存在匹配项”。我会这样做:

success=y
for arg in "$@"
do
  if grep -qF "$arg" "$testfile"
  then :
  else
    printf 'no match for %s\n' "$arg"
    success=n
  fi
done
if [ "$success" = "y" ]; then
  printf 'all strings matched\n'
fi

(then :; else ... 构造是反转 shell if 语句含义的唯一可移植方式;if ! ... 是 bashism。如果您不关心最大可移植性,请不要编写 shell 脚本;Perl 比 Bash 更可能跨平台可用。-q-F grep 的参数也不是完全可移植的, printf 也不是完全可移植的,但自 2000 年代中期以来,我还没有被没有它们的系统绊倒。)

关于linux - 如何在linux中检查 'if-then-else-fi'中的多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24896314/

相关文章:

linux - 如何在 Linux 中使用 bash 从文本文件中提取行?

linux - 无法拉取 .vim/目录

Linux Bash Shell 读取日志文件将每一行与文件的重置进行比较

linux - 如何在 sudo 命令后执行多个命令

bash - 如何在 bash shell 中给出变量路径?

linux - 在bash中创建一个zenity菜单

c++ - 不使用退格键替换 Linux 终端中的文本

linux - 如何使 bond0/eth0 接口(interface) UP

bash - shell脚本: Is there a way to use variable as output instead of a file for executable?

bash - 从完整路径中获取 Unix 中的文件名