hedleyyan hedleyyan - 10 months ago 58
Perl Question

How to use backreferrence matches for simple math operations?

I have one file looks like:

~ cat dump.txt
<ItemSpec id="46301" Day="1" Week="244251"/>
<ItemSpec id="46302" Day="2" Week="244252"/>
<ItemSpec id="46303" Day="3" Week="244253"/>
<ItemSpec id="46304" Day="4" Week="244254"/>
<ItemSpec id="46305" Day="5" Week="244255|244256|244257|244255|244256|244257|244255|244256|244257|244255|244256|244257"/>

I want the
column number add 100,000 after process, just like:

~ <simple shell code> dump.txt
<ItemSpec id="46301" Day="1" Week="344251"/>
<ItemSpec id="46302" Day="2" Week="344252"/>
<ItemSpec id="46303" Day="3" Week="344253"/>
<ItemSpec id="46304" Day="4" Week="344254"/>
<ItemSpec id="46305" Day="5" Week="344255|344256|344257|344255|344256|344257|344255|344256|344257|344255|344256|344257"/>

I don't know if there is a simple way to use backreference as a number for math operation. And my helpless try as below:

~ awk '{print gensub(/([0-9]{6})/,"\\1+100000","g",$0)}' dump.txt
<ItemSpec id="46301" Day="1" Week="244251+100000"/>
<ItemSpec id="46302" Day="2" Week="244252+100000"/>
<ItemSpec id="46303" Day="3" Week="244253+100000"/>
<ItemSpec id="46304" Day="4" Week="244254+100000"/>
<ItemSpec id="46305" Day="5" Week="244255+100000|244256+100000|244257+100000|244255+100000|244256+100000|244257+100000|244255+100000|244256+100000|244257+100000|244255+100000|244256+100000|244257+100000"/>


Any idea would be helpful, thank you!

Answer Source

Found one similar question and problem solved!

Math operations in regex

perl -pe 's/(\d{6})/$1+100000/eg' dump.txt