Home > Mobile >  How to add suffix to multiple files in subdirectories based on parent directory?
How to add suffix to multiple files in subdirectories based on parent directory?

Time:03-11

I have 100 directories as followed:

bins_copy]$ ls

bin.1/  
bin.112/  
bin.126/  
bin.24/  
bin.38/  

etc. etc.

Each of these directories contains two files names genes.faa and genes.gff, e.g. bin.1/genes.faa

I now want to add a suffix based on the parent directory so each gene file has a unique identifier, e.g. bin.1/bin1_genes.faa and bin1_genes.gff.

I've been going down the google rabbit hole all morning and nothing has sufficiently worked so far. I tried something like this:

for each in ./bin.*/genes.faa ; mv genes.faa ${bin%-*}_genes.faa $each ; done 

but that (and several versions of it) gives me the following error:

-bash: syntax error near unexpected token `mv'

Since this is a really generic one I haven't figured it out yet and truly would appreciate your help with.

Cheers/

CodePudding user response:

There may be a more elegant way of doing this but create this script in the same directory as the bin directories, chmod 700 and run. you might want to back up with tar first (tar -cf bin.tar ./bin*)

#!/bin/bash
files="bin.*"
for f in $files; do
        mv ./${f}/genes.faa ./${f}/${f}_genes.faa
        mv ./${f}/genes.gff ./${f}/{$f}_genes.gff
done

CodePudding user response:

Try this Shellcheck-clean code:

#! /bin/bash -p

for genespath in bin.*/genes.*; do
    dir=${genespath%/*}
    dirnum=${dir##*.}
    genesfile=${genespath##*/}
    new_genespath="$dir/bin${dirnum}_${genesfile}"
    echo mv -iv -- "$genespath" "$new_genespath"
done
  • It currently just prints the required mv command. Remove the echo when you've confirmed that it will do what you want.
  • Related