How to use the symbol %, &, = in batch files?

2019-03-06 22:27发布

问题:

This is the batch file I wrote to rename files. The problem I get is that if the file name includes one of the following symbol, the script does not work. % & =

@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:

The following example shows you how to work the character substitution.
Please just open cmd instead of clicking on batch-file, navigate in the directory where is your script and run the script.

@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

Note I added an instance pause.

Output:

REN "_somefile with %  &  =  21 .txt" "_somefilewith%&=21.txt"
REN "_somefile with %  &  =  22 .txt" "_somefilewith%&=22.txt"
REN "_somefile with %  &  =  23 .txt" "_somefilewith%&=23.txt"

Edit: I updated the example with the characters that you mentioned.