更改解压后的文件夹名称
我有相当多的目录(500+),每个目录(和可能的子目录)包含 4 个或更多 zip 文件。我设法拼凑了一个 bash 脚本,该脚本解压缩压缩文件,同时将 zip 文件名保持为目录和所有目录层次结构。
例如:如果我有一个名为 的 zip 文件100011_test123.zip,它包含 10 个文件。该脚本会将所有文件解压缩到100011_test123/目录中。100010文件名/目录名中下划线前出现的数字是完全随机的。
这是实际的 bash 脚本:
#!/bin/bash
cd <directory-with-large-number-of-zip-files>
find . -name "*.zip" | while read filename; do unar -d -o "`dirname "$filename"`" "$filename"; done;
find . -name "*.zip" -type f -delete
现在我想更新脚本以便100010_从 .zip 文件名中删除.zip 文件名而不篡改目录结构/层次结构(我想有一种方法可以在使用unar命令之前重命名 zip 文件)然后将文件解压缩到一个目录中100010_一开始。
我已经坚持了 3 天多。对此的任何见解将不胜感激。
谢谢你。
回答
对于同一级别的所有 zip 文件,您不需要查找,但常规文件名模式通配符将迭代每个 zip 存档。
使用 bash 的globstar选项,您还可以在子目录中找到 zip 档案
#!/usr/bin/env bash
shopt -s nullglob # Prevents iterating if no filename match
shopt -s globstar # ./**/ Allow searching inside sub-directories
# Set the basedir if you want all output directories at same place
#basedir="$PWD"
for zipfile in ./**/*.zip; do
# Extract the base directory containing the archive
zipdir="${zipfile%/*}"
# Extract the base name without the directory path
basename="${zipfile##*/}"
# Remove the .zip extension
# 100011_test123.zip -> 100011_test123
extensionless="${basename%.zip}"
# Remove everything before and first underscore 100011_
# 100011_test123 -> test123
outputdir="${basedir:-$zipdir}/${extensionless#*_}"
# Create output directory or continue with next archive
# mkdir -p test123
mkdir -p "$outputdir" || continue
# Unzip the zipfile into the outputdir and remove the zipfile if successful
# unrar -d -o test123 100011_test123.zip && rm -f -- 100011_test123.zip
unar -d -o "$outputdir" "$zipfile" && rm -f -- "$zipfile"
done