sed: wc -w
1
1 7.13 Counting Words
1 ===================
1
1 This script is almost the same as the previous one, once each of the
1 words on the line is converted to a single 'a' (in the previous script
1 each letter was changed to an 'a').
1
1 It is interesting that real 'wc' programs have optimized loops for
1 'wc -c', so they are much slower at counting words rather than
1 characters. This script's bottleneck, instead, is arithmetic, and hence
1 the word-counting one is faster (it has to manage smaller numbers).
1
1 Again, the common parts are not commented to show the importance of
1 commenting 'sed' scripts.
1
1 #!/usr/bin/sed -nf
1
1 # Convert words to a's
1 s/[ tab][ tab]*/ /g
1 s/^/ /
1 s/ [^ ][^ ]*/a /g
1 s/ //g
1
1 # Append them to hold space
1 H
1 x
1 s/\n//
1
1 # From here on it is the same as in wc -c.
1 /aaaaaaaaaa/! bx; s/aaaaaaaaaa/b/g
1 /bbbbbbbbbb/! bx; s/bbbbbbbbbb/c/g
1 /cccccccccc/! bx; s/cccccccccc/d/g
1 /dddddddddd/! bx; s/dddddddddd/e/g
1 /eeeeeeeeee/! bx; s/eeeeeeeeee/f/g
1 /ffffffffff/! bx; s/ffffffffff/g/g
1 /gggggggggg/! bx; s/gggggggggg/h/g
1 s/hhhhhhhhhh//g
1 :x
1 $! { h; b; }
1 :y
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 y/bcdefgh/abcdefg/
1 /[a-h]/ by
1 p
1