0

I want to copy a list of files, called dti_fin_fa, from one folder to another.

These files are scattered in different folders.

   Controls

   └───C01
   │   └───difusion 
   │       └───Deterministic
   │             └───dti_fin_fa.nii
   └───C02
   │   └───difusion 
   │       └───Deterministic
   │             └───dti_fin_fa.nii
   └───C03
   │   └───difusion 
   │       └───Deterministic
   │             └───dti_fin_fa.nii

I want to select and copy all the dti_fin_fa, keeping the folder structure, so, in my new directory, I would have the folder distribution just seen above. The problem is that in this folders, (deterministic, difusion, etc), there are lots of other files I don´t want to copy, so I can´t just copy the main folder (C01 etc)

This is what I have:

#!/bin/bash
DIR="/media/Batty/Analysis"; cd "$DIR" || exit
for group in Controls; do
    for folder in $group/*; do
        for dti in $folder/difussion/Deterministic/dti_fin_fa.nii; do
        echo $dti
        cp $dti /media/Roy/Analysis/Controls/ --verbose
        done;
    done;
done;

The problem is that this code copies each of the dti_fin_fa.nii images into /media/Roy/Analysis/Controls/, hence keeping just the last one, instead of creating all the other subfolders.

Could something like this work?

cp $folder/difusion/Deterministic/$dti /media/Roy/Analysis/Patients/ --verbose

RoyBatty
  • 107
  • 3
  • Does this answer your question? [Bash: Copy named files recursively, preserving folder structure](https://stackoverflow.com/questions/1650164/bash-copy-named-files-recursively-preserving-folder-structure) – Joe Apr 22 '21 at 12:14

1 Answers1

0

Iterate through each control, make the equivalent directory and copy only the file you want:

for group in "Control"/* "Patients"/*; do
  orig="$group/difusion/Deterministic"
  dest="/media/Roy/Analysis/Controls/$(dirname group)/$orig" 
  mkdir -p "$dest"
  cp "$orig/dti_fin_fa.nii" "$dest/" 
done

I suppose you execute this from the DIR directory of your example. So here orig is the relative path to the image folder, dest is the absolute path to your destination directory, including the preserved original folder structure. mkdir -p ensures that such end directory exists and finally the image is copied.

Miguel
  • 2,130
  • 1
  • 11
  • 26
  • Thanks @Miguel, but I don´t understand this line `dest="/media/Roy/Analysis/Controls/$group/$dir"` . What is that `$dir` doing? If I `echo $dest`, this is what I get `/media/Roy/Analysis/Controls/Controls/*/`. Shouldn´t it be just one `Control`. – RoyBatty Apr 22 '21 at 15:43
  • there are errors in your code, as for example should be `"Controls"/*` and `"Patients"/*`, and $dir is reference but not assigned – RoyBatty Apr 22 '21 at 17:55
  • OK, check it now, I corrected the errors (you should edit your question to mention the Patients folder) and added some explanations. – Miguel Apr 22 '21 at 18:16