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

时间:2021-05-28 03:37:56

I am trying to convert as following:

我想转换如下:

bool foo(int a, unsigned short b)
{
    return pImpl->foo(int a, unsigned short b);
}

to:

bool foo(int a, unsigned short b)
{
    return pImpl->foo(a, b);
}

In other words, I need to remove the type definition on the lines which are not the function definition.

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

I am using Linux.

我正在使用Linux。

The following removes the type on both lines:

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

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

How can I replace only on the line beginning with 'return' and still make multiple changes on the same line?

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

2 个解决方案

#1


8  

Add an if statement:

添加if语句:

perl -p -e 's/regex/replacement/g if /^\s*return/;' fileName.cpp

Alternatively, you may utilize that the string you pass to perl -p is a body of a loop:

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

perl -p -e 'next unless /^\s*return/; s/add/replacement/g;' filename.cpp

#2


0  

You could just put something to match -> in your regex so it doesn't match the function definition. Even better would be to write a script which parses line by line and rejects lines without a -> before even doing the substitution.

你可以在你的正则表达式中放置匹配的东西 - >它与函数定义不匹配。更好的方法是编写一个逐行解析的脚本,并在进行替换之前拒绝没有 - >的行。

#1


8  

Add an if statement:

添加if语句:

perl -p -e 's/regex/replacement/g if /^\s*return/;' fileName.cpp

Alternatively, you may utilize that the string you pass to perl -p is a body of a loop:

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

perl -p -e 'next unless /^\s*return/; s/add/replacement/g;' filename.cpp

#2


0  

You could just put something to match -> in your regex so it doesn't match the function definition. Even better would be to write a script which parses line by line and rejects lines without a -> before even doing the substitution.

你可以在你的正则表达式中放置匹配的东西 - >它与函数定义不匹配。更好的方法是编写一个逐行解析的脚本,并在进行替换之前拒绝没有 - >的行。