Question

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.

Était-ce utile?

La solution

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

Autres conseils

Using awk.

awk 'FNR==NR{map[$2]=$1;next;}{print map[$1], map[$2]}' m.txt r.txt
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top