字符串变量内的&号会扰乱执行



下面的代码片段在批处理文件中工作得很好,但是当字符串变量中有&符号时不起作用,不幸的是,这将发生在我正在工作的项目中。是否有一种方法重写这两个语句,使&号不劫持语句的执行?

如果"目的"这一点并不明显;我将不得不粘贴大量的行,以使我要做的事情真正明显。我希望人们能把注意力集中在这些线条的微观层面上,而不是让这些线条明显缺乏"大局"。别挡道。

除了这个批处理文件之外,还有一个名为file.txt的文件,其中只有一行:/Here and There/Over & Yonder/This & That。下面是批处理文件代码:

setlocal enabledelayedexpansion
set "FolderName=This & That"
set "ChosenFolder=Here & There/Over & Yonder/This & That"
set "NewFolder=Yin & Yang/Up & Down"
:: Ideally the following problematic line would change the value of %ChosenFolder% to 'Here & There/Over & Yonder', but the ampersands make it fail
For /f "delims=" %%a in ("/!FolderName!") do set "ChosenFolder=!ChosenFolder:%%a=!"
set /a count=0
:: The next problematic line should search file.txt for a string that matches "/Here & There/Over & Yonder" and count the number of matches, but the ampersands make it fail
for /f "delims=" %%a in ('findstr /i /n /c:"/!ChosenFolder!" file.txt" ^| find /c /v ""') do set "count=%%a">nul
:: And finally this problematic line is supposed to actually replace the string with "Yin & Yang/Up & Down"
if %count% gtr 0 type file.txt"|jrepl "/!ChosenFolder!" "/!NewFolder!" /l >temp.txt
echo.
echo FolderName:  %FolderName%
echo ChosenFolder:  %ChosenFolder%  - should be "Here & There/Over & Yonder"
echo NewFolder:  %NewFolder% - should be "Yin & Yang/Up & Down"
echo.
echo file.txt should display "Yin & Yang/Up & Down"
type file.txt
echo.

这不是简单地通过转义各种字符来解决的问题。字符串本身必须是"阴"的。Yang"等,而不是Yin && Yang,Yin ^& Yang等,因为它们将用于文件名,页面标题等,并且转义字符本身将最终显示。我以前见过这种棘手的解决方案,比如把call放在语句前面,把语句包装在括号里,或者,正如我下面试图做的那样,把它们放在for循环中……我只是没能自己破解它。

使用jrepl.bat,可以在这里找到。顺便说一句,我很乐意考虑文本文件搜索/替换的替代方案,这些替代方案不需要我把鸡蛋放在Windows 12或Windows 13中可能不支持的。exe命令行实用程序中,例如美妙的"src .exe"这个文件我20年前用过,但现在已经不能用了。

我不确定您的预期结果应该是什么,因为您声称file.txt包含什么,但您从未替换file.txt中的任何内容,而是将输出重定向到temp.txt

不管怎样,这里是你的代码工作的一个例子:

@echo off
setlocal enabledelayedexpansion
set "FolderName=This & That"
set "ChosenFolder=Here & There/Over & Yonder/This & That"
set "NewFolder=Yin & Yang/Up & Down"
For /f "delims=" %%a in ("/!FolderName!") do set "ChosenFolder=!ChosenFolder:%%a=!"
set /a count=0
for /f "delims=" %%a in ('findstr /i /n /c:"/!ChosenFolder!" "file.txt" ^| find /c /v ""') do set "count=%%a"
if %count% gtr 0 type "file.txt"|"jrepl.bat" "/!ChosenFolder!" "/!NewFolder!" /l > temp.txt
echo(
echo FolderName:  "%FolderName%"
echo ChosenFolder:  "%ChosenFolder%"  - should be "Here & There/Over & Yonder"
echo NewFolder: "%NewFolder%" - should be "Yin & Yang/Up & Down"
echo(
echo file.txt should display "This & That"
type file.txt
echo temp.txt should display "/Yin & Yang/Up & Down/This & That"
type temp.txt
echo.

相关内容

  • 没有找到相关文章

最新更新