按前缀分类Zip文件并实现一级深度解压的技术方案需求
解决方案:批量分类解压Zip文件(Windows 10 + RedHat 7)
Windows 10 实现方案(PowerShell脚本)
利用Windows自带PowerShell编写脚本,自动按前缀分类、一级深度解压,避免多层嵌套:
# 遍历当前目录下所有.zip文件 Get-ChildItem -Filter *.zip | ForEach-Object { # 提取文件名前缀(第一个'-'分隔符前的内容) $prefix = $_.Name.Split('-')[0] # 提取不带扩展名的完整文件名作为子文件夹名 $subFolderName = $_.BaseName # 构建最终解压路径:前缀文件夹\子文件夹 $targetPath = Join-Path -Path $prefix -ChildPath $subFolderName # 创建目标目录(不存在则自动创建) if (-not (Test-Path -Path $targetPath)) { New-Item -ItemType Directory -Path $targetPath | Out-Null } # 创建临时目录用于中转解压内容 $tempDir = Join-Path -Path $env:TEMP -ChildPath ([Guid]::NewGuid().ToString()) New-Item -ItemType Directory -Path $tempDir | Out-Null try { # 先将Zip文件解压到临时目录 Expand-Archive -Path $_.FullName -DestinationPath $tempDir -Force # 检查临时目录内的根结构 $rootItems = Get-ChildItem -Path $tempDir if ($rootItems.Count -eq 1 -and $rootItems[0].PSIsContainer) { # 如果Zip内只有一个根目录,直接将目录内的内容移到目标路径 Move-Item -Path (Join-Path -Path $rootItems[0].FullName -ChildPath "*") -Destination $targetPath -Force } else { # 否则直接将临时目录内的所有内容移到目标路径 Move-Item -Path (Join-Path -Path $tempDir -ChildPath "*") -Destination $targetPath -Force } } finally { # 清理临时目录 Remove-Item -Path $tempDir -Recurse -Force } }
使用说明
- 将脚本保存为
Unzip-ByPrefix.ps1,放到Zip文件所在目录 - 右键点击脚本,选择「用PowerShell运行」
- 若遇到执行权限限制,先运行
Set-ExecutionPolicy RemoteSigned并按提示确认
RedHat 7 实现方案(Bash脚本)
基于系统自带的unzip工具编写bash脚本,实现相同需求:
#!/bin/bash # 遍历当前目录下所有.zip文件 for zipfile in *.zip; do # 跳过非文件对象 [ -f "$zipfile" ] || continue # 提取文件名前缀(第一个'-'分隔符前的内容) prefix=$(echo "$zipfile" | cut -d'-' -f1) # 提取不带扩展名的完整文件名作为子文件夹名 subfolder=${zipfile%.zip} # 构建最终解压路径 target_path="./$prefix/$subfolder" # 递归创建目标目录(忽略已存在的错误) mkdir -p "$target_path" # 获取Zip内的第一个条目,判断是否为单个根目录 first_entry=$(unzip -l "$zipfile" | awk 'NR>3 && NF>0 {print $4; exit}') if [[ "$first_entry" =~ ^[^/]+/$ ]]; then # 如果Zip内只有一个根目录,跳过该目录直接提取内部内容 unzip -q "$zipfile" "${first_entry}*" -d "$target_path" # 将内容移到目标路径根目录,清理临时子目录 mv "$target_path/$first_entry"* "$target_path/" rmdir "$target_path/$first_entry" else # 否则直接解压到目标路径 unzip -q "$zipfile" -d "$target_path" fi done
使用说明
- 将脚本保存为
unzip_by_prefix.sh,放到Zip文件所在目录 - 赋予脚本执行权限:
chmod +x unzip_by_prefix.sh - 运行脚本:
./unzip_by_prefix.sh - 若系统未安装
unzip,先执行sudo yum install unzip安装
内容的提问来源于stack exchange,提问作者Steve Daubs
相关产品推荐
相关产品推荐

