home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume21 / mailmerge / part01 / mailmerge.awk < prev    next >
Encoding:
AWK Script  |  1991-07-26  |  1.7 KB  |  74 lines

  1.  
  2. BEGIN {
  3.     # recall variable L has been setup.
  4.     # first, we swallow the file L into the (integer indexed) array
  5.     # "let_lines".  The variable "line" contains the number of
  6.     # lines in this file, at the end.
  7.     line = 0;
  8.     do {
  9.         eof = getline s < L;
  10.         if (eof > 0) {
  11.                 line++; 
  12.                 let_lines[line] = s;
  13.             }
  14.     } while (eof > 0);
  15.     if (line == 0) {
  16.         print "mailmerge.awk: File " L " does not exist." > "/dev/tty";
  17.         goch = 1; exit 1;
  18.     }
  19. }
  20.  
  21. {taken = 0}
  22.     # "This line has not yet been dealt with.
  23.  
  24. (NF == 0) {taken = 1}
  25.     # Ignore blank lines (i.e., those with no fields).
  26.  
  27. # Now catch the LAYOUT line:
  28. /^#LAYOUT/ {
  29.     taken = 1;
  30.     if (NF == 1) {
  31.         print "mailmerge.awk: LAYOUT must contain some fields!" > "/dev/tty";
  32.         goch = 1; exit 1;
  33.     }
  34.     for (i=2; i<=NF; i++) position[$i] = i-1;
  35.     fnum = NF-1;
  36.         # just gobble layout into "position" associative array.
  37.     gotlayout = 1;
  38. }
  39.  
  40. # Finally, if you have a line with taken == 0, it's a normal DB line.
  41. (taken == 0) {
  42.     if (gotlayout == 0) {
  43.         print "mailmerge.awk: Database file must contain a LAYOUT line before any real data." > "/dev/tty";
  44.         goch = 1; exit 1;
  45.     }
  46.  
  47.     print "";
  48.     print "Input line = " substr($0, 1, 50) " ...";
  49.  
  50.     n = split($0, words, "|");
  51.     if (n != fnum) {
  52.         print "mailmerge.awk: Error on Line " NR " of database" > "/dev/tty";
  53.         print "    (Expect " fnum " fields, got " n ")" > "/dev/tty";
  54.     }
  55.  
  56.     # Now we're all set to generate code.
  57.     # First generate filename.
  58.     ofn = "mm_" L "." (NR-1);
  59.     print "Generating file named " ofn;
  60.  
  61.     # run over lines of letter, doing find-replace.
  62.     for (i=1; i<=line; i++) {
  63.         s = let_lines[i];
  64.         for (v in position)
  65.             if (0 != index(s, v))    # only try replace if it matches
  66.                 gsub(v, words[position[v]], s);
  67.         print s > ofn;
  68.     }
  69. }
  70.  
  71. END {
  72.     if (goch == 1) exit 1;
  73. }
  74.