home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / gnuawk.zip / awklib / eg / prog / wc.awk < prev    next >
Text File  |  1997-03-15  |  1KB  |  69 lines

  1. # wc.awk --- count lines, words, characters
  2. # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  3. # May 1993
  4.  
  5. # Options:
  6. #    -l    only count lines
  7. #    -w    only count words
  8. #    -c    only count characters
  9. #
  10. # Default is to count lines, words, characters
  11.  
  12. BEGIN {
  13.     # let getopt print a message about
  14.     # invalid options. we ignore them
  15.     while ((c = getopt(ARGC, ARGV, "lwc")) != -1) {
  16.         if (c == "l")
  17.             do_lines = 1
  18.         else if (c == "w")
  19.             do_words = 1
  20.         else if (c == "c")
  21.             do_chars = 1
  22.     }
  23.     for (i = 1; i < Optind; i++)
  24.         ARGV[i] = ""
  25.  
  26.     # if no options, do all
  27.     if (! do_lines && ! do_words && ! do_chars)
  28.         do_lines = do_words = do_chars = 1
  29.  
  30.     print_total = (ARGC - i > 2)
  31. }
  32. function beginfile(file)
  33. {
  34.     chars = lines = words = 0
  35.     fname = FILENAME
  36. }
  37.  
  38. function endfile(file)
  39. {
  40.     tchars += chars
  41.     tlines += lines
  42.     twords += words
  43.     if (do_lines)
  44.         printf "\t%d", lines
  45.     if (do_words)
  46.         printf "\t%d", words
  47.     if (do_chars)
  48.         printf "\t%d", chars
  49.     printf "\t%s\n", fname
  50. }
  51. # do per line
  52. {
  53.     chars += length($0) + 1    # get newline
  54.     lines++
  55.     words += NF
  56. }
  57.  
  58. END {
  59.     if (print_total) {
  60.         if (do_lines)
  61.             printf "\t%d", tlines
  62.         if (do_words)
  63.             printf "\t%d", twords
  64.         if (do_chars)
  65.             printf "\t%d", tchars
  66.         print "\ttotal"
  67.     }
  68. }
  69.