Get Information with scan Format Strings

The Section MH Format Strings showed how to write format files for scan. Format files, or format strings, are a great way to get information about mail messages for a shell program. For instance, here's a a format string that prints the message number in a field of width 4, a space, then either the Sender: (if the message has one) or the From:. It formats the addresses with the %(friendly) function, which gives a "nice" output when it can.

    $ scan -format "%4(msg) %<{sender}%(friendly{sender})%|%(friendly{from})%>"
      46 "Don C. Meach"
      48 Jerry Peek
You could use a scan format string like that to write a simple loop that processes mail messages automatically. The loop below uses the (mbox) function to get the address without the hostname. (There are more efficient ways to process incoming mail -- see the Chapter Processing New Mail Automatically.)
    msgfrom="%(msg) %<{sender}%(mbox{sender})%|%(mbox{from})%>"
    scan -format "$msgfrom" |
    while read msgnum from
        # DON'T READ ANYTHING FROM steveq; refile ALL mh-users MAIL.
        case "$from" in
        steveq) rmm $msgnum ;;
        mh-users) refile $msgnum +mh-users ;;
This is using a Bourne shell while loop with its standard input taken from the pipe (from the scan command). The read command reads a line of input; it puts the first word (here, the message number) in a shell variable named msgnum, and the rest (the local part of the address) goes into the variable called from. Then, a case structure checks who sent the message and does the right thing with it.