Unix & Linux
awk read
Updated Wed, 31 Aug 2022 21:12:28 GMT

Trying to find complete string values from one file based on another file using AWK


Hello I have 2 files with the first file containing a few values for example

powershell
vectormaps
JuniperSA

and the second file containing values and and ID

appid uid
SplunkforSnort 340
powershell 610
vectormaps 729
JuniperSA 826
postfix 933
SplunkforJuniperSRX 929
TA-barracuda_webfilter 952
TA-dragon-ips 954
dhcpd 392

So im trying to run a while loop with AWK to get the values and their corresponding ID's but the output file seems to be writing something else. This is how im trying to run the while loop.

while read $line;
do
awk '/'$line'/ {print $0}' file2.csv > new
done < file1

My expected output should be

powershell 610
vectormaps 729
JuniperSA 826

but my output is

appid uid
SplunkforSnort 340
powershell 610
vectormaps 729
JuniperSA 826
postfix 933
SplunkforJuniperSRX 929
TA-barracuda_webfilter 952
TA-dragon-ips 954
dhcpd 392

it seems as if nothing is happening. What am i missing here?




Solution

Using awk

$ awk 'FNR==NR {a[$1]=$2; next} {$(NF+1)=a[$1]}1' file2 file1
powershell 610
vectormaps 729
JuniperSA 826




Comments (2)

  • +1 – Worked like a charm. — Jul 27, 2022 at 11:35  
  • +1{print $0, a[$1]} would be a bit more efficient than {$(NF+1)=a[$1]}1 since the former just prints the 2 strings while the latter additionally modifies a field which causes awk to have to rebuild $0 from the fields, replacing every FS with OFS. It MAY also cause awk to have to resplit the record into fields again too as adding a field modifies the record, I'm not sure about that one. — Jul 27, 2022 at 12:12