'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 1:[1]
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
mvcommand. Remove theechowhen you've confirmed that it will do what you want.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pjh |
| Solution 2 | rabbit |
