使用grep在文件中查找多个字符串

时间:2017-05-14 10:10:06

标签: linux unix grep vi

如果使用grep Linux在文件中存在所有字符串时,如何在文件中查找多个字符串并返回 true

3 个答案:

答案 0 :(得分:1)

要搜索文件中的多字符串,可以在linux上使用egrep或grep。

egrep -ri --color 'string1|string2|string3' /path/to/file

-r search recursively
-i ignore case
--color - displays the search matches with color

你可以这样做并回显$?如果你的grep匹配任何东西,它将显示0(true),如果grep命令没有匹配,则显示1(false)

$? is a variable holding the return value of the last command you ran.

从这里你可以玩bash并创建一个小脚本或任何你需要的东西。

答案 1 :(得分:0)

试试这个:

if grep -q string1 filename && grep -q string2 filename; then
  echo 'True'
else
 echo 'false'
fi

测试片段:

Test Output

答案 2 :(得分:0)

一个在awk中。首先是测试文件:

$ cat file
foo
bar
baz

代码和测试运行:

$ awk '
BEGIN {
    RS="\177"                             # set something unusual to RS and append
    FS=FS "\n" }                          # \n to FS to make the whole file one record
{
    print (/foo/&&/bar/?"true":"false") } # search and output true or false
    # exit (/foo/&&/bar/?0:1)             # exit if you are interested in return value
' file
true

一衬垫:

$ awk 'BEGIN{RS="\177";FS=FS "\n"} {print (/foo/&&/bar/?"true":"false")}' file