Windows 批处理 For 循环文件名带有感叹号“!”问题

Windows 批处理 For 循环文件名带有感叹号“!”问题

感叹号是我在 Windows Batch 中遇到的麻烦。比如说,我只想跳过带有感叹号的文件名!

我知道要在 for 循环中检查变量中的常规文本,我可以运行:

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

但是我该如何指定感叹号?

我尝试使用 ^: 来退出"!fname:^!=!"

然后我看到使用 enabledelayedexpansion 时,需要一个^^!转义字符。所以我试了一下,但没有成功。然后我想也许三个^^^!两个转义 delayedexpansion 和一个文件名中的一个...

没有运气...

有什么建议么?

答案1

下列评论脚本揭开了秘密:

@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

结果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%

答案2

由于某种原因,当带有文件名的 for 标记需要进一步处理时(就像我需要的那样),可以使用函数解决它,否则,我无法使用包含感叹号的文件实现最终目标。

例子:

@echo off

SetLocal DisableDelayedExpansion
for /r %%f in (*.zip,*.7z) do (
    call :GetFileFolder "%%~dpf" filefolder
    set "fullfilepath=%%f"
    SetLocal EnableDelayedExpansion
    "c:\program files\7-zip\7z.exe" x "!fullfilepath!" -o".\extract\!filefolder!" -aos > nul
    EndLocal
)
EndLocal
exit /b

:GetFileFolder
SetLocal DisableDelayedExpansion
set "folder=%~1"
if "%folder:~-1%" == "\" set "folder=%folder:~0,-1%"
for %%1 in ("%folder%") do set "folder=%%~nx1"
EndLocal & set "%~2=%folder%"
goto :eof

相关内容