How to copy a file to multiple directories using t

2019-01-09 22:10发布

Is it possible to copy a single file to multiple directories using the cp command ?

I tried the following , which did not work:

cp file1 /foo/ /bar/
cp file1 {/foo/,/bar}

I know it's possible using a for loop, or find. But is it possible using the gnu cp command?

标签: linux bash shell
21条回答
The star\"
2楼-- · 2019-01-09 22:29

As far as I can see it you can use the following:

ls | xargs -n 1 cp -i file.dat

The -i option of cp command means that you will be asked whether to overwrite a file in the current directory with the file.dat. Though it is not a completely automatic solution it worked out for me.

查看更多
▲ chillily
3楼-- · 2019-01-09 22:31

ls -db di*/subdir | xargs -n 1 cp File

-b in case there is a space in directory name otherwise it will be broken as a different item by xargs, had this problem with the echo version

查看更多
你好瞎i
4楼-- · 2019-01-09 22:31

Using a bash script

DESTINATIONPATH[0]="xxx/yyy"
DESTINATIONPATH[1]="aaa/bbb"
                ..
DESTINATIONPATH[5]="MainLine/USER"
NumberOfDestinations=6

for (( i=0; i<NumberOfDestinations; i++))
    do
        cp  SourcePath/fileName.ext ${DESTINATIONPATH[$i]}

    done
exit
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-09 22:32

Essentially equivalent to the xargs answer, but in case you want parallel execution:

parallel -q cp file1 ::: /foo/ /bar/

So, for example, to copy file1 into all subdirectories of current folder (including recursion):

parallel -q cp file1 ::: `find -mindepth 1 -type d`

N.B.: This probably only conveys any noticeable speed gains for very specific use cases, e.g. if each target directory is a distinct disk.

It is also functionally similar to the '-P' argument for xargs.

查看更多
欢心
6楼-- · 2019-01-09 22:33

Another way is to use cat and tee as follows:

cat <source file> | tee <destination file 1> | tee <destination file 2> [...] > <last destination file>

I think this would be pretty inefficient though, since the job would be split among several processes (one per destination) and the hard drive would be writing several files at once over different parts of the platter. However if you wanted to write a file out to several different drives, this method would probably be pretty efficient (as all copies could happen concurrently).

查看更多
爷的心禁止访问
7楼-- · 2019-01-09 22:35

No - you cannot.

I've found on multiple occasions that I could use this functionality so I've made my own tool to do this for me.

http://github.com/ddavison/branch

pretty simple -
branch myfile dir1 dir2 dir3

查看更多
登录 后发表回答