awk search patterns from file in another

I would like to grep for aaa and bbb and ccc from one line in file1.txt in any order on a line on file2.txt

file1.txt

aaa bbb ccc
ddd fff ggg
hhh ddd jjj
jjj ccc

file2.txt

aaa bbb ccc ddd fff ggg  --> output whole line since it matches with aaa bbb ccc of file1.txt
aaa ddd jjj hhh --> no output since it does not match with any search pattern in file1.txt
ccc ddd fff ggg jjj --> output whole line since it matches with jjj ccc of file1.txt

I tried to use this code. But won't work as desired

NR==FNR{a[c++]=$0;next} {for(i in a) { m=1; m=split(i,b," "); { for(j=1;j<=m;j++) if($0~b[j]) m=0 } } } m{print} 

Try

awk '
NR==FNR         {a[$0]
                 next
                }
                {for (i in a)   {m=split (i, b, " ")
                                 for (j=1; ($0 ~ b[j]) && j<=m; j++);
                                 if (j > m)     {print
                                                 next
                                                }
                                }
                }
' file1 file2

Please note that ALL lines in your input file will be printed as line 2 matches hhh ddd jjj . On top, the first and the last line match more than one pattern.

1 Like