我有一个名为“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/