解压到与存档同名的文件夹

Den*_*ken 5 archive shell-script rar

我有很多 rar 文件

- Folder/
--- Spain.rar
--- Germany.rar
--- Italy.rar
Run Code Online (Sandbox Code Playgroud)

所有文件都不包含根文件夹,所以它只是文件。

提取时我想实现的是这种结构:

- Folder/
-- Spain/
---- Spain_file1.txt
---- Spain_file2.txt
-- Germany/
---- Germany_file1.txt
---- Germany_file2.txt
-- Italy/
---- Italy_file1.txt
---- Italy_file2.txt
Run Code Online (Sandbox Code Playgroud)

这样就创建了一个具有存档名称的文件夹,并将存档解压缩到其中。

我在另一个线程中找到了这个 bash 示例,但它对我不起作用,它试图创建一个以所有文件为名称的文件夹。

#!/bin/bash

for archive in "$(find . -name '*.rar')"; do
  destination="${archive%.rar}"
  if [ ! -d "$destination" ] ; then mkdir "$destination"; fi
  unrar e "$archive" "$destination"
done
Run Code Online (Sandbox Code Playgroud)

任何想法我怎么能做到这一点?

Gil*_*il' 6

我的个人档案中有一个脚本就是这样做的。更准确地说,它提取Spain.rar到例如一个名为 的新目录Spain,除非其中的所有文件Spain.rar都在同一个顶级目录下,则保留该顶级目录。

#!/bin/sh

# Extract the archive $1 to a directory $2 with the program $3. If the
# archive contains a single top-level directory, that directory
# becomes $2. Otherwise $2 contains all the files at the root of the
# archive.
extract () (
  set -e
  archive=$1
  case "$archive" in
    -) :;; # read from stdin
    /*) :;; # already an absolute path
    *) archive=$PWD/$archive;; # make absolute path
  esac
  target=$2
  program=$3
  if [ -e "$target" ]; then
    echo >&2 "Target $target already exists, aborting."
    return 3
  fi
  case "$target" in
    /*) parent=${target%/*};;
    */[!/]*) parent=$PWD/${target%/*};;
    *) parent=$PWD;;
  esac
  temp=$(TMPDIR="$parent" mktemp -d)
  (cd "$temp" && $program "$archive")
  root=
  for member in "$temp/"* "$temp/".*; do
    case "$member" in */.|*/..) continue;; esac
    if [ -n "$root" ] || ! [ -d "$member" ]; then
      root=$temp # There are multiple files or there is a non-directory
      break
    fi
    root="$member"
  done
  if [ -z "$root" ]; then
    # Empty archive
    root=$temp
  fi
  mv -v -- "$root" "$target"
  if [ "$root" != "$temp" ]; then
    rmdir "$temp"
  fi
)

# Extract the archive $1.
process () {
  dir=${1%.*}
  case "$1" in
    *.rar|*.RAR) program="unrar x";;
    *.tar|*.tgz|*.tbz2) program="tar -xf";;
    *.tar.gz|*.tar.bz2|*.tar.xz) program="tar -xf"; dir=${dir%.*};;
    *.zip|*.ZIP) program="unzip";;
    *) echo >&2 "$0: $1: unsupported archive type"; exit 4;;
  esac
  if [ -d "$dir" ]; then
    echo >&2 "$0: $dir: directory already exists"
    exit 1
  fi
  extract "$1" "$dir" "$program"
}

for x in "$@"; do
  process "$x"
done
Run Code Online (Sandbox Code Playgroud)

用法(在您$PATH的名称下安装此脚本extract并使其可执行后):

extract Folder/*.rar
Run Code Online (Sandbox Code Playgroud)