解压特定目录而不创建顶级目录

16 command-line unzip

我有一个 ZIP 文件,其中有一个存储所有文件的顶级目录:

Release/
Release/file
Release/subdirectory/file
Release/subdirectory/file2
Release/subdirectory/file3
Run Code Online (Sandbox Code Playgroud)

我想提取 下的所有内容Release,保留目录结构,但是当我运行它时:

unzip archive.zip Release/* -d /tmp

它创建顶级Release文件夹:

/tmp/Release/
/tmp/Release/file
/tmp/Release/subdirectory/file
/tmp/Release/subdirectory/file2
/tmp/Release/subdirectory/file3
Run Code Online (Sandbox Code Playgroud)

我如何在Release 创建Release文件夹的情况下提取所有内容,如下所示:

/tmp/
/tmp/file
/tmp/subdirectory/file
/tmp/subdirectory/file2
/tmp/subdirectory/file3
Run Code Online (Sandbox Code Playgroud)

小智 7

在您的情况下,请尝试在目标文件夹中:

ln -s Release . && unzip <YourArchive>.zip
Run Code Online (Sandbox Code Playgroud)

比您需要删除您创建的链接:

rm Release
Run Code Online (Sandbox Code Playgroud)

  • `ln` 的参数顺序被交换。它应该是 `ln -s 。释放`。 (2认同)

jst*_*sta 4

j标志应该阻止文件夹创建unzip -j archive.zip -d .

手册页

-j 

junk paths. The archive's directory structure is not recreated; 
all files are deposited in the extraction directory (by default, the
current one).
Run Code Online (Sandbox Code Playgroud)

  • 我认为这已经很接近了,但是OP希望只跳过顶级目录的创建并保留剩余的目录结构。`-j` 选项将所有文件转储到当前目录中,而不考虑存档中的目录结构。 (18认同)

Ser*_*nyy 1

用于压平提取的树的 Python 脚本

下面编写的脚本提取 zip 文件并将最顶层目录中包含的文件移出到当前工作目录。这个快速脚本是为满足这一特定问题而定制的,其中有一个包含所有文件的最顶层目录,尽管可以进行一些编辑以适合更一般的情况。

#!/usr/bin/env python3
import sys
import os
from zipfile import PyZipFile
for zip_file in sys.argv[1:]:
    pzf = PyZipFile(zip_file)
    namelist=pzf.namelist()
    top_dir = namelist[0]
    pzf.extractall(members=namelist[1:])
    for item in namelist[1:]:
        rename_args = [item,os.path.basename(item)]
        print(rename_args)
        os.rename(*rename_args)
    os.rmdir(top_dir)
Run Code Online (Sandbox Code Playgroud)

测试运行

这是脚本应该如何工作的示例。所有内容都提取到当前工作目录,但源文件可以完全位于不同的目录中。该测试是在我的个人 github 存储库的 zip 存档上执行的。

$ ls                                                                                   
flatten_zip.py*  master.zip
$ ./flatten_zip.py master.zip                                                          
['utc-time-indicator-master/.gitignore', '.gitignore']
['utc-time-indicator-master/LICENSE', 'LICENSE']
['utc-time-indicator-master/utc-time-indicator', 'utc-time-indicator']
['utc-time-indicator-master/utc_indicator.png', 'utc_indicator.png']
$ ls
flatten_zip.py*  LICENSE  master.zip  utc_indicator.png  utc-time-indicator
Run Code Online (Sandbox Code Playgroud)

使用位于不同位置的源文件进行测试

$ mkdir test_unzip
$ cd test_unzip
$ ../flatten_zip.py  ../master.zip                                                     
['utc-time-indicator-master/.gitignore', '.gitignore']
['utc-time-indicator-master/LICENSE', 'LICENSE']
['utc-time-indicator-master/utc-time-indicator', 'utc-time-indicator']
['utc-time-indicator-master/utc_indicator.png', 'utc_indicator.png']
$ ls
LICENSE  utc_indicator.png  utc-time-indicator
Run Code Online (Sandbox Code Playgroud)