【问题标题】:List strings not found with grep列出用 grep 找不到的字符串
【发布时间】:2017-11-10 16:39:58
【问题描述】:

我想在文件中搜索特定单词,然后只显示未找到的单词。到目前为止,以我在这方面的有限技能,我可以找到找到哪些单词:

egrep -w "^bower_components|^npm-debug.log" .gitignore

如果我的 .gitignore 文件包含 bower_components 但不包含 npm-debug.log,它将返回 bower_components。我想知道如何要求它只返回未找到的模式部分。也就是说,我希望它只返回 npm-debug.log。我不想看到文件中与搜索不匹配的所有文本,只看到文件中未找到的单个单词。我该怎么做?

【问题讨论】:

    标签: linux ubuntu grep


    【解决方案1】:

    如果您的示例中只有简单的单词,您可以在一行中使用两个 grep 命令来完成。例如:

    文件:

    first line
    _another line
    just another line
    STRANGE LINE
    last line
    

    单词:

    first
    last
    row
    other
    ^another
    LINE$
    

    我们可以先得到匹配的模式

    > grep -owf words file
    first
    LINE
    last
    

    然后我们在words 中为他们grep -v。还要在中间添加一个uniq 以删除所有重复项。

    所以最后我们从words 得到模式在file 中不匹配:

    > grep -owf words file | uniq | grep -vf - words
    row
    other
    ^another
    

    【讨论】:

      【解决方案2】:

      我认为这不能单独使用 grep 来完成;这是一个笨拙的 awk 单行代码:

      awk -v p1="npm-debug.log" -v p2="bower-component" 'BEGIN{a[p1]=0;a[p2]=0} $0 ~ p1 {a[p1]+=1}; $0 ~ p2 {a[p2]+=1}; END{for(i in a){if( a[i]==0){print i}}}' .gitignore
      

      我将搜索模式作为变量传递给 awk,使用模式作为索引预填充数组,如果匹配则递增它们,并且只打印没有命中的数组(仍然为 0)。

      【讨论】:

        【解决方案3】:

        我没有适合您的单行脚本,但可以为您的用例提供一个简短的脚本。

        file=$1
        shift
        for var in "$@"
        do
          found=`grep "^$var" $file`
          if [[ -z $found ]]
          then
           echo $var
          fi
        done
        

        解释,将第一个参数作为文件名,任何后续参数作为字符串在文件中进行测试。遍历这些参数并测试 grep 命令的结果以查看它是否返回空。如果确实如此,则找不到该字符串,我们将其打印到控制台。 用法:[script name] .gitignore bower_components npm-debug.log

        【讨论】:

        • 我需要稍微调整一下答案,发现最容易调整这个布局合理且易于阅读的 bash 脚本。
        猜你喜欢
        • 1970-01-01
        • 2012-04-17
        • 2017-11-11
        • 2021-07-10
        • 1970-01-01
        • 2018-09-16
        • 1970-01-01
        • 2013-08-19
        • 1970-01-01
        相关资源
        最近更新 更多