Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing integers in particular positions in perl

I have a string like this:

1,2,4 0:5 1:10 3:14

which I want to convert into

1,2,4 1:5 2:10 4:14

Only numbers before ":" have to be incremented by 1.

I have tried:

perl -w -e '$s="1,2,4 0:5 1:10 3:14"; 
$s =~ s/([0-9]*):/print(($1+1).":")/ge; 
print("$s\n");'

which strangely returns

1:2:4:1,2,4 15 110 114

Is there any easy way of achieving my objective?

like image 508
vervenumen Avatar asked Dec 20 '22 02:12

vervenumen


1 Answers

You were close enough, but it has to match at least one digit, followed by :, and substitution part has to return desired result, not print it.

my $s = "1,2,4 0:5 1:10 3:14"; 
$s =~ s/([0-9]+) (?=:)/ $1+1 /xge; 
print $s, "\n";
like image 199
mpapec Avatar answered Jan 04 '23 23:01

mpapec