windows - 如何在 Batch For 循环中获取 C++ 错误

标签 windows batch-file escaping

我正在尝试处理在批处理脚本中编译 C++ 代码时生成的错误。我有一个类似于以下内容的 for 循环:

@FOR /F "delims=" %%A IN ('COMMAND TO COMPILE C++') DO @(
  SET MESSAGE=%%A
  SET MESSAGE=!MESSAGE:"='!
  CALL :PRINT "!MESSAGE!"
)

我遇到的问题是当我收到有关模板、比较运算符、异或运算符或位移运算符的错误时。在这些情况下,%%A 中的错误字符串包含引号和大于/小于符号。例如:

error: yada yada TemplateClass<> "Some Message"
error: yada yada operator <<() 'Some Message'
error: yada yada 'operator ^()' "Some Message"

我的问题是:是否可以捕获 for 循环中包含双引号、单引号和小于/大于字符的整个消息?我尝试过的:

:: Fails when %%A contains a quote
SET "MESSAGE=%%A"
:: Fails when %%A contains a quote
SET MESSAGE="%%A"
:: Fails when %%A contains a greater-than symbol
SET MESSAGE=%%A

有什么方法可以让我在另一个变量中捕获 %%A ,这样我就可以在批处理文件的其他地方使用这个变量吗?谢谢。

最佳答案

将值分配给变量的“正确”方法是set "message=%%a"。但是当调用 print 函数时,不要传递值,而是传递变量名(引用),并在函数内取消引用该变量。

并且,在 :print 函数中,访问变量的内容时,请使用 !var! 表示法以避免特殊字符被视为命令的一部分而不是文本的一部分。

一些示例(dbenham 风格)

@echo off

    setlocal enableextensions

    for /f "tokens=* delims=:" %%f in ('findstr /b /c:":::" "%~f0" ') do (
        set "line=%%f"
        call :print line
    ) 

    exit /b

:print variable
    setlocal enabledelayedexpansion
    echo( Parameter                     : %~1
    echo( Dereferenced value            : !%~1!
    set "var=!%~1!"
    echo( Variable with the value       : !var!

    echo.

    rem If var contains special characters the following line fails
    rem echo( Variable with the value       : %var%

    endlocal
    goto :EOF


exit /b 

:::This is a plain line
:::This line has special characters !"'#$%&/()=?:
:::This line has more special characters << " >>
:::"This is a double quoted line"
:::'This is a single quoted line'

关于windows - 如何在 Batch For 循环中获取 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20414104/

相关文章:

windows - 如何使用 wmic 命令仅从此输出获取设备 ID

batch-file - 批处理命令仅从输入中获取第一行

windows - 如何使用 CMD 命令将文件路径拆分为其组件,并使用双反斜杠再次连接

c# - 在 c# 的 MySQL 查询中使用文字下划线字符

c++ - 有没有办法逃避 C 预处理器指令?

sql-server - 如何在工作组环境中为 MS SQL Server 创建 Windows 服务帐户?

windows - 在Windows计算机上为单个DNS映射覆盖DNS服务器

mysql_real_escape_string 问题

c++ - SetWindowsHookEx WH_KEYBOARD_LL 右移不响应

regex - 在批处理脚本中打印第二个标记之后的所有标记