/ F的`delims`选项中的转义双引号
收藏

我在批处理脚本中遇到了麻烦,该脚本需要将配置文件中的值解析为变量。

适当地匿名化,文件的相关行看起来像

<?define ProductShortName="Foo" ?>

I want to set a variable to Foo. The string ProductShortName is unique enough to get the line with findstr, but then I have to extract the value. The correct approach seems to be for /F, but all of the following give errors:

for /F "delims=^" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)
for /F "delims="" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)
for /F "delims=\" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)
for /F 'delims=^" usebackq' %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)
for /F 'delims=" usebackq' %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)
for /F "delims=" usebackq" %%G in (`findstr /L "ProductShortName" "%~dp0Installer\Branding.wxi"`)

大部分遵循

usebackq" %G in (`findstr /L "ProductShortName" "C:\foo\bar\Installer\Branding.wxi"`) was unexpected at this time.

What's the correct way of escaping it to split the string on "?

最佳答案

您可以使用双引号作为定界符,语法如下:

FOR /F delims^=^"^ tokens^=2 %G IN ('echo I "want" a "pony"') DO @ECHO %G

When run on the command line, using tokens^=2 should give you want, and 4 tokens gets you a pony.

将技术应用于您的原始问题,这应该在您的批处理文件中起作用:

FOR /F delims^=^"^ tokens^=2 %%G IN ('FINDSTR /L "ProductShortName" "data.txt"')

细节

I'm no expert on quirks of the command line parser, but it may help to think of the usual "delims=blah tokens=blah" as a single, combined argument passed to FOR. The caret escaping trick in delims^=blah^ tokens^=blah bypasses the need for enclosing quotes while still treating the sequence as a single argument. I've used a bit of creative analogy here, and the effect isn't universal across the shell. E.g. you can't do dir C:^\Program^ Files (which makes sense since ^ is a valid filename character).

测试用例

通过足够的转义,您可以在命令行上快速检查原始样本:

FOR /F delims^=^"^ tokens^=2 %G IN ('echo ^^^<?define ProductShortName="Foo" ?^^^>') DO @ECHO %G

其他与此相关的人可能想要创建文件testcases.txt:

blah blah "red"
     blah "green" blah
How about a "white" "unicorn"?

并运行类似:

FOR /F delims^=^"^ tokens^=2 %G IN (testcases.txt) DO @ECHO %G

检查各种输入的结果。在这种情况下,它应该产生:

red
green
white

最后一个例子:

FOR /F delims^=^"^ tokens^=2 %G IN ('FINDSTR /L "unicorn" "testcases.txt"') ^
DO @ECHO The unicorn is %G.

最后,请注意我的测试是在Windows Server 2003上完成的。

    公众号
    关注公众号订阅更多技术干货!