unzip (zip, tar, tag.gz) files with ruby

gustavgans picture gustavgans · May 13, 2009 · Viewed 37.7k times · Source

I want to unzip a lot of zip files. Is there a module or script that checks which format the zip file is and decompresses it? This should work on Linux, I don't care about other OSs.

Answer

Florian Feldhaus picture Florian Feldhaus · Jul 16, 2012

To extract files from a .tar.gz file you can use the following methods from packages distributed with Ruby:

require 'rubygems/package'
require 'zlib'
tar_extract = Gem::Package::TarReader.new(Zlib::GzipReader.open('Path/To/myfile.tar.gz'))
tar_extract.rewind # The extract has to be rewinded after every iteration
tar_extract.each do |entry|
  puts entry.full_name
  puts entry.directory?
  puts entry.file?
  # puts entry.read
end
tar_extract.close

Each entry of type Gem::Package::TarReader::Entry points to a file or directory within the .tar.gz file.

Similar code can be used (replace Reader with Writer) to write files to a .tar.gz file.