branquito
branquito

Reputation: 4064

awk to search multiple word pattern from one file in another file

1st file content:

fruit bags    
nice things  
string guitar

2nd file content

bagsfruit  
nicefruit  
guitarstring  
simplethings  
stringguitar

how would i write awk program to search line by line 1st file content in 2nd file, and print only lines from 2nd file, that contain in ANY order BOTH words from 1st file..

so the result of script should be :

bagsfruit  
guitarstring  <--any order  
stringguitar  <--any order

BUT NOT any of these :

nicefruit  
simplethings

THANKS!

Upvotes: 1

Views: 2801

Answers (1)

fedorqui
fedorqui

Reputation: 290415

This can work:

$ awk 'NR == FNR{a[$2$1];next} ($1 in a)' first_file second_file
bagsfruit  
guitarstring  

The code is based in examples from Idiomatic awk.

Basically it loops through the first_file and creates an array a[] with fi[eld2 field1] (that is, $2$1) as index. Then it checks which field1 from second_file are in the array a[] and prints them.


Update

$ awk 'NR == FNR{a[$2$1];a[$1$2];next} ($1 in a)' first_file seconf_file
bagsfruit  
guitarstring  
stringguitar

let's create two array indexes each time, [$1$2] and [$2$1].

Upvotes: 1

Related Questions