Linux – How to sort a first file (csv) based on the second file keys

awkcsvlinuxsort

I am trying to find a solution where I can sort my first file using the first column based on the second file keys

First file example (file1.csv)

COLUMN1 COlUMN2
apple fruit
dog animal
cat animal
cow animal

Second file example (sort_keys.txt)

cat
dog
apple
cow

Expected output (sorted.txt)

COLUMN1 COlUMN2
cat animal
dog animal
apple fruit
cow animal

So far I have found a sort command and awk commands might be able to help but I do not have any working code.

$> awk 'NR==FNR{o[FNR]=$1; next} {t[$1]=$0} END{for(x=1; x<=FNR; x++){y=o[x]; print t[y]}}' sort_key.txt file1.csv

However, this command is not working as expected, and would request any expert advice on this. P.S I do have Linux commands knowledge but this is something very specific and I do not have any idea how to achieve this.

Any help or hint is highly appreciated.

Best Answer

$ awk 'NR==1; NR==FNR{a[$1]=$2; next} {print $1, a[$1]}' file1 sort_keys.txt
COLUMN1 COlUMN2
cat animal
dog animal
apple fruit
cow animal
Related Question