Seth Carnegie
Seth Carnegie

Reputation: 75130

Adding one to matched number in substitution regex

I have a file full of C++ code which is a bunch of small functions that return a number. I am trying to replace each number with the number plus one if the number is greater than 2. So,

int blah() { return 5; }

would become

int blah() { return 6; }

but

int blah() { return 1; }

would remain the same.

How is this done?

Upvotes: 2

Views: 1577

Answers (3)

Blagovest Buyukliev
Blagovest Buyukliev

Reputation: 43508

A bit ugly, but should work:

s/\{\s*return\s+(\d+)\s*;\s*\}/$1 > 2 ? "{ return " . ($1 + 1) . "; }" : $&/ge;

Upvotes: 5

fvox
fvox

Reputation: 1087

Check the number with [3-9]. Example:
/int\s*blah\(\)\s*\{\s*return\s*([3-9]);\s*}/g

EDIT:

To increase a value in the $1, you will need the flag e and concat the string:

$_ = 'int blah() { return 5; }';
s/int\s*blah\(\)\s*\{\s*return\s*([3-9]);\s*}/'int blah() { return '.$1+1 . '; }'/eg;
print;

Upvotes: 0

cirne100
cirne100

Reputation: 1558

perl -e 'use Tie::File;tie @array,'Tie::File',$ARGV[0] || die;s|(return\s+)(\d+)(.*)|$2>1?$1.($2+1).$3:$1.$2.$3|e for (@array);untie @array;' FILENAME

Upvotes: 0

Related Questions