0

I have to rename a large number of files inside of directories (one file per directory) based on part of the parent directory's name: for example

abc_S1_R1/contig.fasta
bcd_S2_R1/contig.fasta
cde_S5_R1/contig.fasta

The final name I want is:

abc_S1_R1/abc.fasta
bcd_S2_R1/bcd.fasta
cde_S5_R1/cde.fasta

What will be the best way for me to do it? Thank you.

1

Try the following code. You might want to add an echo in front of the mv line, to check that the commands look good. The quotes are only necessary if the names include spaces or other characters in them.

for x in */contig.fasta; do
    d=$(dirname "$x")
    p=$(echo $d | cut -d_ -f1)
    mv "$d/contig.fasta" "$d/$p.fasta"
done
4
  • Thanks. Is it possible to use rename command to do it? – Bio_farmer Jan 22 '20 at 12:21
  • 1
    FWIW you could use d=${x%/*} and p=${x%%_*} to avoid the external dirname and cut – steeldriver Jan 22 '20 at 13:02
  • :-) For every shellscript, there is a shorter and more efficient one using some slightly more obscure functionality of the shell. Thanks for the comment, even after 20 years of Unix, you learn something new every day. – Ketil Malde Jan 22 '20 at 17:35
  • @Bio_farmer, probably - I generally use the shell for things like this. Quick and general, without resorting to specialized commands. BTW, if you want fast, use GNU parallel instead of the loop (but it will surely be IO limited anyway). – Ketil Malde Jan 22 '20 at 17:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.