sed: Increment a number

1 
1 7.3 Increment a Number
1 ======================
1 
1 This script is one of a few that demonstrate how to do arithmetic in
1 'sed'.  This is indeed possible,(1) but must be done manually.
1 
1    To increment one number you just add 1 to last digit, replacing it by
1 the following digit.  There is one exception: when the digit is a nine
1 the previous digits must be also incremented until you don't have a
1 nine.
1 
1    This solution by Bruno Haible is very clever and smart because it
1 uses a single buffer; if you don't have this limitation, the algorithm
1 used in ⇒Numbering lines cat -n, is faster.  It works by replacing
1 trailing nines with an underscore, then using multiple 's' commands to
1 increment the last digit, and then again substituting underscores with
1 zeros.
1 
1      #!/usr/bin/sed -f
1 
1      /[^0-9]/ d
1 
1      # replace all trailing 9s by _ (any other character except digits, could
1      # be used)
1      :d
1      s/9\(_*\)$/_\1/
1      td
1 
1      # incr last digit only.  The first line adds a most-significant
1      # digit of 1 if we have to add a digit.
1 
1      s/^\(_*\)$/1\1/; tn
1      s/8\(_*\)$/9\1/; tn
1      s/7\(_*\)$/8\1/; tn
1      s/6\(_*\)$/7\1/; tn
1      s/5\(_*\)$/6\1/; tn
1      s/4\(_*\)$/5\1/; tn
1      s/3\(_*\)$/4\1/; tn
1      s/2\(_*\)$/3\1/; tn
1      s/1\(_*\)$/2\1/; tn
1      s/0\(_*\)$/1\1/; tn
1 
1      :n
1      y/_/0/
1 
1    ---------- Footnotes ----------
1 
1    (1) 'sed' guru Greg Ubben wrote an implementation of the 'dc' RPN
1 calculator!  It is distributed together with sed.
1