bash script: copy from a folder to another within a directory and loop the process over multiple directories
I am still a beginner for bash scripting.I am trying to loop copy command to run through multiple directories.
I have set of directories, P1, P2, P3,..P60. Inside each directory there are three folders ‘A’, ‘M’ and ‘out’. I want to copy files from A and M folders and paste them into "out" folder. Then repeat it through all the 60 directories.
‘AL’ has a file called PIL_CBR.nii and ‘M’ has a file called PIL_MO.nii.
Thank you!
I assume that P1, P2, …, P60 directories are in the same folder. Then, you just need to loop through all directories in this folder and run cp
. Running the following script in this folder should do.
for d in P*/ ; do
echo "$d"
cp $d/A/* $d/M/* $d/out/
done
You’re probably aware of it that here * expands to file and directory names in current directory.
Assuming that your directories are named exactly as you say, are in the current directory, and don’t contain thousands of files each, something like this should work:
for dir in P{1..60}/{A,M} ; do
[ -d "$P" ] || continue
cp "$dir"/* "${dir%[AM]}out/"
done
Using the *
wildcard to select your directories may work but risks over matching and changing things you don’t expect.
This should only match the exact set of items you describe, but as such it is quite specific to the case you describe, and the approach may need to be modified for different input.
If you have file name clashes in your two directories the contents from M
will replace that from A
. This could be handled, but wasn’t in your original specification.