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

  1. # egrep.awk --- simulate egrep in awk
  2. # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  3. # May 1993
  4.  
  5. # Options:
  6. #    -c    count of lines
  7. #    -s    silent - use exit value
  8. #    -v    invert test, success if no match
  9. #    -i    ignore case
  10. #    -l    print filenames only
  11. #    -e    argument is pattern
  12.  
  13. BEGIN {
  14.     while ((c = getopt(ARGC, ARGV, "ce:svil")) != -1) {
  15.         if (c == "c")
  16.             count_only++
  17.         else if (c == "s")
  18.             no_print++
  19.         else if (c == "v")
  20.             invert++
  21.         else if (c == "i")
  22.             IGNORECASE = 1
  23.         else if (c == "l")
  24.             filenames_only++
  25.         else if (c == "e")
  26.             pattern = Optarg
  27.         else
  28.             usage()
  29.     }
  30.     if (pattern == "")
  31.         pattern = ARGV[Optind++]
  32.  
  33.     for (i = 1; i < Optind; i++)
  34.         ARGV[i] = ""
  35.     if (Optind >= ARGC) {
  36.         ARGV[1] = "-"
  37.         ARGC = 2
  38.     } else if (ARGC - Optind > 1)
  39.         do_filenames++
  40.  
  41. #    if (IGNORECASE)
  42. #        pattern = tolower(pattern)
  43. }
  44. #{
  45. #    if (IGNORECASE)
  46. #        $0 = tolower($0)
  47. #}
  48. function beginfile(junk)
  49. {
  50.     fcount = 0
  51. }
  52. function endfile(file)
  53. {
  54.     if (! no_print && count_only)
  55.         if (do_filenames)
  56.             print file ":" fcount
  57.         else
  58.             print fcount
  59.  
  60.     total += fcount
  61. }
  62. {
  63.     matches = ($0 ~ pattern)
  64.     if (invert)
  65.         matches = ! matches
  66.  
  67.     fcount += matches    # 1 or 0
  68.  
  69.     if (! matches)
  70.         next
  71.  
  72.     if (no_print && ! count_only)
  73.         nextfile
  74.  
  75.     if (filenames_only && ! count_only) {
  76.         print FILENAME
  77.         nextfile
  78.     }
  79.  
  80.     if (do_filenames && ! count_only)
  81.         print FILENAME ":" $0
  82.     else if (! count_only)
  83.         print
  84. }
  85. END    \
  86. {
  87.     if (total == 0)
  88.         exit 1
  89.     exit 0
  90. }
  91. function usage(    e)
  92. {
  93.     e = "Usage: egrep [-csvil] [-e pat] [files ...]"
  94.     print e > "/dev/stderr"
  95.     exit 1
  96. }
  97.