yunshi11
yunshi11

Reputation: 11

bash - Find names in file1 according to IDs in file2

Sorry if this is duplicate, but I searched and haven't found exactly same question. So I have

File1:
Aaron ID00456
Brad ID00123
Cassie ID00789
Doug ID12345
Ethan ID05555

File2:
ID12345
ID00123
ID00456

Keeping the order of IDs in File2, I'd like to have output File3 as:
Doug ID12345
Brad ID00123
Aaron ID00456

Upvotes: 0

Views: 45

Answers (2)

karakfa
karakfa

Reputation: 67497

awk to the rescue!

$ awk 'NR==FNR {a[$2]=$1; next} 
               {print a[$1],$1}' file1 file2

Doug ID12345
Brad ID00123
Aaron ID00456

Upvotes: 1

Banghua Zhao
Banghua Zhao

Reputation: 1556

Try this script (suppose File1.txt and File2.txt are in the same directory of the script).

#!/bin/bash
while read -r ID2
do
  while read -r NAME ID1
  do
    if [ "$ID1" = "$ID2" ]
    then
      echo $NAME $ID1 >> File3.txt
    fi
  done < File1.txt
done < File2.txt

Then find File3.txt in the same directory with the content:

Doug ID12345
Brad ID00123
Aaron ID00456

Upvotes: 1

Related Questions