6

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.

jasonwryan
  • 71,734
  • 34
  • 193
  • 226
user61043
  • 63
  • 1
  • 3

3 Answers3

2

Here you go (this will change the original file):

perl -pi -e 's/\[task\K([0-9]+)/3640+$1/e' your_file
terdon
  • 234,489
  • 66
  • 447
  • 667
Joseph R.
  • 38,849
  • 7
  • 107
  • 143
2

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
slm
  • 363,520
  • 117
  • 767
  • 871
0

Here is one way to do it:

perl -pe 's/(\d+)/$1+3640/e if /^\[task.*\]/' file
cuonglm
  • 150,973
  • 38
  • 327
  • 406
  • This didn't do anything to the results. – slm Feb 22 '14 at 13:12
  • 1
    @slm it works fine here, it just will replace all numbers irrespective of where they're found which is not a good idea. – terdon Feb 22 '14 at 14:49
  • It also anchors on the beginning of the line, so it would seem to not be the optimal solution. – slm Feb 22 '14 at 15:04