Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zipping a directory recursively & skip container directory

Consider, we have following directory structure:

Location:
/Users/me/Desktop/directory_to_zip/
dir1 dir2 somefile.txt

now, If I use rubyzip to zip the contents of directory_to_zip using the following code:

directory = '/Users/me/Desktop/directory_to_zip/'
zipfile_name = '/Users/me/Desktop/recursive_directory.zip'

Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
    Dir[File.join(directory, '**', '**')].each do |file|
      zipfile.add(file.sub(directory, ''), file)
    end
end

This will create a zip file named recursive_directory.zip, which will contain a container directory called directory_to_zip & inside directory_to_zip, will I find my files(dir1 dir2 somefile.txt)

HOw do I skip creation of directory_to_zip inside recursive_directory.zip, so that the zip file just contains the contents of directory_to_zip & not the directory itself.

like image 990
CuriousMind Avatar asked Feb 02 '14 20:02

CuriousMind


People also ask

How do I zip a folder recursively?

Use the zipfile module to create a zip archive of a directory. Walk the directory tree using os. walk and add all the files in it recursively.

Can you zip folders with subfolders?

Creating a zip folder allows files to be organized and compressed to a smaller file size for distribution or saving space. Zip folder can have subfolders within this main folder.

How do I zip all subfolders?

To add all files in the folder and subfolder, we can use the -r command, which will compress all the files in the folder.

Are zips recursive?

By default, the zip command doesn't archive a directory recursively. By using the flag -r, zip will traverse subdirectories recursively and archive their files. Running the command with option -r ensures the files within the directory are included as well.


1 Answers

Okay, I solved this on my own. If you are in same boat, here is here how I did it:

Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
  Dir.chdir directory
  Dir.glob("**/*").reject {|fn| File.directory?(fn) }.each do |file|
    puts "Adding #{file}"
    zipfile.add(file.sub(directory + '/', ''), file)
  end
end

This works exactly I want. the limitation here here is that it doesn't handle empty directories. Hopefully, it would help someone.

like image 143
CuriousMind Avatar answered Oct 06 '22 06:10

CuriousMind