Skip to content

Instantly share code, notes, and snippets.

@lucaswerkmeister
Created February 18, 2019 08:20
Show Gist options
  • Save lucaswerkmeister/23b7cdff228541dda29539b6f9464cf3 to your computer and use it in GitHub Desktop.
Save lucaswerkmeister/23b7cdff228541dda29539b6f9464cf3 to your computer and use it in GitHub Desktop.
sed script to increment an integer by one
#!/bin/sed -f
# if the number is not negative:
/^-/! {
# increment the last digit; mark carry with an “X”
s/9$/X/
s/8$/9/
s/7$/8/
s/6$/7/
s/5$/6/
s/4$/5/
s/3$/4/
s/2$/3/
s/1$/2/
s/0$/1/
# reset the test command: t branches to a label if there was any successful substitution since the last input line or t,
# so here we introduce a no-op branch so that the test below only tests the one previous substitution
t r
:r
# increment digit before carry; loop if this introduces a new carry
:b
s/9X/X0/; t b
s/8X/90/
s/7X/80/
s/6X/70/
s/5X/60/
s/4X/50/
s/3X/40/
s/2X/30/
s/1X/20/
s/0X/10/
# handle final carry
s/^X/10/
}
# same thing in reverse for negative numbers
/^-/ {
s/0$/X/
s/1$/0/
s/2$/1/
s/3$/2/
s/4$/3/
s/5$/4/
s/6$/5/
s/7$/6/
s/8$/7/
s/9$/8/
t r2
:r2
:b2
s/0X/X9/; t b2
s/1X/09/
s/2X/19/
s/3X/29/
s/4X/39/
s/5X/49/
s/6X/59/
s/7X/69/
s/8X/79/
s/9X/89/
s/^-X/-09/
# remove leading zeroes
s/^-0*/-/
# well, except for one
s/^-$/0/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment