如何在不复制终端中的特定文件或子目录的情况下复制目录?

zia*_*ome 6 command-line gnome-terminal cp

我有一个目录 main_dir,其中包含许多文件和 3 个子目录(dir1 和 dir2 和 dir3)。我想将它复制到另一个位置,而不是在一个命令中复制 dir2。我搜索了 cp 手册,看看是否可以以某种方式完成,但我没有找到答案。我唯一的解决方案是复制整个目录,然后在复制的位置删除 dir2。

cp -r main_dir ~/Documents/main_dir_copy
cd ~/Documents/main_dir_copy
rm -r dir2
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点而不必复制 dir2 的所有内容然后删除它?

ste*_*ver 9

在 bash 中,您可以使用扩展的 glob来实现否定。

给定的

$ tree main_dir
main_dir
??? dir1
?   ??? other file
?   ??? somefile
??? dir2
?   ??? other file
?   ??? somefile
??? dir3
?   ??? other file
?   ??? somefile
??? file

3 directories, 7 files
Run Code Online (Sandbox Code Playgroud)

然后

shopt -s extglob
cp -r main_dir/!(dir2) main_dir_copy/
Run Code Online (Sandbox Code Playgroud)

导致

$ tree main_dir_copy
main_dir_copy
??? dir1
?   ??? other file
?   ??? somefile
??? dir3
?   ??? other file
?   ??? somefile
??? file

2 directories, 5 files
Run Code Online (Sandbox Code Playgroud)

需要注意的是,因为这递归复制内容main_dir(不包括定dir2),而不是main_dir本身的目标目录main_dir_copy必须已经存在-如果没有,添加mkdir main_dir_copy到命令序列。

也可以看看