sed: wc -c
1
1 7.12 Counting Characters
1 ========================
1
1 This script shows another way to do arithmetic with 'sed'. In this case
1 we have to add possibly large numbers, so implementing this by
1 successive increments would not be feasible (and possibly even more
1 complicated to contrive than this script).
1
1 The approach is to map numbers to letters, kind of an abacus
1 implemented with 'sed'. 'a's are units, 'b's are tens and so on: we
1 simply add the number of characters on the current line as units, and
1 then propagate the carry to tens, hundreds, and so on.
1
1 As usual, running totals are kept in hold space.
1
1 On the last line, we convert the abacus form back to decimal. For
1 the sake of variety, this is done with a loop rather than with some 80
1 's' commands(1): first we convert units, removing 'a's from the number;
1 then we rotate letters so that tens become 'a's, and so on until no more
1 letters remain.
1
1 #!/usr/bin/sed -nf
1
1 # Add n+1 a's to hold space (+1 is for the newline)
1 s/./a/g
1 H
1 x
1 s/\n/a/
1
1 # Do the carry. The t's and b's are not necessary,
1 # but they do speed up the thing
1 t a
1 : a; s/aaaaaaaaaa/b/g; t b; b done
1 : b; s/bbbbbbbbbb/c/g; t c; b done
1 : c; s/cccccccccc/d/g; t d; b done
1 : d; s/dddddddddd/e/g; t e; b done
1 : e; s/eeeeeeeeee/f/g; t f; b done
1 : f; s/ffffffffff/g/g; t g; b done
1 : g; s/gggggggggg/h/g; t h; b done
1 : h; s/hhhhhhhhhh//g
1
1 : done
1 $! {
1 h
1 b
1 }
1
1 # On the last line, convert back to decimal
1
1 : loop
1 /a/! s/[b-h]*/&0/
1 s/aaaaaaaaa/9/
1 s/aaaaaaaa/8/
1 s/aaaaaaa/7/
1 s/aaaaaa/6/
1 s/aaaaa/5/
1 s/aaaa/4/
1 s/aaa/3/
1 s/aa/2/
1 s/a/1/
1
1 : next
1 y/bcdefgh/abcdefg/
1 /[a-h]/ b loop
1 p
1
1 ---------- Footnotes ----------
1
1 (1) Some implementations have a limit of 199 commands per script
1