如何在Perl中进行条件替换?

use*_*884 5 regex perl

我想转换如下:

bool foo(int a, unsigned short b)
{
    return pImpl->foo(int a, unsigned short b);
}
Run Code Online (Sandbox Code Playgroud)

至:

bool foo(int a, unsigned short b)
{
    return pImpl->foo(a, b);
}
Run Code Online (Sandbox Code Playgroud)

换句话说,我需要删除不是函数定义的行上的类型定义.

我正在使用Linux.

以下内容删除了两行中的类型:

perl -p -e 's/(?<=[,(])\s*?(\w+ )*.*?(\w*)(?=[,)])/ $2/g;' fileName.cpp
Run Code Online (Sandbox Code Playgroud)

如何仅在以"return"开头的行上替换并仍在同一行上进行多项更改?

P S*_*ved 8

添加if声明:

perl -p -e 's/regex/replacement/g if /^\s*return/;' fileName.cpp
Run Code Online (Sandbox Code Playgroud)

或者,您可以利用传递给perl -p的字符串是循环体:

perl -p -e 'next unless /^\s*return/; s/add/replacement/g;' filename.cpp
Run Code Online (Sandbox Code Playgroud)

  • 很高兴看到警告,即使在oneliner中,所以添加-w(或捆绑为-wpe). (2认同)