Shell-Script
解壓縮到與存檔同名的文件夾
我有很多rar文件
- Folder/ --- Spain.rar --- Germany.rar --- Italy.rar
所有文件都不包含根文件夾,因此它只是文件。
提取時我想要實現的是這個結構:
- Folder/ -- Spain/ ---- Spain_file1.txt ---- Spain_file2.txt -- Germany/ ---- Germany_file1.txt ---- Germany_file2.txt -- Italy/ ---- Italy_file1.txt ---- Italy_file2.txt
這樣就創建了一個具有存檔名稱的文件夾,並將存檔提取到其中。
我在另一個執行緒中找到了這個 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
任何想法我怎麼能做到這一點?
我的個人檔案中有一個腳本可以做到這一點。更準確地說,它例如解壓
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
用法(在您
$PATH
的名稱下安裝此腳本extract
並使其可執行後):extract Folder/*.rar