【问题标题】:sed match lines not containing expression with parenthesissed 匹配行不包含带括号的表达式
【发布时间】:2020-12-13 22:33:37
【问题描述】:

(我有旧版 C+ 代码,它使用 gcc 编译时出现警告,并因 clang 错误而失败。方法签名是 function(int,(char*),(char*)) or function(int,string,string)。此方法在整个代码中大量使用。)

因此,在尝试规范调用时,我尝试使用 sed。 假设这个输入:

function(DEFINED_VAR, (char*)someMethod(OTHER_VAR).c_str() + more->stuff, (char*)"Class::method42()");   // 1
function(DEFINED_VAR,(char*)someMethod(OTHER_VAR).c_str() + more->stuff, (char*)"Class::method42()");    // 2
function(DEFINED_VAR, (char *)someMethod(OTHER_VAR).c_str() + more->stuff, "Class::method42()");         // 3
function(DEFINED_VAR, (char*) someMethod(OTHER_VAR).c_str() + more->stuff, "Class::method42()");         // 4
function(DEFINED_VAR, (char *)someMethod(OTHER_VAR).c_str() + more->stuff, (char*)"Class::method42()");  // 5
function(DEFINED_VAR, (char*)someMethod(OTHER_VAR).c_str() + more->stuff, (char*)"Class::method42()");   // 6
function(DEFINED_VAR, (char*)someMethod(OTHER_VAR).c_str() + more->stuff, (char *)"Class::method42()");  // 7
function(DEFINED_VAR, (char*)someMethod(OTHER_VAR).c_str() + more->stuff, ( char* )"Class::method42()"); // 8
function(DEFINED_VAR, (char*)someMethod(OTHER_VAR).c_str() + more->stuff, "Class::method42()");          // 9
function(DEFINED_VAR, (char*)someMethod(OTHER_VAR).c_str() + more->stuff, (char*)"Class::method42()");   // 10
function(DEFINED_VAR, ( char* )someMethod(OTHER_VAR).c_str() + more->stuff, "Class::method42()");        // 11
function(DEFINED_VAR, (char*)someMethod(OTHER_VAR).c_str() + more->stuff, (char*)"Class::method42()");   // 12

我希望第 3、4、9 和 11 行以 (char*)"whateverstring"); 结尾

到目前为止我尝试过的:

sed -n '/^\s*function\s*(\s*\w.*,\s*(\s*char\s*\*.*,\s*\([^(]\|$\)/p' inputfile.cpp

但我不能完全排除第二个“(char *)”出现以跳过正确的行。

18317221831722 很接近(我更喜欢前者),但 ( 让我望而却步。

我错过了什么?我在 Ubuntu Xenial 上使用 GNU sed。我很喜欢 awk(但我认为它不允许捕获模式匹配)或 perl,如果这里需要的东西并不容易。

VAR 和“字符串”可能会有所不同,我已经考虑了空格。

【问题讨论】:

    标签: c++ c sed


    【解决方案1】:

    使用地址范围,您可以在不匹配两个连续 (char *\*) 的行上应用替换:

    sed '/\(char *\*\).*\(char *\*\)/!s/\("[^"]*");\)/(char*)&/' inputfile.cpp
    

    编辑:

    要确保替换仅适用于函数定义,只需更改替换模式:

    sed '/\(char *\*\).*\(char *\*\)/!s/\(^ *function.*\)\("[^"]*");\)/\1(char*)\2/' inputfile.cpp
    

    【讨论】:

    • 我将不得不研究 s//!s/// 语法,但它似乎会匹配 any 与“char *”的出现,而不仅仅是这些特定的行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多