我想复制一个目录中的所有文件,除了特定子目录中的一些文件。 我注意到cp命令没有——exclude选项。 那么,我怎么才能做到呢?


当前回答

Rsync又快又简单:

rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude

你可以使用-排除多次。

rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherfoldertoexclude

注意——exclude选项后的目录thefoldertoexclude是相对于源文件夹的,即:sourcefolder/thefoldertoexclude。

此外,您还可以添加-n进行演练,以查看在执行实际操作之前将复制什么,如果一切正常,则从命令行中删除-n。

其他回答

我猜你用的是bash或dash。这样能行吗?

shopt -s extglob  # sets extended pattern matching options in the bash shell
cp $(ls -laR !(subdir/file1|file2|subdir2/file3)) destination

执行ls,排除你不想要的文件,并使用它作为cp的第一个参数

为什么要使用rsync,当你可以:

find . -type f -not -iname '*/not-from-here/*' -exec cp '{}' '/dest/{}' ';'

这假设目标目录结构与源目录结构相同。

我发现的最简单的方法是,你可以复制除文件和文件夹以外的所有文件,只需在括号中添加它们的名称:

shopt -s extglob
cp -r !(Filename1 | FoldernameX | Filename2) Dest/
cp -rv `ls -A | grep -vE "dirToExclude|targetDir"` targetDir

编辑:忘记排除目标路径(否则它将递归复制)。

Rsync又快又简单:

rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude

你可以使用-排除多次。

rsync -av --progress sourcefolder /destinationfolder --exclude thefoldertoexclude --exclude anotherfoldertoexclude

注意——exclude选项后的目录thefoldertoexclude是相对于源文件夹的,即:sourcefolder/thefoldertoexclude。

此外,您还可以添加-n进行演练,以查看在执行实际操作之前将复制什么,如果一切正常,则从命令行中删除-n。