Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK associative array, mapping or hash map

Suppose I have two files:

file1 - map.txt

1, 178246
2, 289789
3, 384275
4, 869282

file2 - relation.txt

178246, 289789
384275, 178246
384275, 869282

Expected results are:

1, 2
3, 1
3, 4

But the results I got using the following code were:

awk 'FNR==NR{map[$2]=$1} {$1=map[$1];$2=map[$2];print $0}' map.txt relation.txt

  2,
  1,
  4,

It was confused when I swapped the columns in map.txt like this:

178246, 1
289789, 2
384275, 3
869282, 4

relation.txt doesn't change

The results became:

awk 'FNR==NR{map[$1]=$2} {$1=map[$1];$2=map[$2];print $0}' map.txt relation.txt

1,
3,
3,

It seems that something wrong near {$1=map[$1];$2=map[$2];print $0}

like image 289
cxstam Avatar asked Sep 10 '25 06:09

cxstam


1 Answers

awk  -F"[, ]" 'NR==FNR {m[$3]=$1;next};{print m[$1]",",m[$3]}' map.txt relations.txt
like image 91
Endoro Avatar answered Sep 13 '25 04:09

Endoro