Unix zipping sub directory not including parent di

2020-06-12 05:12发布

问题:

I want to zip a sub directory and send it elsewhere, the problem I have is when I use the zip command it also includes all the unwanted layers of directories I do not want.

e.g.

zip -r /new.zip /Unwanted1/Unwanted2/wanted1/wanted2/file.txt

###unzipped produces the following
/Unwanted1/Unwanted2/wanted1/wanted2/file.txt

###I want
/wanted1/wanted2/file.txt

update: The directory I want to zip has lots of nested directories, hence the -r. Also it would be great to deal with absolute paths, the old solution used to cd about the place but I just didn't really like it. Perhaps that is the best (only) way.

回答1:

You have to change directories to wherever you want to start, or maybe there's an option to 'zip' to do that for you. If you're too lazy to read through the gazillion options in the man page, like I am, just 'cd' first, even in a script. Or you can enclose the whole thing in parenthesis without affecting your shell or script's working directory:

(cd Unwanted1/Unwanted2; zip -r ~/new.zip ./wanted/file.txt)

Or since you're using -r you presumably want more than just file.txt, so:

(cd Unwanted1/Unwanted2; zip -r ~/new.zip wanted)

Or use pushd/popd to jump in/out:

pushd Unwanted1/Unwanted2
zip -r ~/new.zip wanted
popd

This works in sh/bash/csh/tcsh.



回答2:

Simplest, idiomatic way:

(cd ./Unwanted1/Unwanted2 && zip -r ../../new.zip ./wanted/file.txt)

Now zip, tar, rar, cpio and friends all have options to manage the same, but they may differ from version to version and certainly from archive utility to archive utility. I suggest you learn to work with the shell to do the work, and you can use any archive format you desire

Another way:

(cd ./Unwanted1/Unwanted2 && find . -name "*.txt" -print) | zip new.zip -@


回答3:

Well one simple way around might be to do

cd ./Unwanted1/Unwanted2
zip -r ../../new.zip ./wanted/file.txt

But I don't know what your situation is. Perhaps you're required to run from the base directory? Also the "-r" option is used when you want to recursively traverse directories - the example you provided is using one file.