Search code examples
bashfor-looplsxargscp

Copy multiple files from one directory to multiple other directories


I have a directory structure

Dir_1
Dir_2
Dir_3
Source

. The directory Source contains the files File_1.txt and File_2.txt.

I want to copy all the files from the directory Source to all the remaining directories, in this case Dir_1, Dir_2 and Dir_3.

For this, I used

for i in $(ls -d */ | grep -v 'Source'); do echo $i | xargs -n 1 cp ./Source/*; done

. I, however, keep getting the message

cp: target ‘5’ is not a directory

It seems cp has problems with the directory names which have spaces in them. How do I resolve this (keeping the spaces in the directory names, obviously)?


Solution

  • Using find you could do something like this:

    find . -mindepth 1 -maxdepth 1 -type d ! -name Source -exec cp Source/*.txt {} \;
    

    This command searches the current directory for all subdirectories one level deep, excluding Source and then copies the text files into each.

    Hope this helps :)