【问题标题】:How to unzip different compression formats in subfolders in Linux terminal如何在 Linux 终端的子文件夹中解压缩不同的压缩格式
【发布时间】:2012-11-27 05:31:17
【问题描述】:

我在thread看到了下面这段代码,将子文件夹中的所有.zip格式解压到对应的子文件夹中。我对这段代码的问题如下。

(1)这是批处理作业的 bash 脚本吗?如果是这样,我可以将它作为 sudo bash filename.bat 运行。

(2)如何在代码中指定父文件夹目录。父目录下包含所有子文件夹,这些子文件夹又包含压缩(压缩)文件。

(3)如何修改代码以包含.rar.7z

等其他压缩格式
 for file in *.zip; do
       dir=$(basename "$file" .zip) # remove the .zip from the filename
       mkdir "$dir"
       cd "$dir" && unzip ../"$file" && rm ../"$file" # unzip and remove file if successful
       cd ..
  done

【问题讨论】:

标签: bash unzip


【解决方案1】:
  1. 是的,该代码片段看起来像 bash 脚本。如果它被命名为filename.bat,你应该可以使用sudo bash filename.bat来运行它。

  2. 代码假定当前目录是包含所有压缩文件的“父文件夹”。您需要修改代码以处理包含.zip 文件的子目录。有很多方法可以做到这一点。

  3. 鉴于需要处理除 .zip 文件以外的格式,您可能会修改代码以使用作为参数提供的文件名作为要解压缩的文件。

此代码可能有效:

for file in "$@"
do
    dir=$(dirname "$file")
    extn=${base##*.}
    base=$(basename "$file" .$extn)
    mkdir -p "$dir/$base"
    (
    cd "$dir/$base"
    case $extn in
    zip)   unzip "../$base.$extn";;
    esac
    )
done

现在,理论上,您可以扩展 case 语句中的扩展名列表以包含其他文件格式。但是,您应该知道,并非所有压缩器都打包多个文件。通常,您有一个复合格式,例如.tar.gz.tar.xz.tar.bz2。对应的压缩器(或解压器),只是简单地解压文件(丢失压缩后缀),而不从里面的.tar文件中提取数据。但是,如果 rar7z 的行为类似于 zip,那么您可以使用:

    case $extn in
    (zip)   unzip "../$base.$extn";;
    (rar)   unrar "../$base.$extn";;  # Or whatever the command is
    (7z)    un7z  "../$base.$extn";;  # Or whatever the command is
    (*)     echo "$0: unrecognized extension $extn on $file" >&2;;
    esac

如果您认为合适,您还可以恢复代码以删除文件的压缩形式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2013-03-09
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    相关资源
    最近更新 更多