如何批量将目录下x_y.properties格式文件重命名为y_x.properties?
批量重命名文件:交换下划线前后的字符串
Windows(PowerShell)
在文件所在目录打开PowerShell,执行以下命令:
Get-ChildItem -Filter "*.properties" | ForEach-Object { $nameParts = $_.BaseName -split "_", 2 if ($nameParts.Count -eq 2) { $newName = "$($nameParts[1])_$($nameParts[0])$($_.Extension)" Rename-Item -Path $_.FullName -NewName $newName } }
- 仅匹配
.properties格式文件 - 按下划线拆分文件名(仅拆分第一处下划线),交换前后两段字符串后重命名
- 可先添加
-WhatIf参数到Rename-Item命令后,预览重命名结果再执行实际修改
Linux/macOS(Bash)
方法1:Perl版本rename命令(多数Debian/Ubuntu系发行版默认)
rename 's/(\w+)_(\w+)\.properties/$2_$1.properties/' *.properties
方法2:通用循环脚本(适配所有Linux/macOS系统)
for file in *.properties; do if [[ $file =~ ^([^_]+)_([^_]+)\.properties$ ]]; then mv "$file" "${BASH_REMATCH[2]}_${BASH_REMATCH[1]}.properties" fi done
跨平台方案(Python脚本)
将以下代码保存为rename_files.py,放在文件所在目录运行:
import os for filename in os.listdir('.'): if filename.endswith('.properties') and '_' in filename: base, ext = os.path.splitext(filename) part1, part2 = base.split('_', 1) new_filename = f"{part2}_{part1}{ext}" os.rename(filename, new_filename)
内容的提问来源于stack exchange,提问作者Zenith
相关产品推荐
相关产品推荐

