Linux 将 tar.gz 转换为 zip

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6301885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:25:49  来源:igfitidea点击:

Convert tar.gz to zip

linuxubuntuzipgzip

提问by Dan

I've got a large collection of gzipped archives on my Ubuntu webserver, and I need them converted to zips. I figure this would be done with a script, but what language should I use, and how would I go about unzipping and rezipping files?

我的 Ubuntu 网络服务器上有大量 gzipped 档案,我需要将它们转换为 zip。我认为这可以通过脚本来完成,但是我应该使用什么语言,我将如何解压缩和重新压缩文件?

回答by Sven

A simple bash script would be easiest, surely? That way you can just invoke the tarand zipcommands.

一个简单的 bash 脚本肯定是最简单的吗?这样你就可以调用tarzip命令。

回答by sarnold

I'd do it with a bash(1)one-liner:

我会用单线来做bash(1)

for f in *.tar.gz;\
do rm -rf ${f%.tar.gz} ;\
mkdir ${f%.tar.gz} ;\
tar -C ${f%.tar.gz} zxvf $f ;\
zip -r ${f%.tar.gz} $f.zip ;\
rm -rf ${f%.tar.gz} ;\
done

It isn't very pretty because I'm not great at bash(1). Note that this destroys a lot of directories so be sure you know what this does before doing it.

它不是很漂亮,因为我不擅长bash(1)。请注意,这会破坏很多目录,因此请确保在执行此操作之前知道它的作用。

See the bash(1)reference cardfor more details on the ${foo%bar}syntax.

请参见bash(1)参考卡有关更多详细信息${foo%bar}的语法。

回答by ivo Welch

the easiest solution on unix platforms may well be to use fuse and something like archivemount (libarchive), http://en.wikipedia.org/wiki/Archivemount.

unix 平台上最简单的解决方案很可能是使用 fuse 和诸如 archivemount (libarchive)、http://en.wikipedia.org/wiki/Archivemount 之类的东西

/iaw

/iaw

回答by coderaiser

You can use node.jsand tar-to-zipfor this purpose. All you need to do is:

为此,您可以使用node.jstar-to-zip。您需要做的就是:

Install node.js with nvmif you do not have it.

如果没有,请使用nvm安装node.js。

And then install tar-to-zipwith:

然后安装tar-to-zip

npm i tar-to-zip -g

And use it with:

并将其用于:

tarzip *.tar.gz

Also you can convert .tar.gzfiles to .zipprogrammatically. You should install asyncand tar-to-ziplocally:

您也可以.tar.gz.zip编程方式将文件转换为。您应该安装asynctar-to-zip本地:

npm i async tar-to-zip

And then create converter.jswith contents:

然后converter.js用内容创建:

#!/usr/bin/env node

'use strict';

const fs = require('fs');
const tarToZip = require('tar-to-zip');
const eachSeries = require('async/eachSeries');
const names = process.argv.slice(2);

eachSeries(names, convert, exitIfError);

function convert(name, done) {
    const {stdout} = process;
    const onProgress = (n) => {
        stdout.write(`\r${n}%: ${name}`);
    };
    const onFinish = (e) => {
        stdout.write('\n');
        done();
    };

    const nameZip = name.replace(/\.tar\.gz$/, '.zip');    
    const zip = fs.createWriteStream(nameZip)
        .on('error', (error) => {
            exitIfError(error);
            fs.unlinkSync(zipPath);
        });

    const progress = true;
    tarToZip(name, {progress})
        .on('progress', onProgress)
        .on('error', exitIfError)
        .getStream()
        .pipe(zip)
        .on('finish', onFinish);
}

function exitIfError(error) {
    if (!error)
        return;

    console.error(error.message);
    process.exit(1);
}

回答by mmaruska

Zipfiles are handy because they offer random access to files. Tar files only sequential.

Zipfiles 很方便,因为它们提供对文件的随机访问。tar 文件只能按顺序进行。

My solution for this conversion is this shell script, which calls itself via tar(1) "--to-command" option. (I prefer that rather than having 2 scripts). But I admit "untar and zip -r" is faster than this, because zipnote(1) cannot work in-place, unfortunately.

我对这种转换的解决方案是这个 shell 脚本,它通过 tar(1) "--to-command" 选项调用自己。(我更喜欢那个而不是有 2 个脚本)。但我承认“untar and zip -r”比这更快,因为不幸的是,zipnote(1) 不能就地工作。

#!/bin/zsh -feu

## Convert a tar file into zip:

usage() {
    setopt POSIX_ARGZERO
    cat <<EOF
    usage: ${0##*/} [+-h] [-v] [--] {tarfile} {zipfile}"

-v verbose
-h print this message
converts the TAR archive into ZIP archive.
EOF
    unsetopt POSIX_ARGZERO
}

while getopts :hv OPT; do
    case $OPT in
        h|+h)
            usage
            exit
            ;;
        v)
            # todo: ignore TAR_VERBOSE from env?
            # Pass to the grand-child process:
            export TAR_VERBOSE=y
            ;;
        *)
            usage >&2
            exit 2
    esac
done
shift OPTIND-1
OPTIND=1

# when invoked w/o parameters:
if [ $# = 0 ] # todo: or stdin is not terminal
then
    # we are invoked by tar(1)
    if [ -n "${TAR_VERBOSE-}" ]; then echo $TAR_REALNAME >&2;fi
    zip --grow --quiet $ZIPFILE -
    # And rename it:
    # fixme: this still makes a full copy, so slow.
    printf "@ -\n@=$TAR_REALNAME\n" | zipnote -w $ZIPFILE
else
    if [ $# != 2 ]; then usage >&2; exit 1;fi
    # possibly: rm -f $ZIPFILE
    ZIPFILE= tar -xaf  --to-command=
import sys, tarfile, zipfile, glob

def convert_one_archive(file_name):
    out_file = file_name.replace('.tar.gz', '.zip')
    with tarfile.open(file_name, mode='r:gz') as tf:
        with zipfile.ZipFile(out_file, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:
            for m in tf.getmembers():
                f = tf.extractfile( m )
                fl = f.read()
                fn = m.name
                zf.writestr(fn, fl)

for f in glob.glob('*.tar.gz'):
    convert_one_archive(f)
fi

回答by Brad Campbell

Here is a python solution based on this answer here:

这是基于此答案的python解决方案:

##代码##