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

¿Cómo puedo descomprimir un .tar.gz en un solo paso (utilizando 7-Zip)?

Advertisement

Estoy usando 7-Zip en Windows XP y cada vez que descargo un archivo .tar.gz me lleva dos pasos para extraer completamente el archivo(s).

  1. Hago clic con el botón derecho del ratón en el archivo ejemplo.tar.gz y elijo 7-Zip –> Extraer aquí del menú contextual.
  2. Luego tomo el archivo resultante ejemplo.tar y vuelvo a hacer clic con el botón derecho y elijo 7-Zip –> Extraer aquí del menú contextual.

¿Hay alguna manera de hacer esto en un solo paso a través del menú contextual?

Advertisement
Advertisement

Respuestas (7)

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

No es así. Un archivo .tar.gz o .tgz son realmente dos formatos: .tar es el archivo, y .gz es la compresión. Así que el primer paso descomprime y el segundo extrae el archivo.

Para hacerlo todo en un solo paso, necesitas el programa tar. Cygwin lo incluye.

tar xzvf foobaz.tar.gz

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

También podrías hacerlo “en un solo paso” abriendo el archivo en la GUI de 7-zip: Abre el archivo .tar.gz, haz doble clic en el archivo .tar incluido, y luego extrae esos archivos a la ubicación que prefieras.

Hay un hilo que lleva mucho tiempo aquí de gente pidiendo/votando por el manejo en un solo paso de los archivos tgz y bz2. La falta de acción hasta ahora indica que no va a suceder hasta que alguien dé un paso y contribuya significativamente (código, dinero, algo).

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

Vieja pregunta, pero yo estaba luchando con él hoy así que aquí está mi 2c. La herramienta de línea de comandos de 7zip “7z.exe” (tengo instalada la versión 9.22) puede escribir en stdout y leer desde stdin, por lo que se puede prescindir del archivo tar intermedio utilizando una tubería:

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

Donde:

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

Consulte el archivo de ayuda (7-zip.chm) en el directorio de instalación para obtener más información sobre los comandos de la línea de comandos y los interruptores.

Puede crear una entrada en el menú contextual para los archivos .tar.gz/.tgz que llame al comando anterior utilizando regedit o una herramienta de terceros como stexbar .

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

A partir de 7-zip 9.04 existe una opción de línea de comandos para realizar la extracción combinada sin utilizar el almacenamiento intermedio para el archivo .tar plano:

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

-tgzip es necesaria si el archivo de entrada se llama .tgz en lugar de .tar.gz.

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

Estás usando Windows XP, así que deberías tener instalado por defecto el Windows Scripting Host. Dicho esto, aquí tienes un script WSH JScript para hacer lo que necesitas. Sólo tienes que copiar el código en un archivo con el nombre xtract.bat o algo parecido (puede ser cualquier cosa siempre que tenga la extensión .bat), y ejecutarlo:

xtract.bat example.tar.gz

Por defecto, el script comprobará la carpeta del mismo, así como la variable de entorno PATH de tu sistema en busca de 7z.exe. Si quieres cambiar la forma en que busca las cosas, puedes cambiar la variable SevenZipExe en la parte superior del script a lo que quieras que sea el nombre del ejecutable. (Por ejemplo, 7za.exe o 7z-real.exe) También puedes establecer un directorio por defecto para el ejecutable cambiando SevenZipDir. Así que si 7z.exe está en C:\Windows\system32z.exe, pondrías:

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

De todas formas, aquí está el 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 puedes ver 7-Zip no es muy bueno en esto. La gente ha estado pidiendo operación atómica de tarball desde 2009. Aquí hay un pequeño programa ](https://socketloop.com/tutorials/golang-untar-or-extract-tar-ball-archive-example)(490 KB) en Go que puede hacerlo, lo he compilado para ti.

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 de la compilación 17063 de Windows 10, se admiten tar y curl, por lo que es posible descomprimir un archivo .tar.gz en un solo paso utilizando el comando tar, como se indica a continuación.

tar -xzvf your_archive.tar.gz

Escriba tar --help para obtener más información sobre tar.

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

7za funciona correctamente como se indica a continuación:

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

Preguntas relacionadas

3
12
8
9
5
Advertisement
Advertisement