Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file to handle random % character in FOR LOOP

Tags:

batch-file

cmd

I am trying to pass file names as FOR loop parameters to a separate batch file. The problem is, if a file name contains special characters (especially %), the parameter doesnt go to the called script. EG -

The FIRST_SCRIPT.bat is as follows -

cd "C:\theFolder"
for /R %%a in (*.*) do call SECOND_SCRIPT "%%~a"

The SECOND_SCRIPT.bat is as follows -

ECHO %1

If a file name contains % eg. "% of STATS.txt", the output ends up being

of STATS.txt

Which is wrong. I have tried using Setlocal DisableDelayedExpansion but with little success

Setlocal DisableDelayedExpansion
for /R %%a in (*.*) do (
SET "var=%%~a" 
Setlocal EnableDelayedExpansion
call TEST_UPGRADE "%var%" "%%~a"
)

There are other stackoverflow answers, but they all need the % character to be known before hand. Since the file names are not in our control, these solutions won't work for us. Is there any way of handling this?

Thanks!

platform: cmd.exe for Windows XP

like image 248
Jai Avatar asked Dec 07 '25 03:12

Jai


2 Answers

Aacini shows a solution that would work with % and also ! but it fails with carets ^.

But the solution is simple.

First it's necessary to disable the delayed expansion to handle the exclamation marks.
The filename is now exactly in the var variable.
The problems with carets and percents are caused by the CALL. This can be solved with the CALL itself by use only the second percent expansion phase of the CALL by using %%var%%.

Setlocal DisableDelayedExpansion
for /R %%a in (*.*) do (
  SET "var=%%~a" 
  call TEST_UPGRADE "%%var%%"
)

The next problem is in the second.bat to display the filename. This should be done with delayed expansion enabled to avoid problems with special characters, or you need always quotes.

set "var=%~1"
setlocal EnableDelayedExpansion
echo Filename: !var!
like image 163
jeb Avatar answered Dec 09 '25 18:12

jeb


solution with a temp file:

first.bat

@ECHO OFF &SETLOCAL
REM to escape the '%' use a second '%'
SET "var=40%% &off!.txt"
REM get a random temp file name
:loop
SET "tname=%temp%%random%%random%"
IF EXIST "%tname%" GOTO :loop
SETLOCAL ENABLEDELAYEDEXPANSION
REM save the variable in the file
>"%tname%" (ECHO(!var!)
CALL "second.bat" "%tname%"
ENDLOCAL

second.bat

@ECHO OFF &SETLOCAL
SET "tname=%~1"
<"%tname%" set/p"var="
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !var!
DEL "%tname%" /F /Q

..output is:

40% &off!.txt
like image 31
Endoro Avatar answered Dec 09 '25 18:12

Endoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!