This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to sort lines in a file based on listing in another file using loop "while read line"

Hi, I have a file with sequence ID + metadata that I would like to sort as ID ordered in a second file (corresponding to a phylogenetic tree).

File 1 is like this (header in the first line, then sequence ID + metadata for following lines):

RUN,3.code,SL,SL2
ERR911851,GRL,4.4.1.1,4.4
ERR911854,GRL,4.4.1.1,4.4
ERR911855,GRL,4.4.1.1,4.4
ERR911856,GRL,4.4.1.1,4.4
ERR911859,GRL,4.8,4.8
ERR911860,GRL,4.8,4.8
ERR911862,GRL,4.4.1.1,4.4

etc ........

File 2 is like this:

"ERR163930"
"ERR182011"
"ERR221551"
"ERR221600"
"ERR245800"
"ERR212152"

etc........

Any idea how to proceed? Thanks for your help best Yann

bash

Hi, I have a file with sequence ID + metadata that I would like to sort as ID ordered in a second file (corresponding to a phylogenetic tree).

File 1 is like this (header in the first line, then sequence ID + metadata for following lines):

RUN,3.code,SL,SL2

ERR911851,GRL,4.4.1.1,4.4

ERR911854,GRL,4.4.1.1,4.4

ERR911855,GRL,4.4.1.1,4.4

ERR911856,GRL,4.4.1.1,4.4

ERR911859,GRL,4.8,4.8

ERR911860,GRL,4.8,4.8

ERR911862,GRL,4.4.1.1,4.4

etc ........

File 2 is like this:

"ERR163930"

"ERR182011"

"ERR221551"

"ERR221600"

"ERR245800"

"ERR212152"

etc........

Any idea how to proceed? Thanks for your help best Yann

Thanks it works perfectly!!!!! best Yann

If an answer was helpful you should upvote it, if the answer resolved your question you should mark it as accepted. Upvote|Bookmark|Accept

Sorry I just realized the upvoting stuff and "accept" option, I am new on this website and didnt get the rules. Next time I would do it. Anyway thanks for your help!

1 answer

Not exactly a bioinformatics question but this should work

cat FILE2.txt | while read -r ID; do grep "^$ID" -w FILE1.txt; done

If you have double quotes " in FILE2, try following

cat FILE2.txt | sed 's/"//g' | while read -r ID; do grep "^$ID" -w FILE1.txt; done

Marked accepted as answer since OP didn't...

Thanks. Some OPs never care about this after finding a working solution. Too bad :(

You would think that's the least they can do, in return for us spending our time here. Oh well, good thing we have plenty of nice people here too ;)

Log in to answer this question.