如何转义/传递百分号字符给子程序

huangapple go评论79阅读模式
英文:

How to escape / pass the % character to the Sub

问题

I have this batch file, where I am trying to extract a substring but in the end result the % character is being removed. Eg some%value becomes somevalue. I have escaped the & character but nothing works for the percent character.

setlocal enabledelayedexpansion

For /F "Delims=" %%A In ('FindStr /I "<start>.*</end>" "AllApiLogs.log"') Do (
	Call :Sub "%%A"
)
GoTo :EOF

:Sub
Set "Line=%~1"
Set "Line=!Line:&amp;amp;=^&amp;!"
Set "Up2Sub=!Line:*<start>=!"
Set "SubStr=!Up2Sub:</end>=&amp;:&!"
Echo '!SubStr!', >> ApiRegExExtract.log
Exit /B

How do I work around this?
Is there a way to escape all characters that need escaping in batch files? I am new to these.

英文:

I have this batch file, where I am trying to extract a substring but in the end result the % character is being removed. Eg some%value becomes somevalue. I have escaped the &amp;amp; character but nothing works for the percent character.

setlocal enabledelayedexpansion

For /F &quot;Delims=&quot; %%A In (&#39;FindStr /I &quot;&lt;start&gt;.*&lt;/end&gt;&quot; &quot;AllApiLogs.log&quot;&#39;) Do (
	Call :Sub &quot;%%A&quot;
)
GoTo :EOF

:Sub
Set &quot;Line=%~1&quot;
Set &quot;Line=%Line:&amp;amp;=^&amp;%&quot;
Set &quot;Up2Sub=%Line:*&lt;start&gt;=%&quot;
Set &quot;SubStr=%Up2Sub:&lt;/end&gt;=&quot;&amp;:&quot;%&quot;
Echo &#39;%SubStr%&#39;, &gt;&gt; ApiRegExExtract.log
Exit /B

How do I work around this?
Is there a way to escape all characters that need escaping in batch files? I am new to these.

答案1

得分: 1

你可以使用插入符号(caret)来转义百分号(%)。
通过将百分号(%)重复两次来转义它,因此要表示百分号(%),请使用%%来转义此字符。

英文:

You can not escape a % with a caret.
You can escape a % by doubling it, so for % use a % to escape this character.

答案2

得分: 1

在你的情况下,通过使用Call :Sub "%%A",你会失去百分号。

只需更改为:

For /F "Delims=" %%A In ('FindStr /I "<start>.*</end>" "AllApiLogs.log"') Do (
    set "line=%%A"
    Call :Sub
)
GoTo :EOF

:Sub

Set "Line=%Line:&amp;=^&%..."

这是CALL命令的效果,它解析参数两次。

英文:

In your case, you lose the percent sign by using Call :Sub &quot;%%A&quot;.

Just change that to:

For /F &quot;Delims=&quot; %%A In (&#39;FindStr /I &quot;&lt;start&gt;.*&lt;/end&gt;&quot; &quot;AllApiLogs.log&quot;&#39;) Do (
    set &quot;line=%%A&quot;
    Call :Sub
)
GoTo :EOF

:Sub

Set &quot;Line=%Line:&amp;amp;=^&amp;%&quot;
...

It's an effect of the CALL command, it parses the arguments two times

huangapple
  • 本文由 发表于 2023年5月26日 16:25:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定