bashbatch-renamesuffix

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


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/


Solution

  • 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