我的文件名称如下:
foo_baar_AB_01.ending
fOo_BaAr_BC_05.ending
FOo_baaR_BA_15.ending
带有重命名文件的规则集的Excel或CSV列表:
AB ; Data
BC ; Stuff
BA ; Other
我的任务是重命名文件。结果应如下所示:
foo_baar_AB_01.Data.ending
fOo_BaAr_BC_05.Stuff.ending
FOo_baaR_BA_15.Other.ending
是否有解决方案将Exel-Pattern-List集成到批处理文件中,还是必须在批处理文件中集成Pattern-List?什么是这个问题的解决方案?
答案 0 :(得分:2)
@echo off
setlocal EnableDelayedExpansion
rem Load the list of names from the ruleset
for /F "tokens=1,2 delims=; " %%a in (list.csv) do (
set "name[%%a]=%%b"
)
rem Process the files
for /F "tokens=1-5 delims=_." %%a in ('dir /B /A-D *.ending') do (
ECHO ren "%%a_%%b_%%c_%%d.%%e" "%%a_%%b_%%c_%%d.!name[%%c]!.%%e"
)
确认名称正确后,从ECHO
命令中删除ren
部分。
答案 1 :(得分:1)
嵌套for
循环可以解决这个问题 - 请参阅解释性rem
备注:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define rule-set CSV file here:
set "RULES=%~dp0ruleset.csv"
rem // Resolve the files to rename, provided as command line arguments:
for %%F in (%*) do (
rem // Extract the third `_`-delimited token from file name:
for /F "tokens=3 delims=_" %%N in ("%%~nF") do (
rem // Read the rule-set CSV file (`delims=;<TAB><SPACE>`!):
for /F "usebackq tokens=1,* delims=; " %%I in ("%RULES%") do (
rem // Check whether third token from file name matches rule:
if /I "%%I"=="%%N" (
rem // File name matches, so rename file finally:
ECHO rename "%%~F" "%%~nF.%%J%%~xF"
)
)
)
)
endlocal
exit /B
这肯定不是最高性能和最有效的方法,但理解起来非常简单。
测试输出后,删除ECHO
前面的大写rename
命令。
答案 2 :(得分:0)
这是一个做你想要的excel宏。在您的Excel文件中,将规则放在名为规则的工作表中,如下所示:
COLUMN A COOLUMN B
AB Data
BC Stuff
在宏行中更改文件路径设置objFolder = objFSO.GetFolder(&#34; C:\\ files&#34;)。并运行宏。希望它有所帮助。
Sub renameFiles()
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Set rulesSheet = ActiveWorkbook.Worksheets("rules")
'Create an instance of the FileSystemObject
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Get the folder object
Set objFolder = objFSO.GetFolder("C:\\files")
'loops through each file in the directory
For Each objFile In objFolder.Files
Filename = objFile.Path
' loop ruleset
rulesrow = 1
Do While (rulesSheet.Cells(rulesrow, 1) <> "")
rule = Trim(rulesSheet.Cells(rulesrow, 1))
newtext = Trim(rulesSheet.Cells(rulesrow, 2))
pos = InStr(Filename, rule)
If pos > 0 Then ' if the rule exists in your file name
newfilename = objFSO.getparentfoldername(Filename) & "\" & objFSO.GetBaseName(Filename) & "." & newtext & "." & objFSO.getextensionname(Filename)
' rename
Name Filename As newfilename
End If
rulesrow = rulesrow + 1
Loop
Next objFile
End Sub