Next: , Previous: Centering lines, Up: Examples


4.2 Increment a Number

This script is one of a few that demonstrate how to do arithmetic in sed. This is indeed possible,1 but must be done manually.

To increment one number you just add 1 to last digit, replacing it by the following digit. There is one exception: when the digit is a nine the previous digits must be also incremented until you don't have a nine.

This solution by Bruno Haible is very clever and smart because it uses a single buffer; if you don't have this limitation, the algorithm used in Numbering lines, is faster. It works by replacing trailing nines with an underscore, then using multiple s commands to increment the last digit, and then again substituting underscores with zeros.

     #!/usr/bin/sed -f
     
     /[^0-9]/ d
     
     # replace all leading 9s by _ (any other character except digits, could
     # be used)
     :d
     s/9\(_*\)$/_\1/
     td
     
     # incr last digit only.  The first line adds a most-significant
     # digit of 1 if we have to add a digit.
     #
     # The tn commands are not necessary, but make the thing
     # faster
     
     s/^\(_*\)$/1\1/; tn
     s/8\(_*\)$/9\1/; tn
     s/7\(_*\)$/8\1/; tn
     s/6\(_*\)$/7\1/; tn
     s/5\(_*\)$/6\1/; tn
     s/4\(_*\)$/5\1/; tn
     s/3\(_*\)$/4\1/; tn
     s/2\(_*\)$/3\1/; tn
     s/1\(_*\)$/2\1/; tn
     s/0\(_*\)$/1\1/; tn
     
     :n
     y/_/0/

Footnotes

[1] sed guru Greg Ubben wrote an implementation of the dc rpn calculator! It is distributed together with sed.