I am trying to use ruby to generate an iterated value in gsub(). The line I wrote is:
ruby -pe '$i=0; gsub(/⎦\d+?⎡/, "⎦#{$i+=1}⎡")' < test.txt
But that doesn’t actually do the iteration; instead, it sets the value of $i to zero and adds 1 to it each time the substitution takes place.
I have also used:
ruby -pe 'BEGIN{$i=0}; gsub(/\d+?/, "#{$i+=1}")' < test.txt
That one outputs the line number instead of the variable iteration value. Shouldn’t the gsub() get called ONLY when the REGEX has a match?
The purpose of the command is to substitute the iterated value + 1 for the next number found in the file. e.g. :
Lorem ipsum dolor 2 sit amet, consectetuer adipiscing elit, sed 7 diam nonummy nibh euismod 1 tincidunt ut laoreet dolore magna 10 aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci 15 tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Output:
Lorem ipsum dolor 1 sit amet, consectetuer adipiscing elit, sed 2 diam nonummy nibh euismod 3 tincidunt ut laoreet dolore magna 4 aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci 5 tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
Update1:
I have tried this line after further reading:
ruby -pe 'BEGIN{$i=0}; gsub /\d+?/, "#{$i+=1}" if ~/\d+?/' < aa01.xhtml
However, it seems that the process in the command lines I used is not correct to start with. It should first find the line which has numbers. Then increment the variable and substitute it in the place of the number found and move to the next number if any are present in the same line.
I think that the expression
"⎦#{$i+=1}⎡"is computed only once. A block is computed at each replacement.outputs :
New input :
output :