如何用cmd.exe中的百分比字符替换? [英] How to replace with percent character in cmd.exe?

查看:193
本文介绍了如何用cmd.exe中的百分比字符替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows命令提示符下,我尝试用 set string = Hello World 替换字符串%20 。尝试使用字符串文字%20,如下所示:

In the Windows command prompt, I am trying to replace the space in set string=Hello World with the string %20. Naively trying to use the string literal %20 like this:

set string=%string: =%20%

结果 HelloWorld20%。尝试使用转义字符 ^ 这样:

results in HelloWorld20%. Trying to use the escape character ^ like this:

set string=%string: =^%20%

还会导致 HelloWorld20%。试图逃避,将其加倍:

also results in HelloWorld20%. Trying to escape the % by doubling it like this:

set string=%string: =%%20%

结果 HelloWorld%20% 。我也尝试使用另一个变量来做这样的替换:

results in HelloWorld%20%. I also tried to use another variable to do the replacement like this:

set r=%20
set string=%string: =%r%%

导致 HelloWorldr %%

我发现这个,它处理变量中百分号字符的转义。我还发现,它处理转义的百分比字符输入。但是没有一个似乎适用于字符串替换。

I found this, which handles the escaping of percent characters in variables. I also found this, which handles the escaped input of percent characters. But neither one seems to apply to string replacing.

A

A tutorial/docu page for the Windows cmd.exe which I found online tells me I have the correct syntax, but does not cover replacing with percent characters.

阅读全部后,我尝试:

setlocal EnableDelayedExpansion
set string=!string: =%20!

导致!string:=%20!

我没有想法,可以帮忙吗?

I am out of ideas, can you help?

推荐答案

在这种情况下,您需要延迟扩展

You need delayed expansion in this case:

set "str1=Hello World!"
set "str2=%20"
for /f "delims=" %a in ('cmd /v:on /c @echo "%str1: =!str2!%"') do set "str3=%~a"
echo %str3%

什么是延迟扩展?

这篇关于如何用cmd.exe中的百分比字符替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆