Unzip a file into a target directory?

I have a file called All CRGs.zip and I want to unzip its contents into a directory called data (which already exists and has some other files in).

Is this possible? I'm working on OSX.

I've tried:

$ unzip "All CRGs.zip" -d data/

But this unzips everything into data/All CRGs which is not what I'm looking for. I'd like everything to go straight into data.

Is this possible?


Solution 1:

You can either recreate the complete folder-structure including the All CRGs-Folder or you can ommit all folders inside the ZIP-file by using the -j-flag for the unzip-command.

The problem is that the ZIP-file has been created using the All CRGs-Folder as top-level like zip "All CRGs.zip" "All CRGs". The correct way would have been zip "All CRGs.zip" "All CRGs/*"which would have created a ZIP-Archive of all the files and folders inside the All CRGs-folder without the surrounding folder.

So the only way to extract only the files by retaining the folder-structure would be something like this:

unzip "All CRGs.zip" -d data/ && mv "data/All CRGs/*" "data/" && rmdir "data/All CRGs"

It will unzip the complete folder and after that move the content of the folder up one level and finaly remove the (now empty) "All CRGs"-folder.

Solution 2:

Since you know the zip file contains an unwanted top-level folder, and since you know the name of that top level folder, you can use a symlink to cause all the contents of that folder to appear in the parent like so:

ln -s . 'data/All CRGs'
unzip 'All CRGs.zip' -d data

The ln step causes the folder data/All CRGs to be created, linking to the current directory (relative to data/), which is data/. Then, when you extract files from All CRGs.zip and the unzip command tries to create data/All CRGs/file.dat, that file will get created as data/./file.dat.

This technique can be demonstrated without a zip file using touch:

$ mkdir data
$ ln -s . data/subdir     
$ touch data/subdir/foo.txt
$ ls data
foo.txt subdir

You can use this trick too to cause certain files or folders to be extracted to an alternate folder:

ln -s /tmp data/subdir2

Then anything in the archive being extracted to subdir2 will appear in /tmp.