windows - 如何在 FOR 循环中处理包含感叹号的文件/文件夹名称列表?
问题描述
我编写批处理脚本来查找文件夹中文件的内容。内容在文本文件中,并带有感叹号等特殊字符。
我如何得到FILENAME
,FOLDERNAME
其中包含感叹号。
@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:源文件夹有很多文件。
解决方案
一种解决方案是使用子例程来避免使用延迟的环境变量扩展:
@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 返回到哪里?
推荐阅读
- c++ - 获取每个目录或子目录中第一个文件的路径
- performance - SQL Developer File Open & Export 显示对话框很慢
- c++ - Qt/C++ 模拟 QSettings
- c# - 将字符串数组传递给 Redshift
- bash - 在 bash 中使用 JSON 文件的名称及其内容创建 JSON 对象
- wordpress - 从 Woocommerce 的管理员列表中发送选定的订单通知电子邮件
- angular - 如何避免 Angular 库中的多个服务实例?(带有延迟加载的模块)
- firebase - Firestore 安全规则是否会提前返回?
- html - 大纲 html5 音频元素
- node.js - MERN OAuth 实现不会重定向到谷歌登录页面