3

I have two files which separated by tabs:

file1.txt:

1 KD 
2 LBJ
3 YAO
4 LBJ
5 YAO
6 MJ
7 MJ
8 YAO
9 KD

file2.txt:

KD 35
LBJ 6
YAO 11
MJ  23

Expected output:

1 KD 35 
2 LBJ 6
3 YAO 11
4 LBJ 6
5 YAO 11
6 MJ 23
7 MJ 23
8 YAO 11
9 KD 35

Any help in awk is appreciated.

1 Answer 1

7

You could do it with awk:

awk -F'\t' -v OFS='\t' 'NR==FNR{a[$1]=$2;next}{print $0, a[$2]}' file2 file1
1   KD  35  
2   LBJ 6
3   YAO 11
4   LBJ 6
5   YAO 11
6   MJ  23
7   MJ  23
8   YAO 11
9   KD  35

Another option is to use join command:

join -1 2 -2 1 -o 1.1 1.2 2.2 -t $'\t' <(sort -k2,2 file1) <(sort file2) | sort -n

Explanation:

  • -1 2 -2 1 tells the join command to join the second field of the first with the first field of the second file
  • -o 1.1 1.2 2.2 This specifies the order of the fields in the output. The number before the dot is the file number, the number after the dot is the field number of the file
  • -t $'\t' specifies that the delimiter is the tab character
  • <(sort -k2,2 file1) <(sort file2) sorts the files by the field to be joined. The join command requires that the files are sorted.
  • | sort -n sorts the output file
1
  • 1
    Thank you @EdMorton, I'll keep that in mind.
    – user000001
    Aug 23, 2022 at 13:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .