如何在';如果是,则为fi';在linux中?

如何在';如果是,则为fi';在linux中?,linux,bash,shell,unix,Linux,Bash,Shell,Unix,我有一个名为“testfile”的文件,其中包含: Computer Science 123 Congress Street, Biology 2 New York Ave, Graduate Center 1 New York Ave 我有一个名为“搜索”的脚本,如下所示: grep $* testfile ____________________ # line 2 then echo "there is a match"

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

Computer Science   123 Congress Street,
Biology            2 New York Ave,
Graduate Center    1 New York Ave
我有一个名为“搜索”的脚本,如下所示:

grep $* testfile
____________________                 # line 2
then echo "there is a match"         # message 1
else echo "no such department found" # message 2
fi
它应该打印“计算机科学”、“生物学”和“研究生中心”部门的“有一个匹配”。如果没有上述部门,则“未发现此类部门”

所以我在试第二行。 关于这一点,我有几个问题:

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

如果grep-q Biology“$testfile”

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

(2) 我知道如果我只使用grep来查找多个字符串

grep'string1\| string2\| string3'路径

白鹭-w’string1 | string2’路径

但是我可以在if语句中使用这种格式吗?如果是,如何进行

(三) 有可能这样做吗

如果[“$”==“计算机科学”]|【“$”==“生物学”]|【“$”==“研究生中心”】


有人能帮我澄清一下我的疑问吗?

如果语句使用任意shell命令,shell
。如果该命令(无论是什么)成功退出,则将执行
then
子句;否则,将执行
else
子句。因此,第一个问题的答案是,是的,如果grep-q'pattern'测试文件
,您可以编写
,如果egrep-qw'string1 | string2'测试文件
,您还可以编写
如果perl-ne(这里有数百行代码)测试文件

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

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!…
是一种Bash主义。如果您不关心最大可移植性,就不要编写shell脚本;Perl比Bash更可能跨平台可用。
-q
-F
argum到
grep
的ENT也不是完全可移植的,而且
printf
也不是,但我从未被自2000年代中期以来就没有它们的系统绊倒过。)

我尝试使用以下脚本解决此问题,它成功运行。最初我提交了输入字符串。并尝试了输入字符串是否与testfile中已存在的字符串匹配。但目标是在“grep”和“then”之间仅使用一行“if”。 请提交其他答案(如有)

grep $* directory
echo -e "Hi, please type the word: \c "
read  word
echo "The word you entered is: $word"

if echo "Biology\|Computer Science\|Graduate Center MO" | grep -q "$word"
then 
echo "there is a match"
else 
echo "no such department found"
fi

我只有四行作为基本格式。那么我可以检查“if grep-qF”$arg“$testfile”格式中的多个字符串吗?在我的例子中,我可以这样写“if grep-qF”ComputerScience\| Biology\| GraduationCenter'$testfile”?这在三个方面做不到你想要的:1)
-f
-f
是不同的(和往常一样,Unix是区分大小写的);2)假设您指的是
-F
,那么将查找带有反斜杠和所有内容的文本字符串
ComputerScience\| Biology\|GraduationCenter
;3) 有一种方法可以在一个
grep
操作中查找多个字符串,
grep-qE“ComputerScience | Biology | GraduationCenter'$testfile”
,但如果三个字符串中的任何一个出现在文件中,而不是全部出现,则会报告成功。没有办法在一个
grep
中查找所有字符串。另外,我不明白“我只有四行作为基本格式”是什么意思。您可以在shell脚本中放入任意数量的代码。定期生成数万行长的shell脚本,它们可以正常工作。