Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl one-liner to increment a value

Tags:

perl

I want to increment every number in quotes in a file, one per line:

perl -pe 's/\"(\d+)\"/ 1 + $1 /ge' file

This strips the quotes, but how do add the quotes back in to the output?

like image 641
chuckfinley Avatar asked Jul 20 '12 21:07

chuckfinley


3 Answers

perl -pe 's/\"(\d+)\"/ q{"} . (1 + $1) . q{"} /ge'
like image 110
Roman Cheplyaka Avatar answered Nov 18 '22 05:11

Roman Cheplyaka


You can use look-around assertions - http://perldoc.perl.org/perlre.html#Extended-Patterns.

So the regex becomes: s/(?<=")(\d+)(?=")/ $1 + 1 /ge

like image 26
RickF Avatar answered Nov 18 '22 04:11

RickF


And the golf winner is:

perl -pe's/"(\d+)"/"@{[1+$1]}"/g'
like image 2
Hynek -Pichi- Vychodil Avatar answered Nov 18 '22 04:11

Hynek -Pichi- Vychodil