如何复制目录和子文件夹但忽略子文件夹中的某些文件?

mrj*_*per 6 cp recursive file-copy

我相信这个问题最好用一个例子来问。

/home
   test1.txt
   test2.txt
   /home/my-folder
      test3.txt
      test4.txt
Run Code Online (Sandbox Code Playgroud)
  1. test1.txttest2.txtmy-folder文件夹在里面/home
  2. test3.txt并且text4.txt在里面/home/my-folder

我想复制/home文件夹的所有内容,但排除里面的 2 个文件(test3.txttest4.txtmy-folder

我该如何使用cp

我知道这是可能的,rsync因为我刚刚尝试过,但有时rsync未安装在服务器中并且我无权安装软件。

lcd*_*047 7

你可以用find(1)and做到cpio(1)

find /home -path './my-folder/test[34].txt' -prune -o \( -type f -print \) | \
    cpio -pdamv /some/other/dir
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 5

您无法cp单独完成此操作,除非列出要复制的文件。制作部分副本超出了cp的能力范围。

Rsync 是完成这项工作的明显工具,而且应用非常广泛。

如果您只有 POSIX 工具,则可以使用pax。您可以通过将文件路径重写为空字符串来省略文件。

cd /home && pax -rw -pe -s'~^\./my-folder/test[34]\.txt$~~' . /path/to/destination
Run Code Online (Sandbox Code Playgroud)

如果您只有一个缺少 的最小 Linux 服务器pax,请查看其传统的等效项cpiotar是否可用。有关示例,请参阅lcd047 的答案cpio。使用GNU tar,你可以做到

mkdir /path/to/destination
tar -cf - -C /home --exclude='./my-folder/test[34].txt' . |
  tar -xf - -C /path/to/destination
Run Code Online (Sandbox Code Playgroud)