Text Processing – Increment Numbers Inside Strings by an Offset

awkmathsedtext processing

I want to search a text file for strings like these.

[task0]
[task1]
...
[task1613]

and increment each by a given offset, in this case by 3640.
So, with the example I gave above, I'd get the following.

[task3640]
[task3641]
...
[task5253]

I want each of the incremented numbers in their original positions in the target file though,
with [task#] wrapped around the number. Using sed:

sed "/^\[task/s/[0-9]*\]/3640+&/" ./test.file2

I can get something like:

[task3640+0]
[task3640+1]
...
[task3640+1614]

but that isn't very useful because I don't know how to evaluate the expressions in place and

I'm fairly sure that sed isn't suited for this.
I'm thinking that awk or perl would work better for this, but I'm fairly inept at both of them.

Can someone at least point me in the right direction, please? I've spent way longer than I want to admit on this already.

For a more detailed view of what I want to do see this page on pastebin.

Best Answer

Here you can use Perl's look behind to find a section of a string that starts with [task followed by numbers. If this is found it will extract the digits and add 3640 to them.

$ perl -p -e 's/(?<=\[task)([0-9]+)/3640+$1/e' sample.txt 
blah blah blah [task3641] blah blah
blah blah blah [task3642] blah blah
blah blah blah [task5254] blah blah
Related Question