这是我为重命名文件而写的batch file。 我得到的问题是,如果文件名包括下列符号之一,该脚本不起作用。 %
&
=
@echo off SETLOCAL set file="C:\Users\Desktop\newdocument.txt" SET file1=%file: =% FOR /f %%i IN ("%file1%") DO ( set fileextension=%%~xi ) REN %file% "newname%fileextension%"
以下示例显示如何处理字符替换。
请打开cmd而不是点击批处理文件,在你的脚本所在的目录中导航并运行脚本。
@echo off setlocal set "mydir=%USERPROFILE%\Desktop" pushd %mydir% REM creating some empty files with space in file name REM Here, you must escape the character '%' by doubling. REM _somefile with % .txt copy nul "_somefile with %% & = 21 .txt" copy nul "_somefile with %% & = 22 .txt" copy nul "_somefile with %% & = 23 .txt" setlocal enabledelayedexpansion for /f "delims=" %%i in ('dir _somefile*with*.txt /s /B') do ( set "newname=%%~nxi" echo REN "%%i" "!newname: =!" ) endlocal popd pause exit /b 0
注意我添加了一个实例pause
。
输出:
REN "_somefile with % & = 21 .txt" "_somefilewith%&=21.txt" REN "_somefile with % & = 22 .txt" "_somefilewith%&=22.txt" REN "_somefile with % & = 23 .txt" "_somefilewith%&=23.txt"
编辑:我更新了你提到的字符的例子。