Create zip file and ignore directory structure

后端 未结 7 1038
栀梦
栀梦 2020-12-07 10:38

I need to create a zip file using this command:

zip /dir/to/file/newZip /data/to/zip/data.txt

This works, but the created zip file creates

相关标签:
7条回答
  • 2020-12-07 11:02

    You can use -j.

    -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).
    
    0 讨论(0)
  • 2020-12-07 11:02

    Retain the parent directory so unzip doesn't spew files everywhere

    When zipping directories, keeping the parent directory in the archive will help to avoid littering your current directory when you later unzip the archive file

    So to avoid retaining all paths, and since you can't use -j and -r together ( you'll get an error ), you can do this instead:

    cd path/to/parent/dir/;
    zip -r ../my.zip ../$(basename $PWD)
    cd -;
    

    The ../$(basename $PWD) is the magic that retains the parent directory.

    So now unzip my.zip will give a folder containing all your files:

    parent-directory
    ├── file1
    ├── file2
    ├── dir1
    │   ├── file3
    │   ├── file4
    

    Instead of littering the current directory with the unzipped files:

    file1
    file2
    dir1
    ├── file3
    ├── file4
    
    0 讨论(0)
  • 2020-12-07 11:16

    Use the -j option:

       -j     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 path).
    
    0 讨论(0)
  • 2020-12-07 11:19

    Alternatively, you could create a temporary symbolic link to your file:

    ln -s /data/to/zip/data.txt data.txt
    zip /dir/to/file/newZip !$
    rm !$
    

    This works also for a directory.

    0 讨论(0)
  • 2020-12-07 11:22

    Using -j won't work along with the -r option.
    So the work-around for it can be this:

    cd path/to/parent/dir/;
    zip -r complete/path/to/name.zip ./* ;
    cd -;
    

    Or in-line version

    cd path/to/parent/dir/ && zip -r complete/path/to/name.zip ./* && cd -
    

    you can direct the output to /dev/null if you don't want the cd - output to appear on screen

    0 讨论(0)
  • 2020-12-07 11:23

    Somewhat related - I was looking for a solution to do the same for directories. Unfortunately the -j option does not work for this :(

    Here is a good solution on how to get it done: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file

    0 讨论(0)
提交回复
热议问题