2017-02-12 88 views
-1

我有下面的示例關鍵字輸入文件Input.txt打印grep的關鍵字,如果grep的找到匹配

One 
Two 

我也有一個文件Text.txt進行搜索,例如:

Bla Bla 
Two more Bla 

我想如果grep找到匹配項,則打印grep關鍵字後跟一個匹配項。

所需的輸出:

Two: 
======== 
Two more Bla 
######## 
+1

前綴代碼/數據有四個空格。請看[編輯幫助](http://stackoverflow.com/editing-help)。 – Cyrus

+2

如果您不需要「標題」,請使用'grep -Ff Input.txt Text.txt' –

回答

0

使用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