首页 > 解决方案 > 如何在 FOR 循环中处理包含感叹号的文件/文件夹名称列表?

问题描述

我编写批处理脚本来查找文件夹中文件的内容。内容在文本文件中,并带有感叹号等特殊字符。

我如何得到FILENAMEFOLDERNAME其中包含感叹号。

@ECHO off
SETLOCAL EnableDelayedExpansion

set /p SRC="Enter source folder link: "
set /p DST="Enter destination folder link: "

FOR /F "delims=" %%a IN ('DIR /b /s /a-d "%SRC%"') do (
    Set "CODE=%%~na"
    Set "EXT=%%~xa"
    findstr /c:"!CODE!" "%SRC%\Content.txt">nul
    IF "!errorlevel!" EQU "0" (
        for /F "tokens=2,3" %%c in ('findstr /c:"!CODE!" "%SRC%\Content.txt"') do (
            ECHO !CODE!
            Set "NEWNAME=%%c"
            Set "FOLDERNAME=%%d"
            Set "NEWNAME=!NEWNAME:_= !"
            Set "FOLDERNAME=!FOLDERNAME:_= !"
            IF not exist "%DST%\!FOLDERNAME!" md "%DST%\!FOLDERNAME!"
            mklink "%DST%\!FOLDERNAME!\!NEWNAME!!EXT!" "%%a"
        )
    )
)
Endlocal
Exit

PS:源文件夹有很多文件。

标签: windowsbatch-filecmd

解决方案


一种解决方案是使用子例程来避免使用延迟的环境变量扩展:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

:GetSource
set "SRC="
set /P SRC="Enter source folder link: "
if not defined SRC goto GetSource
set "SRC=%SRC:"=%"
if not defined SRC goto GetSource

:GetDestination
set "DST="
set /P DST="Enter destination folder link: "
if not defined DST goto GetDestination
set "DST=%DST:"=%"
if not defined DST goto GetDestination

for /F "eol=| delims=" %%I in ('dir /A-D /B /S "%SRC%" 2^>nul') do (
    if exist "%SRC%\Content.txt" for /F "tokens=2,3" %%A in ('%SystemRoot%\System32\findstr.exe /C:"%%~nI" "%SRC%\Content.txt" 2^>nul') do (
        set "NEWNAME=%%~A"
        set "FOLDERNAME=%%~B"
        call :MakeLink "%%I"
    )
)

endlocal
exit /B

:MakeLink
echo %~n1
set "NEWNAME=%NEWNAME:_= %"
set "FOLDERNAME=%FOLDERNAME:_= %"
if not exist "%DST%\%FOLDERNAME%" md "%DST%\%FOLDERNAME%"
mklink "%DST%\%FOLDERNAME%\%NEWNAME%%~x1" %1
goto :EOF

打开命令提示符窗口并运行call /?以获取帮助,解释如何使用启用命令扩展的命令CALL像子例程一样运行同一批处理文件中的块。另请参阅GOTO :EOF 返回到哪里?


推荐阅读