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条回答
闹够了就滚
2楼-- · 2019-01-09 22:12

These answers all seem more complicated than the obvious:

for i in /foo /bar; do cp "$file1" "$i"; done
查看更多
叼着烟拽天下
3楼-- · 2019-01-09 22:15

No, cp can copy multiple sources but will only copy to a single destination. You need to arrange to invoke cp multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.

查看更多
太酷不给撩
4楼-- · 2019-01-09 22:15

You can't do this with cp alone but you can combine cp with xargs:

echo dir1 dir2 dir3 | xargs -n 1 cp file1

Will copy file1 to dir1, dir2, and dir3. xargs will call cp 3 times to do this, see the man page for xargs for details.

查看更多
何必那么认真
5楼-- · 2019-01-09 22:17

If you need to be specific on into which folders to copy the file you can combine find with one or more greps. For example to replace any occurences of favicon.ico in any subfolder you can use:

find . | grep favicon\.ico | xargs -n 1 cp -f /root/favicon.ico
查看更多
Explosion°爆炸
6楼-- · 2019-01-09 22:24

I like to copy a file into multiple directories as such: cp file1 /foo/; cp file1 /bar/; cp file1 /foo2/; cp file1 /bar2/ And copying a directory into other directories: cp -r dir1/ /foo/; cp -r dir1/ /bar/; cp -r dir1/ /foo2/; cp -r dir1/ /bar2/

I know it's like issuing several commands, but it works well for me when I want to type 1 line and walk away for a while.

查看更多
戒情不戒烟
7楼-- · 2019-01-09 22:25

I would use cat and tee based on the answers I saw at https://superuser.com/questions/32630/parallel-file-copy-from-single-source-to-multiple-targets instead of cp.

For example:

cat <inputfile> | tee <outfile1> <outfile2> > /dev/null
查看更多
登录 后发表回答