tar: 压缩并删除原始文件并保持目录不变

tar: compress & remove original files & leave directories untouched

我所在的目录包含:

f0 f1 f2 .h1 .h2 .h3 /tmp

我想tartar所有文件并擦除原始文件。我不想 tar /tmp,也不想触摸它的 files.Following post https://unix.stackexchange.com/questions/24870/tar-files-only-no-directories,看起来没有直接的方法来执行这个,所以我尝试了以下:

find . -maxdepth 1 -type f -exec tar cvf test.tar {} --remove-files \;

几乎有效:

-存档已创建

-所有文件都被删除

-/tmp 保持不变

但是

我的存档中只有文件 f2 (!)

虽然我找到了一个非常丑陋的解决方案:

find . -maxdepth 1 -type f -exec tar cvf test.tar {} \; && find . -maxdepth 1 -type f ! -name '*.tar' -exec shred -xuvz {} \;

但更优雅的东西将不胜感激。

谢谢大家!

find . -maxdepth 1 -type f -exec tar cvf test.tar {} --remove-files \;

几乎可以,但是

there is only file f2 in my archive (!)

是的,因为 -exec 命令是针对 find 发现的每个文件单独执行的,并且 tarc 选项导致它每隔一段时间创建一个新存档时间。

有几种方法可以解决这个问题,但是对于数量不是特别多的文件,您可以将 findxargs 组合到 运行 所有文件的单个命令被 find 选中:

find . -maxdepth 1 -type f | xargs tar cvf test.tar --remove-files

这是一个很好的模式,但它确实有一些限制。特别是,

  • xargs 将从其标准输入中读取的许多参数组合成较少数量的命令,但系统和数据相关的限制可以形成一个 single命令,这就是你所需要的。如果超过这些限制,那么 xargs 将分派多个命令,这将使您回到起点。但是这些限制通常比示例案例所需的要大得多。

  • 带有空格的文件名将打破这种模式,因为 xargs 通常在空格处拆分其输入。但是,如果您有支持它的 findxargs,那么您可以通过在 find 命令中使用 -print0 谓词和 -0 选项到 xargs,在一起。当然,如果你没有任何这样的文件名,这首先不是问题。