4

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}

3
  • if I use some real name like tony, jerry, frank instead of uid 178246, 289789, etc, my code works perfectly, I do not know why it doesn't work when I use numbers instead of strings as the index of the associative array Commented Jan 14, 2014 at 3:38
  • Great!It works. I use "|" instead of "," and it works perfectly. Thank you so much Shellter. Commented Jan 14, 2014 at 3:47
  • how can i give you a answer score? lol, a nice answer Commented Jan 14, 2014 at 3:50

2 Answers 2

5
awk  -F"[, ]" 'NR==FNR {m[$3]=$1;next};{print m[$1]",",m[$3]}' map.txt relations.txt
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.