如何按文件名x、y字段组合批量移动文件至X_Y命名子目录
批量文件归类移动实现方案
所有方案均直接在存放目标文件的目录下执行,执行后会自动将符合filtered.{x}.R1.clean.id_{y}.{z}命名规则的文件移动到对应{x}_{y}命名的子目录中,不存在的子目录会自动创建,不会修改原文件名。
Linux / macOS(Bash/Zsh 终端环境)
进入目标文件所在目录后,直接执行以下Shell代码即可:
for file in filtered.*.R1.clean.id_*.*; do [ -f "$file" ] || continue # 提取x字段 x=${file#filtered.} x=${x%%.R1.clean.id_*} # 提取y字段 rest=${file#*id_} y=${rest%%.*} target_dir="${x}_${y}" mkdir -p "$target_dir" mv "$file" "$target_dir/" done
- 预校验提示:如果担心匹配出错,可以先把代码中
mv "$file" "$target_dir/"替换为echo "待移动:$file -> $target_dir/",执行后会打印所有待执行的移动操作,确认匹配关系无误后再换回原命令执行即可。
Windows(PowerShell 环境)
进入目标文件所在目录后,直接执行以下PowerShell代码即可:
Get-ChildItem -File -Filter "filtered.*.R1.clean.id_*.*" | ForEach-Object { if ($_.Name -match '^filtered\.(.+)\.R1\.clean\.id_([^.]+)\..+$') { $x = $matches[1] $y = $matches[2] $targetDir = Join-Path $_.DirectoryName "${x}_${y}" if (-not (Test-Path $targetDir)) { New-Item -ItemType Directory -Path $targetDir | Out-Null } Move-Item $_.FullName $targetDir } }
- 预校验提示:如果担心匹配出错,可以先把代码中
Move-Item $_.FullName $targetDir替换为Write-Host "待移动:$($_.Name) -> $targetDir",执行后预览所有移动对应关系,确认无误后再换回原命令执行即可。
内容的提问来源于stack exchange,提问作者P.Yuan
相关产品推荐
相关产品推荐

