Skip to content
Advertisement

Print grep Keyword if grep find a match

I have an input file Input.txt with the following sample keywords:

One 
Two 

I also have a file Text.txt to search such as:

Bla Bla
Two more Bla

I want to print grep Keyword followed by a match if the grep finds a match.

The desired output:

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

Advertisement

Answer

With awk you could do something like this:

$ 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

In a more readable format it would be:

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 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement