AWK associative array, mapping or hash map

associative-array, awk, mapping

Solution

Remove the leading space in both files in column 2.

And do yourself a favor and switch to something besides commas for `FS`. The Tab char is good because most input screens use tab to move to the next field, so it shouldn't be in your data. The `|` char is nice because it is visual and very unlikely to be in your input.

You could build a 'trap' to find records without the right number of fields like this:

awk -F"|" -v expectFldCnt=2 '{
   if (NF==expectFldCnt) { print ":everything OK" ; }
    else { print "ERR: " NF "!=" expectFldCnt  ":" $0 > "errorFile" }
    }' \
  map.txt relation.txt

IHTH

Problem

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}

Original source