batch-file - 如何使用call命令替换for循环中的多个字符串-替换%是一个问题

标签 batch-file

考虑以下代码:

@echo off
chcp 65001 >NUL

rem Main thread here which shows how to change each letter to UPPERCASE: https://stackoverflow.com/questions/34713621/batch-converting-variable-to-uppercase
rem Comment here: https://stackoverflow.com/a/34734724/8262102
rem I want to use this code to replace multiple strings but I'm having difficulty
rem with getting % replaced with double % symbols.

set "str=Change %% to double %% and replace other ^(And convert brackets^)"
echo %str% (Old variable)
call :VALIDATE str
echo %str% (New variable)
pause
goto :EOF

:VALIDATE
if not defined %~1 exit /b
for %%A in ("^%^%=^%^%^%^%" "(='('" ")=')'") do (
call set %~1=%%%~1:%%~A%%
)
goto :EOF

这会将 ( 替换为 '(') 替换为 ')'

我无法将 % 替换为 %%

我尝试使用 %%^% 来转义 %,但此时代码中没有运气 “^%^%=^%^%^%^%”

我不知道如何做到这一点。

最佳答案

这对你有帮助吗?

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str%
Pause

SetLocal EnableDelayedExpansion
Set "str=!str:%%=%%%%!"
Set "str=!str:(='('!"
Set "str=!str:)=')'!"
EndLocal & Set "str=%str%"

Echo %str%
Pause

或者类似的:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str% (Old variable)
Call :Validate str
Echo %str% (New variable)
Pause
GoTo :EOF

:Validate
If "%~1" == "" Exit /B
SetLocal EnableDelayedExpansion
Set "_=!%~1!"
Set "_=!_:%%=%%%%!"
Set "_=!_:(='('!"
Set "_=!_:)=')'!"
EndLocal & Set "%~1=%_%"
Exit /B

[编辑/]

因为……

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "str=Change %% to %%%%, and %%%% to %%%%%%%%, (and also enclose parentheses in single quotes)."
Echo %str% (Old variable)
Call :Validate str
Echo %str% (New variable)
Pause
GoTo :EOF

:Validate
If "%~1" == "" Exit /B
SetLocal EnableDelayedExpansion
Set "_=!%~1!"
For %%G In ("%%=%%%%" "(='('" ")=')'") Do Set "_=!_:%%~G!"
EndLocal & Set "%~1=%_%"
Exit /B

关于batch-file - 如何使用call命令替换for循环中的多个字符串-替换%是一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61990245/

相关文章:

windows - 在继续批处理脚本之前如何等待服务/进程启动?

php - 带有 php/node/python 脚本的 START/B 不能按预期工作

loops - 循环遍历 9000 个单独的 .pov 文件以创建 9000 个单独的 png

windows - 在编译时获取 NSIS 中的文件夹名称

windows-7 - 通过Windows中的命令行工具合并两个png?

java - 使用不同的构建文件启动 java Eclipse headless 构建

iis - "Error 87 the all option is not recognised in this context"使用DISM启用IIS

java - Gradle 运行 bat 文件作为依赖项

windows - 调用其他批处理文件后批处理中断

file - FOR/R - 使用 set/a [变量] = [变量] + %%~zA