【问题标题】:Print grep Keyword if grep find a match如果 grep 找到匹配项,则打印 grep 关键字
【发布时间】:2017-06-30 16:10:23
【问题描述】:

我有一个输入文件Input.txt,其中包含以下示例关键字:

One 
Two 

我还有一个文件Text.txt要搜索,例如:

Bla Bla
Two more Bla

如果 grep 找到匹配项,我想打印 grep 关键字后跟匹配项。

想要的输出:

Two:
========
Two more Bla
########

【问题讨论】:

  • 如果不需要“he​​ader”,使用grep -Ff Input.txt Text.txt

标签: linux bash unix scripting grep


【解决方案1】:

使用 awk 你可以做这样的事情:

$ awk 'NR==FNR{a[FNR]=$0;next}{for(i in a){if($0~a[i])print a[i]":\n========\n"$0}}' input.txt test.txt 
Two:
========
Two more Bla

采用更易读的格式:

awk 'NR == FNR { 
         a[FNR] = $0 
         next
     } 
     { 
         for(i in a) { 
             if ($0 ~ a[i]) {
                 print a[i] ":\n========\n" $0
             }
         }
     }' input.txt test.txt 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2013-11-19
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多