2

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

Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
CQM
  • 42,592
  • 75
  • 224
  • 366
  • 1
    Could you provide an example of the autoincrementing you are looking for? Also, regex syntax is not universal; what language will you use? – Mike Pennington Jun 07 '11 at 00:04
  • I use TextWrangler's grep/regex, example added – CQM Jun 07 '11 at 00:10
  • @RD, thank you. According to TextWrangler's docs, they use Perl-Compatable regular expressions (pcre) – Mike Pennington Jun 07 '11 at 00:12
  • Ah, is there an autoincrement function with prce regex or should I ask the stack universe a new question – CQM Jun 07 '11 at 00:18
  • Is "1, 1, 1, 1, 1" the exact string, or is there more to match of besides a comma and space before incrementing? – Mike Pennington Jun 07 '11 at 00:35
  • there is more to each individual string, I'll be looking to implement your answer tomorrow and comment if there is difficulting adapting it – CQM Jun 07 '11 at 01:48

1 Answers1

4

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).

Mike Pennington
  • 41,899
  • 19
  • 136
  • 174