Linux - 压缩特定文件同时保留路径和文件夹结构

Linux - 压缩特定文件同时保留路径和文件夹结构

所以,基本上我想这样做:仅压缩文件夹中的特定文件,同时保留文件夹结构 但不要使用 Windows 和 7Z,而是在 Linux 上使用原生 Linux 工具(无需 root 权限)来执行。

我想将一个非常大的目录(包含很多嵌套目录)备份到 .zip 文件(最好)或 tarball 中。该文件应该:

  • 仅包含具有特定扩展名的文件和/或小于特定大小的文件
  • 拥有我正在备份的目录的完整文件夹结构
  • 如果可能的话,仍然在备份中保留空目录(例如,如果目录没有任何匹配的文件,则仍会在存档中创建该目录)

环顾四周后,我认为下面的一行代码可以起作用,其中涉及一个我从未听说过的命令cpio

find /path/to/backup/ -iname '*README*' -o -name '*.py' -o -name '*.sh' -o -type d | cpio -pdm mybackup.zip

备份所有 python 和 shell 脚本以及自述文件和文件夹结构。但是,结果mybackup.zip实际上是一个目录,而不是压缩档案。

因此一行代码变为:

mkdir backup_dir
find /path/to/backup -iname '*README*' -o -name '*.py' -o -name '*.sh' -o -type d | cpio -pdm backup_dir
zip -r backup.zip backup_dir
rm -r backup_dir

这意味着创建一个临时文件backup_dir作为中间步骤。这是一个很小的代价,因为它完全符合我的要求。文件大小要求可以作为选项添加到find,例如-size -10M对于小于 10Mb 的文件。

但是有没有更好的方法呢?这种方法有什么注意事项吗?或者有没有更快的方法?

答案1

您可以将要压缩的文件直接导入管道,然后使用选项zip从 STDIN 读取-@

以下是 zip 手册页的摘录

   -@ file lists.  If a file list is specified as -@, zip takes the list of input 
   files from standard input instead of from the command line.  For example,

          zip -@ foo

   will store the files listed one per line on stdin in foo.zip.

   Under Unix, this option can be used to powerful effect in conjunction with the 
   find command.  For example, to archive all the C source files in the current
   directory and its subdirectories:

          find . -name "*.[ch]" -print | zip source -@

因此,对于您来说,命令变成这样:

find /path/to/backup -iname '*README*' -o -name '*.py' -o -name '*.sh' -o -type d | zip backup.zip -@

相关内容