1

Exclamation Points are my bane with Windows Batch. Say I want to just skip filenames with an ! in them.

I know for checking regular text in variables in a for loop, I can run:

setlocal enabledelayedexpansion
for /r %%a in (*) do (
set fname=%%~na
if not "!fname!"=="!fname:text=!" ECHO File contains the word "text"
)

But how do I specify an exclamation point?

I've tried to escape it with ^: "!fname:^!=!"

Then I see that with enabledelayedexpansion you need a ^^! to escape the character. So I tried that with no luck. Then I thought maybe three ^^^! two to escape delayedexpansion and one in the filename...

No luck...

Any suggestions?

2

The following commented script unveils the secrets:

@ECHO OFF

SETLOCAL EnableExtensions DisableDelayedExpansion
echo --- disabled delayed expansion: real file names
FOR /R "D:\bat\Unusual Names" %%G in (*exc*) DO (
  echo(%%~nG 
)
ENDLOCAL
echo(

SETLOCAL EnableExtensions EnableDelayedExpansion
echo --- enabled delayed expansion chokes down unescaped exclamation marks
echo                               (or expands !variables!)
FOR /R "D:\bat\Unusual Names" %%G in (*exc*) DO (
  echo(%%~nG 
)
ENDLOCAL
echo(

SETLOCAL EnableExtensions DisableDelayedExpansion
echo --- SET variables under delayed expansion DISABLED
echo       and USE them with delayed expansion ENABLED as follows
FOR /R "D:\bat\Unusual Names" %%G in (*exc*) DO (
  set "_fname=%%~nG"
  call :replace
  SETLOCAL EnableDelayedExpansion
    if "!_fname!"=="!_gname!" (
      echo(!_fname! == !_gname!
    ) else (
      echo(!_fname! ## !_gname!
    )
  ENDLOCAL
)
ENDLOCAL
goto :eof

:replace
  set "_gname=%_fname:exc!=%"
goto :eof

Result: D:\bat\SU\1552419.bat

--- disabled delayed expansion: real file names
01exclam!ation
02exc!lam!ation
04exc!lam!ation!OS!%OS%

--- enabled delayed expansion chokes down unescaped exclamation marks
                              and expands unescapet percent signs
01exclamation
02excation
04excationWindows_NT%OS%

--- SET variables under delayed expansion DISABLED
      and USE them with delayed expansion ENABLED as follows
01exclam!ation == 01exclam!ation
02exc!lam!ation ## 02lam!ation
04exc!lam!ation!OS!%OS% ## 04lam!ation!OS!%OS%
1
  • Thank you. I spent a bit of time trying to digest that and with some trial and error I managed to get it working... I hope... Thanks for the detailed response.
    – HTWingNut
    May 18 '20 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.