Search code examples
bashreplacesedexpression-evaluation

sed replace number with number-1


Can sed handle a substitution and simultaneously evaluate an expression to substitute somehow?

For example, I have the following entry in a text file:

##################################### topd Tree1 - Tree14 #######################################

For reasons I won't go in to, each Tree's number is N+1 relative to another numbering scheme I've been using so far.

Could sed (or any util really, sed is just my go to for find-and-replace operations), find every instance of TreeN and replace them with TreeN-1 such that the above line would then look like:

##################################### topd Tree0 - Tree13 #######################################

(Using Ubuntu 12.02, so pretty much anything goes.)


Solution

  • Using perl

    perl -pe 's/Tree\K\d+/$&-1/ge' file
    

    Output

    ##################################### topd Tree0 - Tree13 #######################################