Search row by row from one file to another file if match is found print few colums of file 2

this is the requirement

list.txt

table1
table2
table3

testfile.txt

name#place#data#select * from table1
name2#place2#data2#select * from table 10 innerjoin table3
name2#place2#data2#select * from table 10

output

name place table1
name2 place table3

i tried using awk

#! /bin/ bash 
while read line           
do  
x=`echo "$line"`
awk /'$x'/ > "file"($x~/"$line"/?2:1)}' testfile.txt 
done<list.txt

kindly help.

It's not clear what you're doing. First of all get rid of the shell script and just use awk.

awk 'NR==FNR{a[$0]; next} {for(x in a) {if($0 ~ x) {print $1, $2, x}}}' FS='#' list.txt testfile.txt
1 Like

Thanks sahoo but its partially working.

I need $1,$2,$3 of test file and $0/$1 of the list file.
but currently i am getting $4 of the test file in which i want to search for string but get rid of it in output.

Please help.

Your example said you need $1, $2 from test file and $0 from list file and I have provided the code for the same.

If you want to print $3 as well from test file

awk 'NR==FNR{a[$0]; next} {for(x in a) {if($0 ~ x) {print $1, $2, $3, x}}}' FS='#' list.txt testfile.txt
1 Like

This should be more efficient:

awk -F"[# ]" 'NR==FNR{a[$1]=$1;next}$NF in a {print $1, $2, a[$NF]}' list.txt testfile.txt
1 Like

Hi Franklin...you are correct
But the reason why I went with this approach is - since there are select statements with joins at the end, the table we are searching for need not be the last one in query. Below is an example.

name2#place2#data2#select * from table3 innerjoin table 10

Thanks a lot srini. It worked. i was struggling to add the table column at the last.

Thanks franklin :slight_smile: