tags:

views:

226

answers:

2

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.

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?

A: 

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.

Kinopiko
Wouldn't I then have to remember all the fields for recomposition in the replacement?
Is it hard to do that?
Kinopiko
The number of parameters in the function may of course vary
+8  A: 

Add an if statement:

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 -e 'next unless /^\s*return/; s/add/replacement/g;' filename.cpp
Pavel Shved
ah - of course! Thanks.
It's good to see warnings, even in oneliners, so add a -w (or bundle as -wpe).
ysth