我需要使用以下命令创建一个zip文件:
zip /dir/to/file/newZip /data/to/zip/data.txt
这行代码可以正常运行,但所创建的zip文件会模仿原始文件所在的目录结构。我不需要这么多多余的文件夹。
我在手册和谷歌搜索中粗略查看并未找到答案。
我需要使用以下命令创建一个zip文件:
zip /dir/to/file/newZip /data/to/zip/data.txt
这行代码可以正常运行,但所创建的zip文件会模仿原始文件所在的目录结构。我不需要这么多多余的文件夹。
我在手册和谷歌搜索中粗略查看并未找到答案。
你可以使用-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).
使用-j
选项和-r
选项一起不起作用。
因此,解决方法可以是这样:
cd path/to/parent/dir/;
zip -r complete/path/to/name.zip ./* ;
cd -;
或者行内版本
cd path/to/parent/dir/ && zip -r complete/path/to/name.zip ./* && cd -
如果您不想在屏幕上看到cd -
的输出,可以将其直接重定向到/dev/null
cd path/to/parent/dir/ && zip -r ../../../../name.zip ./* && cd -
- eddyP23cd path/to/parent/dir/
中,你可以轻松地计算出双点号 ../
的数量。 - eddyP23使用-j
选项:
-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).
有点相关 - 我正在寻找一个可以对目录执行相同操作的解决方案。
不幸的是,-j
选项对此无效 :(
以下是一个很好的解决方案: https://superuser.com/questions/119649/avoid-unwanted-path-in-zip-file
或者,您可以创建一个临时符号链接到您的文件:
ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$
这同样适用于目录。
当压缩目录时,在存档中保留父目录将有助于避免在以后解压缩存档文件时弄乱当前目录。
因此,为了避免保留所有路径,并且由于您不能同时使用 -j 和 -r(否则将出现错误),您可以执行以下操作:
cd path/to/parent/dir/;
zip -r ../my.zip "../$(basename "$PWD")"
cd -;
"../$(basename "$PWD")"
是保留上级目录的魔法。unzip my.zip
将会给出一个包含所有文件的文件夹:"parent-directory
├── file1
├── file2
├── dir1
│ ├── file3
│ ├── file4
与其将未压缩的文件散落在当前目录中:
file1
file2
dir1
├── file3
├── file4
/../
,例如/../parent/sub/
。 - escalator-jrm
选项即可删除文件和目录结构。zip -jrm /path/to/file.zip /path/to/file