msbuild - sed 命令错误 - 如何包含单引号和双引号

msbuild - sed command error - how to include single quote and double quote

我有一个 GNU makefile,我正在翻译成 MSBuild

有一个包含 sed 的命令不会在 MSBuild 中 运行 因为它包含干扰单引号的 '(单引号)这应该关闭 Exec 任务的 Command 属性:

<Target Name="prebuild_cat">
    <Exec
        EchoOff="true"
        StandardOutputImportance="low"
        StandardErrorImportance="low"
        IgnoreExitCode="true"
        ConsoleToMSBuild="true" 
        Command=' $(GnuSed) 's/^Q(.*)/"&"/'    
    '>
    </Exec>
</Target>

当我运行这个的时候,Visual Studio说

error MSB4025: The project file could not be loaded. 's' is an unexpected token. Expecting white space. Line 244, position 25.

当我将 ' 替换为 &apos; 并将 " 替换为 &quot;

<Target Name="prebuild_cat">
    <Exec
        EchoOff="true"
        StandardOutputImportance="low"
        StandardErrorImportance="low"
        IgnoreExitCode="true"
        ConsoleToMSBuild="true" 
        Command=' $(GnuSed) &apos;s/^Q(.*)/&quot;&&quot;/&apos;    
    '>
    </Exec>
</Target>

error MSB4025: The project file could not be loaded. An error occurred while parsing EntityName.

msbuild - sed command error - how to include single quote and double quote

根据文档MSBuild Special Characters

MSBuild reserves some characters for special use in specific contexts. You only have to escape such characters if you want to use them literally in the context in which they are reserved.

要转义特殊字符,请使用语法 %xx,其中 xx 表示字符的 ASCII 十六进制值。

在这种情况下,单引号是 ASCII 字符 39,十六进制为 27。 & 的值为 26,因此正确的转义序列为:

'$(GnuSed) %27s/^Q(.*)/"%26"/%27'

下面是我的测试样本,你可以检查它是否适合你:

  <Target Name="prebuild_cat" AfterTargets="Build">
    <Message Text='$(GnuSed) %27s/^Q(.*)/"%26"/%27' Importance='high' />
  </Target>

输出结果windows:

1>prebuild_cat:
1>   's/^Q(.*)/"&"/'
1>
1>Build succeeded.