2

I need to copy a particular named file from multiple directories and need to add number in the file prefix sequentially. For example I have the following directories, gene1, gene2, gene3 ..... gene100 and each directory having a file namely protein.fasta. I need to copy all the protein.fasta file from each directory and paste in another directory namely output. I have tried the following script but the script is not serving my purpose, It copy and paste only one file and rest is not copied and renamed finally end up with error. Kindly help me to do the same.

a=1
for i in **/protein.fasta
do
cp "$i" "$a"_"$i" output/
a=`expr $a + 1`
done

Detailed example and expected output is given below, Directories

gene1, gene2, gene3....gene100

file to be extracted from each file is protein.fasta

Expected output in the output directory

1_protein.fasta
2_protein.fasta
3_protein.fasta
.
.
100_protein.fasta

Thank you in advance.

2 Answers 2

4

You should be able to loop over directories and remove the gene prefix from the current directory name to use as the prefix for the target file name:

for d in gene*; do 
  echo cp "$d/protein.fasta" "output/${d#gene}_protein.fasta"
done 

Remove the echo once you are satisfied that it is doing the right thing.

0
1

I think maybe you want to use basename to remove the directory from the filename?

i=1
for f in **/test.file; do
  cp "${f}" "out/${i}_$(basename $f)"
  (( i += 1 ))
done
1
  • This won't prepend each file with the appropriate number though. For example gene10 will be the 2nd result so protein.fasta from the gene10 directory will become 2_protein.fasta
    – jesse_b
    Dec 27, 2019 at 15:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .