如何在批处理文件中使用符号%,&,=?

时间:2015-09-18 04:05:45

标签: windows batch-file cmd

这是我写的用于重命名文件的批处理文件。我得到的问题是,如果文件名包含以下符号之一,则脚本不起作用。 % & =

@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%"

1 个答案:

答案 0 :(得分:0)

以下示例说明如何处理字符替换 请打开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"

编辑:我使用您提到的字符更新了示例。