Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

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
share|improve this answer

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

perl -pi -e 's/\[task\K([0-9]+)/3640+$1/e' your_file
share|improve this answer
    
This didn't work. "Sequence \k... not terminated in regex; marked by <-- HERE in m/[task\k <-- HERE ([0-9]+)/ at -e line 1." –  slm Feb 22 at 13:11
1  
@slm he meant \K, I just edited. –  terdon Feb 22 at 14:47
    
@terdon Cheers. –  Joseph R. Feb 22 at 16:40

Here is one way to do it:

perl -pe 's/(\d+)/$1+3640/e if /^\[task.*\]/' file
share|improve this answer
    
This didn't do anything to the results. –  slm Feb 22 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 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 at 15:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.