I'm trying to sort the rows of a text file based on an 'index' in another file, such that the text file is arranged, row by row, in the same order as the index file.The following code achieves what I'm looking to do, but I want to replace file_to_sort.txt with another variable (so that I can pass 2 command line arguments) to make this a general script. I can't figure out how to make the while loop deal with this.while read line ; do grep $line file_to_sort.txt ; done < ../index.txtThe file to sort looks like so:Locus ./PAK_01896.fsa GC: 0.401826484018Locus ./PAK_02014.fsa GC: 0.355555555556Locus ./PAK_02606.fsa GC: 0.415555555556Locus ./PAK_03203.fsa GC: 0.391111111111Locus ./PAU_01961.fsa GC: 0.395555555556Locus ./PAU_02074.fsa GC: 0.406392694064Locus ./PAU_02206.fsa GC: 0.353333333333Locus ./PAU_02775.fsa GC: 0.415555555556Locus ./PAU_03392.fsa GC: 0.384444444444Locus ./PLT_01696.fsa GC: 0.42Locus ./PLT_01716.fsa GC: 0.422222222222Locus ./PLT_01736.fsa GC: 0.433333333333Locus ./PLT_01758.fsa GC: 0.426666666667Locus ./PLT_02424.fsa GC: 0.413333333333Locus ./PLT_02568.fsa GC: 0.391111111111And the index order looks like this (and so the output should be the first file, sorted according the the ./xxx_xxxx strings in the second).PAU_03392PAK_03203PAU_01961PAK_01787PLT_02568PAU_02074PAK_01896PLT_02424PAU_02775PLT_01696PAK_02606PLT_01736PLT_01758PLT_01716PAU_02206PAK_02014I'm sure this is really simple, but I can't see it and whatever I was searching to try and solve this wasn't dragging up the right answers (since I'm sure this has been answered somewhere.
Sorting one file line by line based on another file
shell script;text processing;grep
#!/bin/bashFILE_TO_SORT=$1INDEX_FILE=$2TMP_FILE=$(mktemp)while read LINE; do    grep $LINE $FILE_TO_SORT >>$TMP_FILEdone <$INDEX_FILEmv -f $TMP_FILE $FILE_TO_SORTThe above script will take 2 arguments and sort the first based on the second, take in consideration that lines not matched by any in the index file will be discarded, also the original file will be replaced by the sorted one. On top of that if you have several lines to be sorted with the same index and want it to be sorted as well you can change the grp line to this grep $LINE $FILE_TO_SORT | sort -f 4 >>$TMP_FILE and it will be sorted by the number (field 4) at the end.