简体   繁体   中英

bash + lookup + doing a lookup on 1 file to feed another

this is a file with the country name and lat and long:

$ cat country_with_lat_long
country,latitude,longitude,name,countrycode
AU,-25.274398,133.775136,Australia,Unknown
CN,35.86166,104.195397,China,Unknown
DE,51.165691,10.451526,Germany,Unknown
FR,46.227638,2.213749,France,Unknown
NZ,-40.900557,174.885971,New Zealand,Unknown
WS,-13.759029,-172.104629,Samoa,Unknown
CH,46.818188,8.227512,Switzerland,Unknown
US,37.09024,-95.712891,United States,Unknown
VU,-15.376706,166.959158,Vanuatu,Unknown

this is the file with the int code

$ cat country_with_code
name,code
Australia,61
China,86
France,33
Germany,49
New Zealand,64
Samoa,685
Switzerland,41
United Kingdom,44
United States,1
Vanuatu,678

how do i do a vlookup in bash so i can get the code from country_with_code and match it to the country in the country_with_lat_long file in the countrycode column?

EDIT1 Trying to understand the answer below better for my reference alone if anything

-F = The Input Field Separator Variable
-v = ?? required before each assignment
OFS = The Output Field Separator Variable
NR = The FNR variable contains the number of lines read, but is reset for each file read. The NR variable accumulates for all files read
FNR = see here
code[$1]= loads field2 from country_with_code into an array indexed by field1
$2 = this is field2 of this file country_with_code
$4 = ?? think this is field 4 in country_with_lat_long
$NF = The Number of Fields Variable, think this is the field I want to write to in the country_with_lat_long file in this case $5
code[$4]= ??

You could use the join command, but since the files aren't sorted, it gets a bit messy.

Here's awk

awk -F, -v OFS=, '
    NR == FNR {code[$1] = $2; next} 
    $4 in code {$NF = code[$4]} 
    {print}
' country_with_code  country_with_lat_long 
country,latitude,longitude,name,code
AU,-25.274398,133.775136,Australia,61
CN,35.86166,104.195397,China,86
DE,51.165691,10.451526,Germany,49
FR,46.227638,2.213749,France,33
NZ,-40.900557,174.885971,New Zealand,64
WS,-13.759029,-172.104629,Samoa,685
CH,46.818188,8.227512,Switzerland,41
US,37.09024,-95.712891,United States,1
VU,-15.376706,166.959158,Vanuatu,678

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM