可能重复:
如何从命令行或使用第三方工具批量重命名文件?
我们有几个文件名类似于以下内容的文件:
Organizing_your_day_in_acute_care_-_Flash_(Medium)_-_20120516_12.04.02PM.mp4
Developing_a_Business_Plan_-_IT_Projects_-_Flash_(Medium)_-_20120529_09.39.09PM.mp4
GI_Medications_-_Flash_(Medium)_-_20120607_11.35.50AM.mp4
Effectiveness_and_Data_and_Information_Set_-_Flash_(Large)_-_20120208_02.41.28PM.mp4
Adult_Learning_-_Theory_-_Flash_(Medium)_-_20100519_05.25.02PM.mp4
我想要做的是创建一个批处理脚本来重命名这些文件,以便删除所有下划线并删除“_-_Flash”字符串后的所有内容,本质上保留文件如下:
Organizing your day in acute care.mp4
Developing a Business Plan - IT Projects.mp4
GI Medications.mp4
Effectiveness and Data and Information Set.mp4
Adult Learning - Theory.mp4
任何帮助将不胜感激。
答案1
这个 .bat 应该可以工作,但请记住,如果您的文件不遵循给定的文件名模式,结果将是不可预测的:
setlocal EnableDelayedExpansion
FOR /F "usebackq delims==" %%i IN (`dir /b *.mp4`) DO (
set oldfilename=%%i
set oldfilename=!oldfilename:^(=!
set oldfilename=!oldfilename:^)=!
set endbit=!oldfilename:*_-_Flash=_-_Flash!
call set newfilename=%%oldfilename:!endbit!=%%
set newfilename=!newfilename:_= !
rename "%%i" "!newfilename!.mp4")
endlocal
答案2
在 VBScript 中执行此操作可能更容易
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder(".")
ext = LCase(fso.GetExtensionName(f))
If ext = "mp4" Then
f.Name = Replace(Left(s, InStr(s, "_-_Flash")-1), "_", " ") & "." & ext
End If
Next
或者在 PowerShell 中
Get-ChildItem -Filter *.mp4 | ForEach-Object {
$newname = $_.Name -replace "_-_Flash.*(.mp4)", '$1'
$newname = $newname -replace "_", " "
Rename-Item $_.FullName $newname
}
答案3
由于您使用的是 Windows,因此您可以充分利用 JScript + ActiveX 的功能来自动执行 JavaScript 中的几乎任何任务,而且我个人认为它看起来更简洁。
将以下内容保存为 rename.js:
var shell = new ActiveXObject("Shell.Application")
var folder = shell.NameSpace("D:\\1\\test") // <--- your folder name here
// or interactive: var folder = shell.BrowseForFolder(0, "Select folder to clean-up", 0)
var items = folder.Items()
for (var idx = 0; idx < items.Count; idx++) {
var file = items.Item(idx)
var filename = file.Name
var new_filename = filename.replace(/_\-_Flash_.*/, '').replace(/_/g, ' ')
if (new_filename != filename) {
file.Name = new_filename
// You can uncomment next line if you run in console.
// WScript.Echo(filename + ' -> ' + new_filename)
}
}
并使用 wscript.exe(GUI)或 cscript.exe(控制台)运行。