2009-12-07 20:01:59 +0000 2009-12-07 20:01:59 +0000
89
89
Advertisement

Como posso descomprimir um .tar.gz num só passo (usando 7-Zip)?

Advertisement

Estou a utilizar o 7-Zip no Windows XP e sempre que descarrego um ficheiro .tar.gz são necessários dois passos para extrair completamente o(s) ficheiro(s).

  1. clico com o botão direito no ficheiro example.tar.gz e escolho 7-Zip –> Extrair Aqui* do menu de contexto.
  2. Em seguida, pego no ficheiro example.tar* resultante e clico novamente com o botão direito e escolho 7-Zip –> Extrair Aqui* do menu de contexto.

Há alguma forma de passar pelo menu de contexto num só passo?

Advertisement
Advertisement

Respostas (7)

49
49
49
2009-12-07 20:07:52 +0000

Nem por isso. Um ficheiro .tar.gz ou .tgz é realmente de dois formatos: .tar é o arquivo, e .gz é a compressão. Assim, a primeira etapa descomprime, e a segunda etapa extrai o arquivo.

Para fazer tudo num só passo, é necessário o programa tar. (http://www.cygwin.com/) inclui isto.

tar xzvf foobaz.tar.gz

; x = eXtract 
; z = filter through gZip
; v = be Verbose (show activity)
; f = filename

Também pode fazê-lo “num só passo” abrindo o ficheiro na GUI 7-zip: Abra o ficheiro .tar.gz, faça duplo clique no ficheiro .tar incluído, depois extraia esses ficheiros para a sua localização de escolha.

Há um longo fio condutor aqui de pessoas que pedem/votam para tratar os ficheiros tgz e bz2 num só passo. A falta de acção até agora indica que isso não vai acontecer até que alguém dê um passo e contribua significativamente (código, dinheiro, alguma coisa).

26
26
26
2013-02-05 02:07:01 +0000

Pergunta antiga, mas eu estava hoje a debater-me com ela, por isso aqui está o meu 2c. A ferramenta de linha de comando 7zip “7z.exe” (tenho a v9.22 instalada) pode escrever para stdout e ler a partir de stdin para que se possa passar sem o ficheiro de alcatrão intermédio utilizando um tubo:

7z x "somename.tar.gz" -so | 7z x -aoa -si -ttar -o"somename"

Onde:

x = Extract with full paths command
-so = write to stdout switch
-si = read from stdin switch
-aoa = Overwrite all existing files without prompt.
-ttar = Treat the stdin byte stream as a TAR file
-o = output directory

Veja o ficheiro de ajuda (7-zip.chm) no directório de instalação para mais informações sobre os comandos de linha de comando e interruptores.

Pode criar uma entrada de menu de contexto para ficheiros .tar.gz/.tgz que chama o comando acima usando regedit ou uma ferramenta de terceiros como stexbar .

10
Advertisement
10
10
2018-01-07 20:23:00 +0000
Advertisement

A partir do 7-zip 9.04 há uma opção de linha de comando para fazer a extracção combinada sem utilizar armazenamento intermédio para o ficheiro .tar simples:

7z x -tgzip -so theinputfile.tgz | 7z x -si -ttar

-tgzip é necessário se o ficheiro de entrada for nomeado .tgz em vez de .tar.gz.

4
4
4
2011-11-26 05:34:01 +0000

Está a utilizar Windows XP, por isso deve ter o Windows Scripting Host instalado por defeito. Dito isto, aqui está um script WSH JScript para fazer o que precisa. Basta copiar o código para um nome de ficheiro xtract.bat* ou algo do género (Pode ser o que quiser desde que tenha a extensão .bat), e correr:

xtract.bat example.tar.gz

Por defeito, o script irá verificar a pasta do script, bem como a variável de ambiente PATH do seu sistema para 7z.exe. Se quiser alterar a forma como procura as coisas, pode alterar a variável SevenZipExe no topo do script para o nome que quiser que o nome executável seja. (Por exemplo, 7za.exe ou 7z-real.exe) Também pode definir um directório padrão para o executável, alterando SevenZipDir. Assim, se 7z.exe estiver em C:\Windows\system32z.exe, colocaria:

var SevenZipDir = "C:\Windows\system32";

De qualquer modo, aqui está o script:

@set @junk=1 /* vim:set ft=javascript:
@echo off
cscript //nologo //e:jscript "%~dpn0.bat" %*
goto :eof
*/
/* Settings */
var SevenZipDir = undefined;
var SevenZipExe = "7z.exe";
var ArchiveExts = ["zip", "tar", "gz", "bzip", "bz", "tgz", "z", "7z", "bz2", "rar"]

/* Multi-use instances */
var WSH = new ActiveXObject("WScript.Shell");
var FSO = new ActiveXObject("Scripting.FileSystemObject");
var __file__ = WScript.ScriptFullName;
var __dir__ = FSO.GetParentFolderName( __file__ );
var PWD = WSH.CurrentDirectory;

/* Prototypes */
(function(obj) {
    obj.has = function object_has(key) {
        return defined(this[key]);
    };
    return obj;
})(this.Object.prototype);

(function(str) {
    str.trim = function str_trim() {
        return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };
})(this.String.prototype);

(function(arr) {
    arr.contains = function arr_contains(needle) {
        for (var i in this) {
            if (this[i] == needle) {
                return true;
            }
        }
        return false;
    }
})(this.Array.prototype);

/* Utility functions */
function defined(obj)
{
    return typeof(obj) != "undefined";
}

function emptyStr(obj)
{
    return !(defined(obj) && String(obj).length);
}

/* WSH-specific Utility Functions */
function echo()
{
    if(!arguments.length) return;
    var msg = "";
    for (var n = 0; n < arguments.length; n++) {
        msg += arguments[n];
        msg += " ";
    }
    if(!emptyStr(msg))
        WScript.Echo(msg);
}

function fatal(msg)
{
    echo("Fatal Error:", msg);
    WScript.Quit(1);
}

function findExecutable()
{
    // This function searches the directories in;
    // the PATH array for the specified file name;
    var dirTest = emptyStr(SevenZipDir) ? __dir__ : SevenZipDir;
    var exec = SevenZipExe;
    var strTestPath = FSO.BuildPath(dirTest, exec);
    if (FSO.FileExists(strTestPath))
        return FSO.GetAbsolutePathName(strTestPath);

    var arrPath = String(
            dirTest + ";" + 
            WSH.ExpandEnvironmentStrings("%PATH%")
        ).split(";");

    for(var i in arrPath) {
        // Skip empty directory values, caused by the PATH;
        // variable being terminated with a semicolon;
        if (arrPath[i] == "")
            continue;

        // Build a fully qualified path of the file to test for;
        strTestPath = FSO.BuildPath(arrPath[i], exec);

        // Check if (that file exists;
        if (FSO.FileExists(strTestPath))
            return FSO.GetAbsolutePathName(strTestPath);
    }
    return "";
}

function readall(oExec)
{
    if (!oExec.StdOut.AtEndOfStream)
      return oExec.StdOut.ReadAll();

    if (!oExec.StdErr.AtEndOfStream)
      return oExec.StdErr.ReadAll();

    return -1;
}

function xtract(exec, archive)
{
    var splitExt = /^(.+)\.(\w+)$/;
    var strTmp = FSO.GetFileName(archive);
    WSH.CurrentDirectory = FSO.GetParentFolderName(archive);
    while(true) {
        var pathParts = splitExt.exec(strTmp);
        if(!pathParts) {
            echo("No extension detected for", strTmp + ".", "Skipping..");
            break;
        }

        var ext = pathParts[2].toLowerCase();
        if(!ArchiveExts.contains(ext)) {
            echo("Extension", ext, "not recognized. Skipping.");
            break;
        }

        echo("Extracting", strTmp + "..");
        var oExec = WSH.Exec('"' + exec + '" x -bd "' + strTmp + '"');
        var allInput = "";
        var tryCount = 0;

        while (true)
        {
            var input = readall(oExec);
            if (-1 == input) {
                if (tryCount++ > 10 && oExec.Status == 1)
                    break;
                WScript.Sleep(100);
             } else {
                  allInput += input;
                  tryCount = 0;
            }
        }

        if(oExec. ExitCode!= 0) {
            echo("Non-zero return code detected.");
            break;
        }

        WScript.Echo(allInput);

        strTmp = pathParts[1];
        if(!FSO.FileExists(strTmp))
            break;
    }
    WSH.CurrentDirectory = PWD;
}

function printUsage()
{
    echo("Usage:\r\n", __file__ , "archive1 [archive2] ...");
    WScript.Quit(0);
}

function main(args)
{
    var exe = findExecutable();
    if(emptyStr(exe))
        fatal("Could not find 7zip executable.");

    if(!args.length || args(0) == "-h" || args(0) == "--help" || args(0) == "/?")
        printUsage();

    for (var i = 0; i < args.length; i++) {
        var archive = FSO.GetAbsolutePathName(args(i));
        if(!FSO.FileExists(archive)) {
            echo("File", archive, "does not exist. Skipping..");
            continue;
        }
        xtract(exe, archive);
    }
    echo("\r\nDone.");
}

main(WScript.Arguments.Unnamed);
2
Advertisement
2
2
2016-10-29 18:37:40 +0000
Advertisement

Como se pode ver o 7-Zip não é muito bom nisto. As pessoas têm pedido tarball atómico operação desde 2009. Aqui está um pequeno programa (490 KB) em Go que o pode fazer, eu compilei-o para si.

package main
import (
  "archive/tar"
  "compress/gzip"
  "flag"
  "fmt"
  "io"
  "os"
  "strings"
 )

func main() {
  flag.Parse() // get the arguments from command line
  sourcefile := flag.Arg(0)
  if sourcefile == "" {
    fmt.Println("Usage : go-untar sourcefile.tar.gz")
    os.Exit(1)
  }
  file, err := os.Open(sourcefile)
  if err != nil {
    fmt.Println(err)
    os.Exit(1)
  }
  defer file.Close()
  var fileReader io.ReadCloser = file
  // just in case we are reading a tar.gz file,
  // add a filter to handle gzipped file
  if strings.HasSuffix(sourcefile, ".gz") {
    if fileReader, err = gzip.NewReader(file); err != nil {
      fmt.Println(err)
      os.Exit(1)
    }
    defer fileReader.Close()
  }
  tarBallReader := tar.NewReader(fileReader)
  // Extracting tarred files
  for {
    header, err := tarBallReader.Next()
    if err != nil {
      if err == io.EOF {
        break
      }
      fmt.Println(err)
      os.Exit(1)
    }
    // get the individual filename and extract to the current directory
    filename := header.Name
    switch header.Typeflag {
    case tar.TypeDir:
      // handle directory
      fmt.Println("Creating directory :", filename)
      // or use 0755 if you prefer
      err = os.MkdirAll(filename, os.FileMode(header.Mode))
      if err != nil {
        fmt.Println(err)
        os.Exit(1)
      }
    case tar.TypeReg:
      // handle normal file
      fmt.Println("Untarring :", filename)
      writer, err := os.Create(filename)
      if err != nil {
        fmt.Println(err)
        os.Exit(1)
      }
      io.Copy(writer, tarBallReader)
      err = os.Chmod(filename, os.FileMode(header.Mode))
      if err != nil {
        fmt.Println(err)
        os.Exit(1)
      }
      writer.Close()
    default:
      fmt.Printf("Unable to untar type : %c in file %s", header.Typeflag,
      filename)
    }
  }
}
1
1
1
2019-04-23 02:33:30 +0000

A partir do Windows 10 build 17063, tar e curl são suportados, portanto é possível descomprimir um ficheiro .tar.gz num só passo usando o comando tar, como abaixo.

tar -xzvf your_archive.tar.gz tar --help

Tipo tar para mais informações sobre 0x6&.

0
Advertisement
0
0
2018-08-31 08:08:02 +0000
Advertisement

7za está a funcionar correctamente como abaixo:

7za.exe x D:\pkg-temp\Prod-Rtx-Service.tgz -so | 7za.exe x -si -ttar -oD:\pkg-temp\Prod-Rtx-Service
Advertisement

Questões relacionadas

3
12
8
9
6
Advertisement
Advertisement