将文件从一个 Zip 复制到另一个?

use*_*077 6 linux scripting bash zip file-management

我有一个名为的文件 'sourceZip.zip'

此文件 ( 'sourceZip.zip') 包含两个文件:

'textFile.txt'

'binFile.bin'


我也有一个名为的文件 'targetZip.zip'

此文件 ( 'targetZip.zip') 包含一个文件:

'jpgFile.jpg'


在 linux 中,我应该使用什么 bash 命令将两个文件 ( 'textFile.txt', 'binFile.bin') 从源存档 ( 'sourceZip.zip') 直接复制到第二个存档 ( 'targetZip.zip'),以便在该过程结束时,第二个存档 ( 'targetZip.zip') 将包含所有三个文件?

(理想情况下,这将在一个命令中完成,使用“zip”或“unzip”)

Gil*_*il' 5

使用通常的命令行zip工具,我认为您无法避免单独的提取和更新命令。

source_zip=$PWD/sourceZip.zip
target_zip=$PWD/targetZip.zip
temp_dir=$(mktemp -dt)
( cd "$temp_dir"
  unzip "$source_zip"
  zip -g "$targetZip" .
  # or if you want just the two files: zip -g "$targetZip" textFile.txt binFile.bin
)
rm -rf "$temp_dir"
Run Code Online (Sandbox Code Playgroud)

还有其他语言具有更方便的 zip 文件操作库。例如,带有Archive::Zip 的Perl 。省略了错误检查。

use Archive::Zip;
my $source_zip = Archive::Zip->new("sourceZip.zip");
my $target_zip = Archive::Zip->new("targetZip.zip");
for my $member ($source_zip->members()) {
          # or (map {$source_zip->memberNamed($_)} ("textFile.txt", "binFile.bin"))
    $target_zip->addMember($member);
}
$target_zip->overwrite();
Run Code Online (Sandbox Code Playgroud)

另一种方法是将 zip 文件挂载为目录。挂载其中一个 zip 文件就足够了,您可以使用zipunzip在另一侧。Avfs为许多存档格式提供只读支持。

mountavfs
target_zip=$PWD/targetZip.zip
(cd "$HOME/.avfs$PWD/sourceZip.zip#" &&
 zip -g "$target_zip" .)  # or list the files, as above
umountavfs
Run Code Online (Sandbox Code Playgroud)

Fuse-zip提供对 zip 存档的读写访问权限,因此您可以使用 .zip 文件复制文件cp

source_dir=$(mktemp -dt)
target_dir=$(mktemp -dt)
fuse-zip sourceZip.zip "$source_dir"
fuse-zip targetZip.zip "$target_dir"
cp -Rp "$source_dir/." "$target_dir" # or list the files, as above
fusermount -u "$source_dir"
fusermount -u "$target_dir"
rmdir "$source_dir" "$target_dir"
Run Code Online (Sandbox Code Playgroud)

警告:我直接在浏览器中输入了这些脚本。使用风险自负。