Extract multiple files from gzip in ruby

1.3k Views Asked by At

Actually i have a multiple .txt files in a .gz file. I would like to extract all the .txt files from .gz file... For example:

gz_extract = Zlib::GzipReader.open("sample.gz")
gz_extract.each do |extract|
  print extract
end

The above code actually prints whatever is present in the .gz file but actually i want to un-gzip the .txt files. I hope you ppl understood the question....

1

There are 1 best solutions below

3
On BEST ANSWER

Actually i have a multiple .txt files in a .gz file. I would like to extract all the .txt files from .gz file.

gzip cannot contain multiple files together. It only works with one file.

If you want to compress multiple files, you first need to tar them together, and then gzip the resulting .tar file, which does not appear to the case with the file you are using.

If you can read the contents of the sample.gz with the code you provided, this is further proof you have only one file inside. You can also try gunzip sample.gz from the command-line to again prove it contains only one file.

EDIT:

If you want the code to output an uncompressed .txt file:

output_file = File.open('sample.txt', 'w')

gz_extract = Zlib::GzipReader.open("sample.gz")
gz_extract.each_line do |extract|
  output_file.write(extract)
end

output_file.close