Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a conditional substitution in Perl?

Tags:

regex

perl

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?

like image 970
user204884 Avatar asked Nov 08 '09 13:11

user204884


1 Answers

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
like image 65
P Shved Avatar answered Sep 23 '22 01:09

P Shved