加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

batch-file – 在Windows批处理文件中回显精确字符串?

发布时间:2020-12-13 22:29:49 所属栏目:Windows 来源:网络整理
导读:我正在尝试回显存储在变量中的字符串,但它似乎需要大量的转义.我正在尝试使用以下代码: setlocal EnableDelayedExpansion@echo offset "grass=@##!$^%**()"echo !grass! 我想逐字回显变量草,所以我在输出中看到@ ##!$^%**().应该做什么?谢谢! 解决方法
我正在尝试回显存储在变量中的字符串,但它似乎需要大量的转义.我正在尝试使用以下代码:

setlocal EnableDelayedExpansion
@echo off
set "grass=@##&!$^&%**(&)"
echo !grass!

我想逐字回显变量草,所以我在输出中看到@ ##&!$^&%**(&).应该做什么?谢谢!

解决方法

回声!草!将始终逐字回显当前值,而无需任何转义.你的问题是,价值不是你想象的那样!当您尝试设置值时,会发生此问题.

设置值的正确转义序列是

set "grass=@##&^!$^^&%%**(&)"

现在来解释一下.你需要的信息埋藏在How does the Windows Command Interpreter (CMD.EXE) parse scripts?年.但它有点难以理解.

你有两个问题:

1)每次解析该行时,%必须以%%的形式进行转义.引号的存在与否都没有区别.延迟扩张状态也没有区别.

set pct=%
 :: pct is undefined

 set pct=%%
 :: pct=%

 call set pct=%%
 :: pct is undefined because the line is parsed twice due to CALL

 call set pct=%%%%
 :: pct=%

2)A!文字必须被转义为^!每当它被解析器的延迟扩展阶段解析.如果一行包含!在延迟扩展期间的任何地方,然后^文字必须转义为^^.但是对于解析器的特殊字符阶段,^也必须被引用或转义为^^.由于CALL会使任何^字符加倍,这可能会进一步复杂化. (抱歉,描述问题非常困难,解析器很复杂!)

setlocal disableDelayedExpansion

set test=^^
:: test=^

set "test=^"
:: test=^

call set test=^^
:: test=^
:: 1st pass - ^^ becomes ^
:: CALL doubles ^,so we are back to ^^
:: 2nd pass - ^^ becomes ^

call set "test=^"
:: test=^^ because of CALL doubling. There is nothing that can prevent this.

set "test=^...!"
:: test=^...!
:: ! has no impact on ^ when delayed expansion is disabled

setlocal enableDelayedExpansion

set "test=^"
:: test=^
:: There is no ! on the line,so no need to escape the quoted ^.

set "test=^!"
:: test=!

set test=^^!
:: test=!
:: ! must be escaped,and then the unquoted escape must be escaped

set var=hello
set "test=!var! ^^ ^!"
:: test=hello ^ !
:: quoted ^ literal must be escaped because ! appears in line

set test=!var! ^^^^ ^^!
:: test=hello ^ !
:: The unquoted escape for the ^ literal must itself be escaped
:: The same is true for the ! literal

call set test=!var! ^^^^ ^^!
:: test=hello ^ !
:: Delayed expansion phase occurs in the 1st pass only
:: CALL doubling protects the unquoted ^ literal in the 2nd pass

call set "test=!var! ^^ ^!"
:: test=hello ^^ !
:: Again,there is no way to prevent the doubling of the quoted ^ literal
:: when it is passed through CALL

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读