All pastes #746947 Raw Edit

silly sed exercise

public text v1 · immutable
·published 2007-10-23 16:49 UTC
rendered paste body
#!/usr/bin/sed -f

# Script to do a weird thing asked for on IRC:
# output lines
# 3 5 7 9 13 35 57 79 135 357 579 1357 3579 13579
# a broken, weird sequence.

# insane version.

# We split up the hold space into several fields, it looks like:
# aaa-bb:ccccccc
# where aaa counts the number of digits at which we are in the sequence (3),
# bb counts the number of sequence members of this amount of digits we still have (2)
# and the c's count the number of lines until the next line to be printed.

# Initialization
1 {
  s/.*/a-bbbb:cc/
  h
  d
}

x
s/c//
/:$/ ! {
  x
  d
}

# Yay, we need to print this line. Fun starts here.
s/b//

# Do we need to skip to the next higher-digit number?
/-:/ b muchinc
# else

# This loop is run as many times as we have a's
:addcs
s/a/A/
# c += 2
s/$/cc/
/a/ {
# c *= 10
# Is \{1,\} posix RE?
  s/c\{1,\}/&&&&&&&&&&/
  b addcs
}

s/A/a/g
# Phew, done.
x
b

# Done? Not quite. We still have to clobber the case of higher-digit.
:muchinc
s/^/a/

# Stop if we're getting out of range
/^aaaaaa/ {
  x
  q
}
# First, the easy part. Reinitialize number of b's.
# This is 6 - number of a's.
s/-:/-bbbbbb:/

:loop
s/a\(A*\)-b/A\1-/
tloop

s/A/a/g

# Now, the really fun part. At a number-of-digits change, we need to skip
# first 3, then 55, then 777, then 9999 lines.

# We use A->E to track how often we need to multiply by 10
# minus one. Think about it.
s/a/E/

# a/e times, c += 2
:compc
# e is the new a.
s/$/cc/
/a/ {
  s/a/A/
  b compc
}
/e/ {
  s/e/E/
  b compc
}
# minus one. Gets us 3/5/7/9.
s/c$//

s/E/e/g
s/A/a/g

s/a/E/
/a/ {
  s/c\{1,\}/&&&&&&&&&&/
  b compc
}

# End of loop.
s/[eE]/a/g

# Add one for the line we just printed.
s/$/c/

# Ooohkay. We should be all set.
x
b