这可以在批处理文件中从所有文件名中删除一个单词,例如“UnwantedWord”,在“SET MODIFIED_FILENAME”行上...
setlocal enableextensions enabledelayedexpansion
for /r "%~dp0" %%A in ("*.*") do (
SET ORIGINAL_FILENAME=%%~nxA
echo.!ORIGINAL_FILENAME!
SET MODIFIED_FILENAME=!ORIGINAL_FILENAME:UnwantedWord=!
echo !MODIFIED_FILENAME!
REN "%~dp0!ORIGINAL_FILENAME!" "!MODIFIED_FILENAME!"
)
我想删除文件名中的感叹号,但是因为“!”字符和“^”是特殊字符,所以需要使用“^^!”对感叹号进行双重转义,但是尝试这样做时,不起作用 - 运行以下命令时,感叹号不会从文件名中删除:
setlocal enableextensions enabledelayedexpansion
for /r "%~dp0" %%A in ("*.*") do (
SET ORIGINAL_FILENAME=%%~nxA
echo.!ORIGINAL_FILENAME!
SET MODIFIED_FILENAME=!ORIGINAL_FILENAME:^^!=!
echo !MODIFIED_FILENAME!
REN "%~dp0!ORIGINAL_FILENAME!" "!MODIFIED_FILENAME!"
)
可以修复这个问题吗?
大家干杯!
答案1
有很多方法可以做到这一点。我自己会放弃延迟扩展,而改用批处理函数的方法。这将使“!”不再特殊。
@echo off
for /r "%~dp0" %%A in ("*.*") do call :RenameTheFile "%%A"
goto :EOF
:RenameTheFile
:: If somehow this batch file matches the pattern, skip it
if "%~nx0"=="%~nx1" goto :EOF
SET ORIGINAL_FILENAME=%~nx1
SET ORIGINAL_FILEPATH=%~dp1
SET MODIFIED_FILENAME=%ORIGINAL_FILENAME:some_word_or_chars=%
:: If the file name wasn't modified, move onto the next
if "%MODIFIED_FILENAME%"=="%ORIGINAL_FILENAME%" goto :EOF
echo ORIGINAL_FILENAME=%ORIGINAL_FILENAME%
echo MODIFIED_FILENAME=%MODIFIED_FILENAME%
rename "%ORIGINAL_FILEPATH%\%ORIGINAL_FILENAME%" "%MODIFIED_FILENAME%"
goto :EOF