如何在 Linux/Unix 上递归复制以“abc”开头的目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5275418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to recursively copy directories starting with "abc" on Linux/Unix?
提问by cwd
I have a directory ~/plugins/
and inside there are many sub-directories. If I wanted to create a backup somewhere else of just the sub-directories starting with abc
could I do that with a one line copy command? I would assume something like this would work (but it doesn't):
我有一个目录~/plugins/
,里面有很多子目录。如果我想在其他地方创建备份,而只是以 开头的子目录,abc
我可以用一行复制命令来做吗?我会假设这样的事情会起作用(但它不会):
cp -R ~/plugins/abc* ~/destination/
I would rather use a one-line command, if possible, because I would also like to use the same syntax for rsync, and if I have to do something like
如果可能的话,我宁愿使用单行命令,因为我也想对 rsync 使用相同的语法,如果我必须做类似的事情
find ~/plugins/ -type d -name "abc*" -exec cp -R {} ~/destination;
then that works fine for the cp
command but it would mean that I would have to run rsync once for each directory and that just doesn't seem efficient :(
那么这对于cp
命令来说工作正常,但这意味着我必须为每个目录运行一次 rsync 并且这似乎效率不高:(
采纳答案by David Gelhar
Not sure why what you're trying didn't work (but what is the "copy" command?), but this works on Linux at least:
不知道为什么您尝试的方法不起作用(但“复制”命令是什么?),但这至少适用于 Linux:
cp -r ~/plugins/abc* ~/destination
回答by Dirk Eddelbuettel
Here is an old trick I still use frequently:
这是我仍然经常使用的一个老技巧:
(cd ~/plugins/ && tar cfp - abc/) | (cd ~/destination && tar xfpv -)
where the p
preserves attributes, and ~/destination
can be anywhere.
其中p
保留属性,并且 ~/destination
可以在任何地方。
回答by Shawn Chin
It is possible to use the output of find
with rsync
:
可以使用find
with的输出rsync
:
# warning: untested
find ~/plugins/ -type d -name "abc*" -print0 | rsync -av --files-from=- --from0 ~/plugins/ ~/destination
- the
-print0
infind
, and--from0
inrsync
makes sure that we handle files with spaces correctly - the
--files-from=-
states that we are reading a list of files from stdin
- 在
-print0
中find
,并--from0
在rsync
确保我们正确处理与空格的文件 --files-from=-
我们正在从标准输入读取文件列表的状态
回答by johnny brasseur
#!/usr/bin/env perl
# copie un fichier avec l'arbo
#
#
use File::Basename;
use File::Copy;
my $source = shift;
my $dest = shift;
if( !defined $source){ print "Manque fichier source"; exit(0); }
if( !defined $dest){ print "Manque reperttheitroade dest"; exit(0); }
my $dir = dirname($source);
my $file = basename($source);
my @arbo = split(/\//, $dir);
my $direct = $dest;
if( !-d $direct ) { mkdir $direct; }
foreach my $d(@arbo) {
$direct.="/".$d;
if( !-d $direct ) { mkdir $direct; }
}
copy($source,$direct);