Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unzipping a file and ignoring 'junk files' added by OS X

Tags:

ruby

zip

I am using code like the following to unzip files in Ruby:

def unzip_file (file)
  Zip::ZipFile.open(file) do |zip_file|
    zip_file.each do  |f| 
      puts f.name if f.file?
    end
  end
end

I would like to ignore all files generated by compress zip in Mac such as: .DS_Store, etc. How can I best do it?

like image 665
Michał Makaruk Avatar asked Sep 12 '25 19:09

Michał Makaruk


1 Answers

I believe that this does what you want:

Zip::ZipFile.open(file) do |zip_file|
  names = zip_file.select(&:file?).map(&:name)
  names.reject!{|n| n=~ /\.DS_Store|__MACOSX|(^|\/)\._/ }
  puts names
end 

That regular expression says,

  • Throw away files
    • that have .DS_Store in the name,
    • that have __MACOSX in the name,
    • or that have ._ at the beginning of the name (^) or right after a /.

That should cover all the 'junk' files and hopefully not hit any others.

If you want more than just the names—if you want to process the non-junk files—then instead you might do the following:

Zip::ZipFile.open(file) do |zip_file|
  files = zip_file.select(&:file?)
  files.reject!{|f| f.name =~ /\.DS_Store|__MACOSX|(^|\/)\._/ }
  puts files.map(&:names) # or do whatever else you want with the array of files
end 
like image 73
Phrogz Avatar answered Sep 15 '25 14:09

Phrogz