Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read contents of tar file without unzipping to disk

Tags:

go

tar

I have been able to loop through the files in a tar file, but I am stuck on how to read the contents of those files as string. I would like to know how to print the contents of the files as a string?

This is my code below

package main

import (
    "archive/tar"
    "fmt"
    "io"
    "log"
    "os"
    "bytes"
    "compress/gzip"
)

func main() {
    file, err := os.Open("testtar.tar.gz")

    archive, err := gzip.NewReader(file)

    if err != nil {
        fmt.Println("There is a problem with os.Open")
    }
    tr := tar.NewReader(archive)

    for {
        hdr, err := tr.Next()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        fmt.Printf("Contents of %s:\n", hdr.Name)
    }
}
like image 620
m.. Avatar asked Mar 02 '17 19:03

m..


People also ask

How can I view tar files without extracting them?

With the tar command, you can use -t to view the contents of tar. gz files with the list of details. The -t switch is used to list the contents of the tar. gz file without actually extracting it.

How do I open a Tar GZ file without unzipping it in Linux?

Use -t switch with tar command to list content of a archive. tar file without actually extracting. You can see that output is pretty similar to the result of ls -l command.

How do you check the contents of a ZIP file in Linux without extracting?

If you need to check the contents of a compressed text file on Linux, you don't have to uncompress it first. Instead, you can use a zcat or bzcat command to extract and display file contents while leaving the file intact. The "cat" in each command name tells you that the command's purpose is to display content.

Which of the following command is used to see the content of tar file without extracting it?

Use '-t' option in tar command to view the content of tar files without extracting it.


1 Answers

Just use the tar.Reader as an io.Reader for each file you want to read.

tr := tar.NewReader(r)

// get the next file entry 
h, _ := tr.Next() 

If you need the whole file as a string:

// read the complete content of the file h.Name into the bs []byte
bs, _ := ioutil.ReadAll(tr)

// convert the []byte to a string
s := string(bs)

If you need to read line by line, then this would be better:

// create a Scanner for reading line by line
s := bufio.NewScanner(tr)

// line reading loop
for s.Scan() {

  // read the current last read line of text
  l := s.Text()

  // ...and do something with l

}

// you should check for error at this point
if s.Err() != nil {
  // handle it
}
like image 143
Pablo Lalloni Avatar answered Sep 20 '22 23:09

Pablo Lalloni