Wally Walters
Wally Walters

Reputation: 75

How to escape reserved characters in Windows batch files

I'm trying to process a list of file names but don't know how to "escape" the command line to produce consistent output regardless of whether the name contains plain text or special characters like the ampersand, exclamation point and percent sign. If I run my code (below) on four sample files whose names are:

01 A Test.txt
02 & Test.txt
03 ! Test.txt
04 % Test.txt

The output is:

1 "01 A Test.txt"
2 "02 & Test.txt"
 "03 COUNT
4 "04Test.txt"

The file names with the plain text and the ampersand pass through correctly (as long as they're enclosed in quotation marks, that is) but the exclamation point and percentage sign produce entirely different results. How can I pass the variables through to the subroutine so all four cases get processed the same (with the quotation marks removed from the output, if possible)? Thank you.

:: CODE
:: ----
@echo off
setlocal EnableDelayedExpansion
set /a COUNT=0
for /f "tokens=*" %%g in ('dir /b *.txt') do (
  set /a COUNT=!COUNT! + 1
  call :LIST "%%g" !COUNT!                )
pause > nul
exit

:LIST
echo %2 %1
goto :EOF

Upvotes: 1

Views: 600

Answers (2)

npocmaka
npocmaka

Reputation: 57322

try this:

@echo off
setlocal EnableDelayedExpansion
set /a COUNT=0
for /f "tokens=*" %%g in ('dir /b *.txt') do (
  set /a COUNT=!COUNT! + 1
  <nul set /p=!count!
  setlocal disableDelayedExpansion & (
    (echo( %%g)
  )
  setlocal enableDelayedExpansion

)

You can turn on/off the delayed expansion within the for loop for proper echoing the special chars. <nul set /p=%%g prints a string without new line at the end - which is needed for proper echoing of the count which should be in delayed expansion part.And it will work faster without subroutine.

Edited to print the count first.

Upvotes: 2

Squashman
Squashman

Reputation: 14320

I think this will work as well.

@echo off

set /a COUNT=0
for /f "tokens=*" %%g in ('dir /b *.txt') do (
    set /a COUNT+=1
    set "file=%%g"
    call :LIST file COUNT
)
pause
exit

:LIST
setlocal enabledelayedexpansion
echo !%2! !%1!
endlocal
goto :EOF

Output

1 01 A Test.txt
2 02 & Test.txt
3 03 ! test.txt
4 04 % test.txt
Press any key to continue . . .

Upvotes: 2

Related Questions