[ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
4.2 Increment a Number
This script is one of a few that demonstrate how to do arithmetic
in sed
. This is indeed possible,(7) 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 |