grep 多个字符串的 shell 命令是什么?

What is the shell command to grep multiple strings?

grep 多个字符串的 shell 命令是什么? 对于输入文本[命令输出],我需要检查是否有几个字符串。如果所有字符串都存在,将 return 为真,否则为假(AND 操作)。

例1:输入:grep多个字符串的shell命令是什么?对于输入文本[命令输出],我需要检查是否有几个字符串。如果所有字符串都存在,将 return 为真,否则为假(AND 操作)。

搜索字符串 "need" "check" "few" "AND"

输出:真

示例 2:什么是 shell grep 多个字符串的命令?对于输入文本[命令输出],我需要检查是否有几个字符串。如果所有字符串都存在,将 return 为真,否则为假

搜索字符串 "need" "check" "few" "AND"

输出:假

你可以使用像

这样的东西
$cat test.txt
name1 is a boy
name2 is a girl
name3 is a good person
name4 is unknown to me
$ grep -q "name1" test.txt && grep -q "name2" test.txt
$ echo $?
0
$ grep -q "name1" test.txt && grep -q "helloWorld" test.txt
$ echo $?
1

使用 grep 搜索每个模式。如果其中任何一个未能在文件中找到模式,它将以 1 状态退出。所以在我的第二个例子中,第一个 grep 成功并且 return 0 而第二个 returns 1 因此当你查询退出状态时它说 1. 这样,你可以检查你是否找到了所有模式是否存档。

如果你的意思是"are all search targets present someplace in the file",那么你可以

   awk '/need/{n=1}/check/{c=1}/few/{f=1}/AND/{A=1}
       END{exit (!(n&&c&&f&&A))}' file2search

回声$? return 当在文件中找到所有内容时为 0,当文件中缺少任何内容或全部内容时为 1。

如果你的意思是"are all search targets on the same line",那么你可以

  awk '{ if ([=11=] ~ /need/ && [=11=] ~ /check/ && [=11=] ~ /few/ && [=11=] ~ /AND/) lineMatched=1 }
      END { if (lineMatched) exit 0 ; else exit 1 }' file2Search

回声$?将以同样的方式工作。

IHTH