【问题标题】:Catch an entire function with grep使用 grep 捕获整个函数
【发布时间】:2023-01-25 04:32:47
【问题描述】:

想要用另一个替换文件中的函数。我有这个 :

文件 1.cpp:

void Component::initialize()
{
    my_component = new ComponentClass();
}

和 File2.cpp:

void Component::initialize()
{
    if (doInit)
    {
        my_component = new ComponentClass();
    }
    else
    {
        my_component.ptr = null;
    }
}

我尝试编写一个脚本,但我的 grep 没有提供结果:

Old=$(grep -Eo "void Component::initialize(\n|.)*(^})*?" file1.cpp)
echo "Old=$Old" # empty variable

# My purpose is to do this :
New=$(grep -Eo "void Component::initialize(\n|.)*(^})*?" file2.cpp)
sed -i "s/$Old/$New/g" file1.cpp

【问题讨论】:

  • 在 bash 示例中需要 ")" 两次并决定 File* 或 file*?如果我在行尾添加 2 个“)”并将文件 File* 重命名为 file*,它会给出预期的输出。请在此处发布之前测试您的示例。
  • 正则表达式并不适合这个;要正确解析代码,您需要一个解析器。
  • 使用awk 来实现更聪明的事情。
  • @A.Pissicat 也许改用一种允许多行搜索的语言。红宝石或 Perl。
  • 请edit您的问题并添加一些背景信息。是否必须替换多个文件中的函数? File1.cpp 和File2.cpp 包含更多代码吗?如果是,则添加一些示例代码。 (否则cp File2.cpp File1.cpp)函数是否总是像您的示例中那样格式化和缩进,即第一列中没有其他花括号,函数名称和参数在一行中,函数块的左大括号在函数下方的新行中名称?

标签: bash unix grep


【解决方案1】:
#!/usr/bin/awk -f

/^void Component::initialize()$/ {
    temp = $0

    while (!/^}/ && getline > 0)
        temp = temp ORS $0

    if (NR == FNR) {
        new = temp
        nextfile
    }

    $0 = new
}

NR != FNR

用法:

awk -f script.awk file{2,1}.cpp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2020-11-04
    • 2013-02-14
    相关资源
    最近更新 更多