【问题标题】:How to unzip multiple files into multiple folders with the same names using command line? [duplicate]如何使用命令行将多个文件解压缩到多个同名文件夹中? [复制]
【发布时间】:2016-03-23 13:47:45
【问题描述】:

我在一个文件夹中有很多 zip 文件,例如:

abc.zip、xyz.zip、....等

我想解压这些文件,但要解压到同名文件夹中:

abc、xyz、...等

我喜欢这样:

解压缩'*.zip'

因为我在文件夹中;解压 $i;完毕

它不起作用,因为它会将这些 zip 文件的所有内容提取到一个文件夹中。

你能帮忙吗?谢谢。 PS:我用的是Mac

【问题讨论】:

  • Mac 解压缩是否有“-d”(将文件解压缩到 exdir)选项?如果是这样,您应该可以做到for f in ``ls *.zip``; do mkdir "${f%.*}"; unzip $f -d "${f%.*}"; done。如果没有“-d”,则执行 cd 进入目录,然后在 zip 后 cd 返回。 (双反引号应该是单引号,但代码粘贴不支持)。
  • 不要使用ls 输出任何东西。 ls 是一个交互式查看目录元数据的工具。任何用代码解析ls 输出的尝试都会被破坏。 Glob 更加简单和正确:`for file in *.txt。阅读Parsing ls
  • @RanyAlbegWein,你说得对,ls 输出可能有问题。但我们不要说任何尝试都失败了。
  • 如果您对环境有足够的了解,可以冒险执行这样一个使用ls 作为输入源的脚本,那很好。问题是您永远足够了解环境,尤其是当您在网络上共享代码时。你的代码坏了。要找出您不想在系统上使用它或与他人共享它的原因,请阅读Parsing ls

标签: shell command-line


【解决方案1】:

引自 Info-ZIP 于 2009 年 4 月 20 日的 UnZip 6.00 版本的 man unzip。由 C. Spieler 维护。

  [-d exdir]
          An  optional  directory  to  which  to extract files.  By default, all files and subdirectories are recreated in the current directory; the -d option allows extraction in an arbitrary directory
          (always assuming one has permission to write to the directory).  This option need not appear at the end of the command line; it is also accepted before the zipfile specification (with the  nor‐
          mal options), immediately after the zipfile specification, or between the file(s) and the -x option.  The option and directory may be concatenated without any white space between them, but note
          that this may cause normal shell behavior to be suppressed.  In particular, ``-d ~'' (tilde) is expanded by Unix C shells into the name of the user's home directory, but ``-d~'' is treated as a
          literal subdirectory ``~'' of the current directory.

从未使用过unzip,但似乎可以运行以下命令:

for f in dir/*.zip; do
    # Creating a name for the new directory.
    new_dir="${f##*/}"
    new_dir="${new_dir%.*}"
    # Creating the directory if it doesn't already exist.
    mkdir -p "$new_dir"
    # Unzip contents of "$f" to "$new_dir"
    unzip -d "$new_dir" -- "$f"
done

这将遍历一个名为 dir 的目录中的所有 zip 文件,在 present-working-directory 中创建一个新目录(或PWD) 以 zip 文件的基本名称命名 - 如果不存在,则unzip zip的内容> 将文件复制到已创建或已存在的目录中。


让我们测试一下:

在一个名为 test 的目录中,我创建了两个存档:a.zipb.zip

a.zip 包含文件 1.txt2.txt3。 txt.

b.zip 包含文件 4.txt5.txt6。 txt.

for f in test/*.zip; do new_dir="${f##*/}"; new_dir="${new_dir%.*}"; mkdir -p "$new_dir"; unzip -d "$new_dir" -- "$f";done
Archive:  test/a.zip
extracting: a/1.txt                 
extracting: a/2.txt                 
extracting: a/3.txt                 
Archive:  test/b.zip
extracting: b/4.txt                 
extracting: b/5.txt                 
extracting: b/6.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多