如何使用命令行将多个文件解压缩到具有相同名称的多个文件夹中?

时间:2016-03-23 13:47:45

标签: shell command-line

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

abc.zip,xyz.zip,....等等。

我想解压缩这些文件,但是要将它们解压缩到具有相同名称的文件夹中:

abc,xyz,...等

我喜欢这个:

unzip '*.zip'

for i in folder; do unzip $i; done

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

你能帮忙吗?谢谢。 PS:我正在使用Mac

1 个答案:

答案 0 :(得分:1)

引自2009年4月20日的版本 UnZip 6.00的man unzip,由Info-ZIP引用。由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 <的内容/ em>文件到已创建或已存在的目录。

让我们测试一下:

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

a.zip 包含文件 1.txt 2.txt 3。 TXT

b.zip 包含文件 4.txt 5.txt 6。 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