procmail
[Top] [All Lists]

Better way of counting characters?

1997-08-26 01:38:26

"Wotan" == Wotan  <wotan(_at_)netcom(_dot_)com> writes:

Wotan> Whats the best way to count the number of characters in a
Wotan> variable? If I set $FROM to the reply-to of the sender, I know
Wotan> I can count the characters like this:

Wotan> echo $FROM | wc -c

Wotan> And either use scoring or test to perform some action.  My
Wotan> question is, is there a bit more system freindly of finding out
Wotan> how many characters are in $FROM?


There may not be much you can do about this. Here are a couple of
suggestions, but seeing as echo is built in to many shells these days
and that wc isn't a resource hog, you may not be able to improve on
the above (or at least the gains may not be worth your while, if they
are gains):

  1) LENGTH = `expr "$FROM" : '.*'`

     Which makes it twice in a week (or so) that I have posted
     something about using expr.


  2) SHELL = /bin/bash          # or some shell with functions
     LENGTH = `length "$FROM"`

     Where length is a shell function you write (and export) that
     returns the length of its argument. You can write this so no
     processes are exec'd, but it may not be worth your while. I'd try

       length () {
         case "$1" in
            '') return 0;;
            ?) return 1;;
            ??) return 2;;
            ???) return 3;;

            ..... etc., # N lines like this.

            N?'s) return N;;

            *)
                 new=`echo "$1" | cut -cN+1-`
                 newlen=`length "$new"`
                 return `expr N + $newlen` ;;
         esac
       }

     Note that I am not claiming this will be faster than setting up
     the pipe, forking and execing the wc, but it may be. If you're
     realy in need of speed cuts, I'd test it (probably with a lighter
     weight shell with functions, like rc).

     Some things to note about this: (a) I haven't tested any of it,
     (b) if you know the frequency distribution of $FROM lengths, you
     can speed this by arranging the order of your case tests to
     better match it (this is shell-dependent, but it's true for at
     least some shells, perhaps many), (c) if the length function sees
     something too long, you lose big time, and (d) N (and hence N+1)
     above get replaced by some number of your choosing, like 20 or
     30.


Terry.

<Prev in Thread] Current Thread [Next in Thread>