Home > Software design >  Move different files to new, individual directories based on list
Move different files to new, individual directories based on list

Time:08-11

I have a directory containing >500 files styled like this:

GCA_000007345.1.fa.gz 
GCA_000681355.2.fa.gz
GCA_000802095.1.fa.gz

I also have a tab-delimited txt file genomes_retrieved.txt where in column 1 is the file name and column 2 is the name of the directory that should be made and where the file should be moved to.

GCA_000007345.1.fa.gz   Methanosarcina_acetivorans_C2A
GCA_000681355.2.fa.gz   Peptococcaceae_bacterium_SCADC1_2_3
GCA_000802095.1.fa.gz   Peptococcaceae_bacterium_BICA1-7

I tried to follow this post here and use awk and xargs to execute in the directory where my files are. I create the directories

awk 'NR > 1{ print $2 }' ../genomes_retrieved.txt | xargs -I {}  mkdir {}

but I am not sure how to handle the mv part correctly.

awk 'NR > 1{ print $1 }' ../genomes_retrieved.txt | xargs -I {}  mv

Any advice?

CodePudding user response:

You can use below trick to run a "scriplet" that uses positional arguments ($1, $2, ...) for the each-line words:

xargs -n2 sh -c 'mkdir -p "${2}" && mv "${1}" "${2}"' -- < genomes_retrieved.txt

Update: an easy way to see what you're actually running is replacing sh -c by sh -xc.

Note also that above CLI requires "sane" files and directories names (in source txt file), i.e. with no special characters like quotes (' , "), backtics, $, (){} and any other character that would be interpreted by the shell.

  • Related