How to read and get the complete text line from compressed file using golang

657 Views Asked by At

There is a compressed text file(.gz) has some set of warning, error and information details.

Sample content.

Oct 25 06:58:51 : For info, please visit https://www.det.org
Oct 25 06:58:51 : Copyright 2004-2018 Internet Systems Consortium.
Oct 25 06:58:51 : All rights reserved.
Oct 25 06:58:51 : ERROR: Host declarations are global.
Oct 25 06:58:51 : WARNING: Host declarations are global

I need to get the warning and error complete line from the text file without uncompressed using golang. How can develop an algorithm for this?

1

There are 1 best solutions below

0
Ibjas Mohamed On

Here is the answer I solved above question.

cmd := exec.Command(`zgrep`, `WARNING\|ERROR`, filename)
stdout, err := cmd.StdoutPipe()

if err != nil {
    log.Fatal(err)
}

if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

data, err := ioutil.ReadAll(stdout)

if err != nil {
    log.Fatal(err)
}

if err := cmd.Wait(); err != nil {
    
        log.Fatalf("cmd.Wait: %v", err)
    
}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
    fmt.Println(line)
    
}