How to package separately located files into a same folder structure?

zip
5,419

Solution 1

Use the -j option to zip to remove (junk) the paths:

-j
--junk-paths
Store just the name of a saved file (junk the path), and do not store directory names. By default, zip will store the full path (relative to the current directory).

Example

For example, suppose that we have these files:

$ ls */
a/:
file

b/:
file2

And we zip them with -j:

$ zip -j new.zip */*
  adding: file (stored 0%)
  adding: file2 (stored 0%)

They are stored without paths:

$ unzip -l new.zip
Archive:  new.zip
  Length      Date    Time    Name ("^" ==> case
---------  ---------- -----   ----   conversion)
        0  2014-10-21 22:15   file
        0  2014-10-21 22:14   file2
---------                     -------
        0                     2 files

Files with same basename will generate an error

Note that, with -j, if two files from different paths have the same name, it is an error:

$ zip -j new2.zip */*
        zip warning:   first full name: a/file
                      second full name: b/file
                     name in zip file repeated: file
                     this may be a result of using -j

zip error: Invalid command arguments (cannot repeat names in zip file)

Solution 2

The zip utility has the option --junk-path for that:

$ zip --junk-path pack.zip home/jack/jack.txt home/jim/jim.txt
  adding: jack.txt (stored 0%)
  adding: jim.txt (stored 0%)
$ unzip -l pack.zip 
Archive:  pack.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2014-10-22 07:12   jack.txt
        0  2014-10-22 07:12   jim.txt
---------                     -------
        0                     2 files
Share:
5,419

Related videos on Youtube

Tommy
Author by

Tommy

Something for nothing. Bite me if you can score 9+ in a CPS Test.

Updated on September 18, 2022

Comments

  • Tommy
    Tommy over 1 year

    When I use zip to pack files from different locations, like:

    zip pack.zip /home/jack/jack.txt /home/jim/jim.txt

    The files would be stored in "pack.zip" as the following structure:

    ./home/jack/jack.txt
    ./home/jim/jim.txt
    

    But this is not what I expected. I just hope the files be stored in the root of the zip file like:

    ./jack.txt
    ./jim.txt
    

    What should I do?

  • Thorbjørn Ravn Andersen
    Thorbjørn Ravn Andersen over 6 years
    zip -r -j zip.file dir will work too.