1

Suppose I have 2 files

File-1 map.txt

1 tony
2 sean
3 jerry
4 ada

File-2 relation.txt

tony sean
jerry ada
ada sean

Expected-Output result.txt

1 2
3 4
4 2

My code was:

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

But I got the left column only:

1
3
4

It seems that something wrong near $2=map[$2].

Very appreciated if you could help.

2 Answers 2

3

You've got the mapping creation the wrong way around, it needs to be:

map[$2] = $1

Your current script maps numbers to names whereas what you seem to be after is a map from names to numbers.

The following transcript shows the corrected script:

pax> cat m.txt
1 tony
2 sean
3 jerry
4 ada

pax> cat r.txt
tony sean
jerry ada
ada sean

pax> awk 'FNR==NR{map[$2]=$1;next;}{$1=map[$1];$2=map[$2];print $0}' m.txt r.txt
1 2
3 4
4 2
Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks paxdiablo. I found that if I change name to number, it happened again. for example: m.txt: 1 23478267 2 97872632 3 47653728 4 12676782 r.txt: 23478267 97872632 47653728 12676782 12676782 97872632 results.txt was: 1 3 4
I was trying to map user id (really big number) to smaller integers like 1 2 3 4 5
3

Using awk.

awk 'FNR==NR{map[$2]=$1;next;}{print map[$1], map[$2]}' m.txt r.txt

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.