【问题标题】:ksh: grep command for multiple string. If all the strings found then only return the resultksh:用于多个字符串的 grep 命令。如果找到所有字符串,则只返回结果
【发布时间】:2014-04-08 20:04:54
【问题描述】:

有没有办法在 ksh 中 grep 2 个字符串,并且只有在两个字符串都找到时才返回 true?

如果找到任何字符串,我们可以使用 egrep 命令。但要匹配所有字符串并仅返回所有存在的字符串。

grep "string1" "sring2" file.txt 不起作用。

请帮助。 提前致谢。

编辑:

请注意,如果不使用 grep,我们可以为此目的使用什么其他选项。第一个字符串也出现在文件的第一行中,而 string2 出现在文件的其他行中。

【问题讨论】:

  • 所以你想知道这两种模式都存在于同一个文件中的任何一行吗?

标签: unix grep ksh


【解决方案1】:

你可以试试

grep "string1.*string2" file

在此测试中,string1 必须在同一行中的 string2 之前出现。


或者你可以这样做:

grep string1 file | grep string2 

如果找到string1string2 则为真


使用awk

awk '/string1/ && /string2/' file

搜索任意一行

awk '/string1/ {f1=1} /string2/ {f2=1} END {if (f2 && f1) print "found"}' file

获取退出状态 (cred Adrian)

awk '/string1/ {f1=1} /string2/ {f2=1} END {exit !(f1 && f2)}' file

这将给出两种模式的退出状态0,如果没有找到1

【讨论】:

  • awk 是去这里的方式,但如果没有找到两个字符串,您的示例将 not exit >0。
  • 你的逻辑颠倒了,如果现在找到两种模式,它将exit 1。我想你的意思是if (f1 && f2) exit 0; exit 1exit !(f1 && f2)
  • 你是对的,更新了你的建议,谢谢。
【解决方案2】:
$ echo "foo bar quux" | awk 'BEGIN{r=1} /foo/&&/bar/{r=0} END{exit r}'
$ echo $?
0

$ echo "foo bar quux" | awk 'BEGIN{r=1} /blah/&&/blubb/{r=0} END{exit r}'
$ echo $?
1

如需更动态的方法,请查看Dennis Williamson's 答案here

【讨论】:

    【解决方案3】:

    如果您希望两种模式出现在同一行或不同行(在同一文件中),请考虑以下简单的事情:

    grep string1 file.txt && grep string2 file.txt

    只有在两个 (&&) 都成功的情况下才会成功,它将优化布尔逻辑,并且仅在第一个成功时才运行第二个 - 没关系,除非您想做更多的事情:

    您可以对它进行分组并制作“then/else”之类的东西 - 请注意 (),它会为您提供整个 grep && grep 的结果:(grep string1 file.txt && grep string2 file.txt) && echo "This file is OK" || echo "I don't like this file"

    【讨论】:

      【解决方案4】:

      尝试使用以下内容:

      grep 'word1\|word2\|word3' /path/to/file
      

      或者在 UNIX 上:

      grep -e pattern1 -e pattern2 /path/to/file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-03
        • 2020-05-11
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        • 2015-05-13
        • 1970-01-01
        相关资源
        最近更新 更多