Regex autoincrement replacements
is there a string in regular expressions that can instruct it to autoincrement it's replacements, whether they be numbers or letters.
Thank you
for instance, I have strings that should be number 1, 2, 3, 4, 5
but they are currently numbered as 1, 1, 1, 1, 1
how would I replace the number in those 5 individual similar strings to be 开发者_运维百科1, 2, 3, 4, 5
I'm not familiar with the syntax of TextWrangler; however, it uses pcre
so this should be what you want as long as you have a way to assign an initial value to your incrementing variable (in this case, I use $ii
)... the script below replaces any occurrence of "pizza-x" with "pizza-0", "pizza-1"...
@foo = ('pizza', 'pizza-a', 'pizza-b', 'pizza-c');
$ii = 0;
foreach (@foo) {
$_ =~ s/(pizza-)[a-z]/"$1".$ii++/e;
print "$_\n";
}
Results...
[mpenning@mpenning-t60 Desktop]$ perl foo.pl
pizza
pizza-0
pizza-1
pizza-2
The magic comes from s///e;
and $ii++
; be sure you enclose the non-incrementing string in quotes and concatenate with a period.
Alternatively, just do your auto-increment mangling with perl -pi -e '$ii = 0; s/something/"here".$ii++/e
` directly on the text file (make a backup copy first, of course).
精彩评论