【问题标题】:linux search multiple word in a fileslinux在一个文件中搜索多个单词
【发布时间】:2011-09-28 14:37:11
【问题描述】:

我有一个包含一组文本文件的文件夹。

-Folder
--- file 1
--- file 2
--- file 3
--- file 4

我有一组单词,我想检查它们是否在里面。 {word1, username, blah blahblah}

有没有办法通过单个命令来发现这些文件中的哪个包含我列表中的所有单词?

我看到可以使用 some 和 grep 但我认为它们在单行上工作,而在我的情况下,wors 总是在不同的行上。

字数是静态的。总是 3 或 4,所以如果需要,我可以在命令中硬编码它们。

编辑: 它们在 AND 中。如果里面没有所有文件,则不接受文件! 我想避免做 egrep -l 'word1' .| xargs egrep -l 'word2'

是否有更好的解决方案只调用一次 grep?

干杯, 步骤

【问题讨论】:

    标签: linux bash command


    【解决方案1】:

    这对你有用吗?

    grep -IRE 'word1|username|blah blahblah' /path/to/files/ | 
    sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P' | 
    awk -F: '$1!=p{if(b"" && c > 2)print b; p=$1;c=0;b=s=""}{b=b s $0;s=RS;c++}END
    {if(b"" && c > 2)print b}' | awk -F: '{print $1}' | sort -u
    

    第一部分(grep)将列出所有具有匹配模式的文件名。第二部分(sed)将从第一个输出中去除重复项,只给出不同的行。第三部分将仅显示多次出现的文件,第四部分将删除您匹配的模式,最后一个将只为您提供文件名我的朋友。

    我现在头疼...

    【讨论】:

      【解决方案2】:

      使用:

      grep -f words.txt input
      

      例子:

      $ cat words
      word1
      username
      blah blahbla
      
      a
      word1
      username blah blahblah
      b
      username blah blahblah
      c
      word1
      d
      word1, username, blah blahblah}
      
      $ grep -f words.txt *
      a:word1
      a:username blah blahblah
      b:username blah blahblah
      c:word1
      d:word1, username, blah blahblah}
      

      【讨论】:

        【解决方案3】:

        使用 grep:

        grep -E '(word1|username|blah blahblah)' Folder/*
        

        -E 标志将 grep 置于正则表达式的“扩展”模式。这将默认显示文件名和匹配的文本。如果您只需要文件名,请将-l 添加到选项中。

        【讨论】:

        • 不起作用。如果我使用 grep -E '(word1|word2)' ,则在当前文件夹中,文件 1 包含 word1 word2 word3 word4 word5 (在不同的行上)。我空了
        • 一些发行版也有一个egrep,与grep -E相同,所有其他选项与grep相同。
        【解决方案4】:

        另一种解决方案,最适合少量单词:

        grep -e word1 -e username -e "blah blahblah" Folder/*
        

        【讨论】:

        • 问题是多次返回文件名。有没有办法避免重复?
        【解决方案5】:

        如果你想用 grep 进入目录树,则如下

        egrep -E '{word1|username|blah blahblah)' `find . -type f -print` 
        

        我建议您在搜索有关 *nix 系统的答案时也使用术语目录而不是文件夹 :-)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-01
          • 2014-03-23
          • 1970-01-01
          • 2021-04-01
          • 1970-01-01
          相关资源
          最近更新 更多