home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 6 / FreshFish_September1994.bin / bbs / gnu / gawk-2.15.5-src.lha / GNU / src / amiga / gawk-2.15.5 / gawk.info-3 < prev    next >
Encoding:
GNU Info File  |  1994-06-13  |  48.6 KB  |  1,289 lines

  1. This is Info file gawk.info, produced by Makeinfo-1.55 from the input
  2. file /gnu/src/amiga/gawk-2.15.5/gawk.texi.
  3.  
  4.    This file documents `awk', a program that you can use to select
  5. particular records in a file and perform operations upon them.
  6.  
  7.    This is Edition 0.15 of `The GAWK Manual',
  8. for the 2.15 version of the GNU implementation
  9. of AWK.
  10.  
  11.    Copyright (C) 1989, 1991, 1992, 1993 Free Software Foundation, Inc.
  12.  
  13.    Permission is granted to make and distribute verbatim copies of this
  14. manual provided the copyright notice and this permission notice are
  15. preserved on all copies.
  16.  
  17.    Permission is granted to copy and distribute modified versions of
  18. this manual under the conditions for verbatim copying, provided that
  19. the entire resulting derived work is distributed under the terms of a
  20. permission notice identical to this one.
  21.  
  22.    Permission is granted to copy and distribute translations of this
  23. manual into another language, under the above conditions for modified
  24. versions, except that this permission notice may be stated in a
  25. translation approved by the Foundation.
  26.  
  27. 
  28. File: gawk.info,  Node: Output Separators,  Next: OFMT,  Prev: Print Examples,  Up: Printing
  29.  
  30. Output Separators
  31. =================
  32.  
  33.    As mentioned previously, a `print' statement contains a list of
  34. items, separated by commas.  In the output, the items are normally
  35. separated by single spaces.  But they do not have to be spaces; a
  36. single space is only the default.  You can specify any string of
  37. characters to use as the "output field separator" by setting the
  38. built-in variable `OFS'.  The initial value of this variable is the
  39. string `" "', that is, just a single space.
  40.  
  41.    The output from an entire `print' statement is called an "output
  42. record".  Each `print' statement outputs one output record and then
  43. outputs a string called the "output record separator".  The built-in
  44. variable `ORS' specifies this string.  The initial value of the
  45. variable is the string `"\n"' containing a newline character; thus,
  46. normally each `print' statement makes a separate line.
  47.  
  48.    You can change how output fields and records are separated by
  49. assigning new values to the variables `OFS' and/or `ORS'.  The usual
  50. place to do this is in the `BEGIN' rule (*note `BEGIN' and `END'
  51. Special Patterns: BEGIN/END.), so that it happens before any input is
  52. processed.  You may also do this with assignments on the command line,
  53. before the names of your input files.
  54.  
  55.    The following example prints the first and second fields of each
  56. input record separated by a semicolon, with a blank line added after
  57. each line:
  58.  
  59.      awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
  60.                 { print $1, $2 }'  BBS-list
  61.  
  62.    If the value of `ORS' does not contain a newline, all your output
  63. will be run together on a single line, unless you output newlines some
  64. other way.
  65.  
  66. 
  67. File: gawk.info,  Node: OFMT,  Next: Printf,  Prev: Output Separators,  Up: Printing
  68.  
  69. Controlling Numeric Output with `print'
  70. =======================================
  71.  
  72.    When you use the `print' statement to print numeric values, `awk'
  73. internally converts the number to a string of characters, and prints
  74. that string.  `awk' uses the `sprintf' function to do this conversion.
  75. For now, it suffices to say that the `sprintf' function accepts a
  76. "format specification" that tells it how to format numbers (or
  77. strings), and that there are a number of different ways that numbers
  78. can be formatted.  The different format specifications are discussed
  79. more fully in *Note Using `printf' Statements for Fancier Printing:
  80. Printf.
  81.  
  82.    The built-in variable `OFMT' contains the default format
  83. specification that `print' uses with `sprintf' when it wants to convert
  84. a number to a string for printing.  By supplying different format
  85. specifications as the value of `OFMT', you can change how `print' will
  86. print your numbers.  As a brief example:
  87.  
  88.      awk 'BEGIN { OFMT = "%d"  # print numbers as integers
  89.                   print 17.23 }'
  90.  
  91. will print `17'.
  92.  
  93. 
  94. File: gawk.info,  Node: Printf,  Next: Redirection,  Prev: OFMT,  Up: Printing
  95.  
  96. Using `printf' Statements for Fancier Printing
  97. ==============================================
  98.  
  99.    If you want more precise control over the output format than `print'
  100. gives you, use `printf'.  With `printf' you can specify the width to
  101. use for each item, and you can specify various stylistic choices for
  102. numbers (such as what radix to use, whether to print an exponent,
  103. whether to print a sign, and how many digits to print after the decimal
  104. point).  You do this by specifying a string, called the "format
  105. string", which controls how and where to print the other arguments.
  106.  
  107. * Menu:
  108.  
  109. * Basic Printf::                Syntax of the `printf' statement.
  110. * Control Letters::             Format-control letters.
  111. * Format Modifiers::            Format-specification modifiers.
  112. * Printf Examples::             Several examples.
  113.  
  114. 
  115. File: gawk.info,  Node: Basic Printf,  Next: Control Letters,  Prev: Printf,  Up: Printf
  116.  
  117. Introduction to the `printf' Statement
  118. --------------------------------------
  119.  
  120.    The `printf' statement looks like this:
  121.  
  122.      printf FORMAT, ITEM1, ITEM2, ...
  123.  
  124. The entire list of arguments may optionally be enclosed in parentheses.
  125. The parentheses are necessary if any of the item expressions uses a
  126. relational operator; otherwise it could be confused with a redirection
  127. (*note Redirecting Output of `print' and `printf': Redirection.).  The
  128. relational operators are `==', `!=', `<', `>', `>=', `<=', `~' and `!~'
  129. (*note Comparison Expressions: Comparison Ops.).
  130.  
  131.    The difference between `printf' and `print' is the argument FORMAT.
  132. This is an expression whose value is taken as a string; it specifies
  133. how to output each of the other arguments.  It is called the "format
  134. string".
  135.  
  136.    The format string is the same as in the ANSI C library function
  137. `printf'.  Most of FORMAT is text to be output verbatim.  Scattered
  138. among this text are "format specifiers", one per item.  Each format
  139. specifier says to output the next item at that place in the format.
  140.  
  141.    The `printf' statement does not automatically append a newline to its
  142. output.  It outputs only what the format specifies.  So if you want a
  143. newline, you must include one in the format.  The output separator
  144. variables `OFS' and `ORS' have no effect on `printf' statements.
  145.  
  146. 
  147. File: gawk.info,  Node: Control Letters,  Next: Format Modifiers,  Prev: Basic Printf,  Up: Printf
  148.  
  149. Format-Control Letters
  150. ----------------------
  151.  
  152.    A format specifier starts with the character `%' and ends with a
  153. "format-control letter"; it tells the `printf' statement how to output
  154. one item.  (If you actually want to output a `%', write `%%'.)  The
  155. format-control letter specifies what kind of value to print.  The rest
  156. of the format specifier is made up of optional "modifiers" which are
  157. parameters such as the field width to use.
  158.  
  159.    Here is a list of the format-control letters:
  160.  
  161. `c'
  162.      This prints a number as an ASCII character.  Thus, `printf "%c",
  163.      65' outputs the letter `A'.  The output for a string value is the
  164.      first character of the string.
  165.  
  166. `d'
  167.      This prints a decimal integer.
  168.  
  169. `i'
  170.      This also prints a decimal integer.
  171.  
  172. `e'
  173.      This prints a number in scientific (exponential) notation.  For
  174.      example,
  175.  
  176.           printf "%4.3e", 1950
  177.  
  178.      prints `1.950e+03', with a total of four significant figures of
  179.      which three follow the decimal point.  The `4.3' are "modifiers",
  180.      discussed below.
  181.  
  182. `f'
  183.      This prints a number in floating point notation.
  184.  
  185. `g'
  186.      This prints a number in either scientific notation or floating
  187.      point notation, whichever uses fewer characters.
  188.  
  189. `o'
  190.      This prints an unsigned octal integer.
  191.  
  192. `s'
  193.      This prints a string.
  194.  
  195. `x'
  196.      This prints an unsigned hexadecimal integer.
  197.  
  198. `X'
  199.      This prints an unsigned hexadecimal integer.  However, for the
  200.      values 10 through 15, it uses the letters `A' through `F' instead
  201.      of `a' through `f'.
  202.  
  203. `%'
  204.      This isn't really a format-control letter, but it does have a
  205.      meaning when used after a `%': the sequence `%%' outputs one `%'.
  206.      It does not consume an argument.
  207.  
  208. 
  209. File: gawk.info,  Node: Format Modifiers,  Next: Printf Examples,  Prev: Control Letters,  Up: Printf
  210.  
  211. Modifiers for `printf' Formats
  212. ------------------------------
  213.  
  214.    A format specification can also include "modifiers" that can control
  215. how much of the item's value is printed and how much space it gets.  The
  216. modifiers come between the `%' and the format-control letter.  Here are
  217. the possible modifiers, in the order in which they may appear:
  218.  
  219. `-'
  220.      The minus sign, used before the width modifier, says to
  221.      left-justify the argument within its specified width.  Normally
  222.      the argument is printed right-justified in the specified width.
  223.      Thus,
  224.  
  225.           printf "%-4s", "foo"
  226.  
  227.      prints `foo '.
  228.  
  229. `WIDTH'
  230.      This is a number representing the desired width of a field.
  231.      Inserting any number between the `%' sign and the format control
  232.      character forces the field to be expanded to this width.  The
  233.      default way to do this is to pad with spaces on the left.  For
  234.      example,
  235.  
  236.           printf "%4s", "foo"
  237.  
  238.      prints ` foo'.
  239.  
  240.      The value of WIDTH is a minimum width, not a maximum.  If the item
  241.      value requires more than WIDTH characters, it can be as wide as
  242.      necessary.  Thus,
  243.  
  244.           printf "%4s", "foobar"
  245.  
  246.      prints `foobar'.
  247.  
  248.      Preceding the WIDTH with a minus sign causes the output to be
  249.      padded with spaces on the right, instead of on the left.
  250.  
  251. `.PREC'
  252.      This is a number that specifies the precision to use when printing.
  253.      This specifies the number of digits you want printed to the right
  254.      of the decimal point.  For a string, it specifies the maximum
  255.      number of characters from the string that should be printed.
  256.  
  257.    The C library `printf''s dynamic WIDTH and PREC capability (for
  258. example, `"%*.*s"') is supported.  Instead of supplying explicit WIDTH
  259. and/or PREC values in the format string, you pass them in the argument
  260. list.  For example:
  261.  
  262.      w = 5
  263.      p = 3
  264.      s = "abcdefg"
  265.      printf "<%*.*s>\n", w, p, s
  266.  
  267. is exactly equivalent to
  268.  
  269.      s = "abcdefg"
  270.      printf "<%5.3s>\n", s
  271.  
  272. Both programs output `<**abc>'.  (We have used the bullet symbol "*" to
  273. represent a space, to clearly show you that there are two spaces in the
  274. output.)
  275.  
  276.    Earlier versions of `awk' did not support this capability.  You may
  277. simulate it by using concatenation to build up the format string, like
  278. so:
  279.  
  280.      w = 5
  281.      p = 3
  282.      s = "abcdefg"
  283.      printf "<%" w "." p "s>\n", s
  284.  
  285. This is not particularly easy to read, however.
  286.  
  287. 
  288. File: gawk.info,  Node: Printf Examples,  Prev: Format Modifiers,  Up: Printf
  289.  
  290. Examples of Using `printf'
  291. --------------------------
  292.  
  293.    Here is how to use `printf' to make an aligned table:
  294.  
  295.      awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
  296.  
  297. prints the names of bulletin boards (`$1') of the file `BBS-list' as a
  298. string of 10 characters, left justified.  It also prints the phone
  299. numbers (`$2') afterward on the line.  This produces an aligned
  300. two-column table of names and phone numbers:
  301.  
  302.      aardvark   555-5553
  303.      alpo-net   555-3412
  304.      barfly     555-7685
  305.      bites      555-1675
  306.      camelot    555-0542
  307.      core       555-2912
  308.      fooey      555-1234
  309.      foot       555-6699
  310.      macfoo     555-6480
  311.      sdace      555-3430
  312.      sabafoo    555-2127
  313.  
  314.    Did you notice that we did not specify that the phone numbers be
  315. printed as numbers?  They had to be printed as strings because the
  316. numbers are separated by a dash.  This dash would be interpreted as a
  317. minus sign if we had tried to print the phone numbers as numbers.  This
  318. would have led to some pretty confusing results.
  319.  
  320.    We did not specify a width for the phone numbers because they are the
  321. last things on their lines.  We don't need to put spaces after them.
  322.  
  323.    We could make our table look even nicer by adding headings to the
  324. tops of the columns.  To do this, use the `BEGIN' pattern (*note
  325. `BEGIN' and `END' Special Patterns: BEGIN/END.) to force the header to
  326. be printed only once, at the beginning of the `awk' program:
  327.  
  328.      awk 'BEGIN { print "Name      Number"
  329.                   print "----      ------" }
  330.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  331.  
  332.    Did you notice that we mixed `print' and `printf' statements in the
  333. above example?  We could have used just `printf' statements to get the
  334. same results:
  335.  
  336.      awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
  337.                   printf "%-10s %s\n", "----", "------" }
  338.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  339.  
  340. By outputting each column heading with the same format specification
  341. used for the elements of the column, we have made sure that the headings
  342. are aligned just like the columns.
  343.  
  344.    The fact that the same format specification is used three times can
  345. be emphasized by storing it in a variable, like this:
  346.  
  347.      awk 'BEGIN { format = "%-10s %s\n"
  348.                   printf format, "Name", "Number"
  349.                   printf format, "----", "------" }
  350.           { printf format, $1, $2 }' BBS-list
  351.  
  352.    See if you can use the `printf' statement to line up the headings and
  353. table data for our `inventory-shipped' example covered earlier in the
  354. section on the `print' statement (*note The `print' Statement: Print.).
  355.  
  356. 
  357. File: gawk.info,  Node: Redirection,  Next: Special Files,  Prev: Printf,  Up: Printing
  358.  
  359. Redirecting Output of `print' and `printf'
  360. ==========================================
  361.  
  362.    So far we have been dealing only with output that prints to the
  363. standard output, usually your terminal.  Both `print' and `printf' can
  364. also send their output to other places.  This is called "redirection".
  365.  
  366.    A redirection appears after the `print' or `printf' statement.
  367. Redirections in `awk' are written just like redirections in shell
  368. commands, except that they are written inside the `awk' program.
  369.  
  370. * Menu:
  371.  
  372. * File/Pipe Redirection::       Redirecting Output to Files and Pipes.
  373. * Close Output::                How to close output files and pipes.
  374.  
  375. 
  376. File: gawk.info,  Node: File/Pipe Redirection,  Next: Close Output,  Prev: Redirection,  Up: Redirection
  377.  
  378. Redirecting Output to Files and Pipes
  379. -------------------------------------
  380.  
  381.    Here are the three forms of output redirection.  They are all shown
  382. for the `print' statement, but they work identically for `printf' also.
  383.  
  384. `print ITEMS > OUTPUT-FILE'
  385.      This type of redirection prints the items onto the output file
  386.      OUTPUT-FILE.  The file name OUTPUT-FILE can be any expression.
  387.      Its value is changed to a string and then used as a file name
  388.      (*note Expressions as Action Statements: Expressions.).
  389.  
  390.      When this type of redirection is used, the OUTPUT-FILE is erased
  391.      before the first output is written to it.  Subsequent writes do not
  392.      erase OUTPUT-FILE, but append to it.  If OUTPUT-FILE does not
  393.      exist, then it is created.
  394.  
  395.      For example, here is how one `awk' program can write a list of BBS
  396.      names to a file `name-list' and a list of phone numbers to a file
  397.      `phone-list'.  Each output file contains one name or number per
  398.      line.
  399.  
  400.           awk '{ print $2 > "phone-list"
  401.                  print $1 > "name-list" }' BBS-list
  402.  
  403. `print ITEMS >> OUTPUT-FILE'
  404.      This type of redirection prints the items onto the output file
  405.      OUTPUT-FILE.  The difference between this and the single-`>'
  406.      redirection is that the old contents (if any) of OUTPUT-FILE are
  407.      not erased.  Instead, the `awk' output is appended to the file.
  408.  
  409. `print ITEMS | COMMAND'
  410.      It is also possible to send output through a "pipe" instead of
  411.      into a file.   This type of redirection opens a pipe to COMMAND
  412.      and writes the values of ITEMS through this pipe, to another
  413.      process created to execute COMMAND.
  414.  
  415.      The redirection argument COMMAND is actually an `awk' expression.
  416.      Its value is converted to a string, whose contents give the shell
  417.      command to be run.
  418.  
  419.      For example, this produces two files, one unsorted list of BBS
  420.      names and one list sorted in reverse alphabetical order:
  421.  
  422.           awk '{ print $1 > "names.unsorted"
  423.                  print $1 | "sort -r > names.sorted" }' BBS-list
  424.  
  425.      Here the unsorted list is written with an ordinary redirection
  426.      while the sorted list is written by piping through the `sort'
  427.      utility.
  428.  
  429.      Here is an example that uses redirection to mail a message to a
  430.      mailing list `bug-system'.  This might be useful when trouble is
  431.      encountered in an `awk' script run periodically for system
  432.      maintenance.
  433.  
  434.           report = "mail bug-system"
  435.           print "Awk script failed:", $0 | report
  436.           print "at record number", FNR, "of", FILENAME  | report
  437.           close(report)
  438.  
  439.      We call the `close' function here because it's a good idea to close
  440.      the pipe as soon as all the intended output has been sent to it.
  441.      *Note Closing Output Files and Pipes: Close Output, for more
  442.      information on this.  This example also illustrates the use of a
  443.      variable to represent a FILE or COMMAND: it is not necessary to
  444.      always use a string constant.  Using a variable is generally a
  445.      good idea, since `awk' requires you to spell the string value
  446.      identically every time.
  447.  
  448.    Redirecting output using `>', `>>', or `|' asks the system to open a
  449. file or pipe only if the particular FILE or COMMAND you've specified
  450. has not already been written to by your program, or if it has been
  451. closed since it was last written to.
  452.  
  453. 
  454. File: gawk.info,  Node: Close Output,  Prev: File/Pipe Redirection,  Up: Redirection
  455.  
  456. Closing Output Files and Pipes
  457. ------------------------------
  458.  
  459.    When a file or pipe is opened, the file name or command associated
  460. with it is remembered by `awk' and subsequent writes to the same file or
  461. command are appended to the previous writes.  The file or pipe stays
  462. open until `awk' exits.  This is usually convenient.
  463.  
  464.    Sometimes there is a reason to close an output file or pipe earlier
  465. than that.  To do this, use the `close' function, as follows:
  466.  
  467.      close(FILENAME)
  468.  
  469. or
  470.  
  471.      close(COMMAND)
  472.  
  473.    The argument FILENAME or COMMAND can be any expression.  Its value
  474. must exactly equal the string used to open the file or pipe to begin
  475. with--for example, if you open a pipe with this:
  476.  
  477.      print $1 | "sort -r > names.sorted"
  478.  
  479. then you must close it with this:
  480.  
  481.      close("sort -r > names.sorted")
  482.  
  483.    Here are some reasons why you might need to close an output file:
  484.  
  485.    * To write a file and read it back later on in the same `awk'
  486.      program.  Close the file when you are finished writing it; then
  487.      you can start reading it with `getline' (*note Explicit Input with
  488.      `getline': Getline.).
  489.  
  490.    * To write numerous files, successively, in the same `awk' program.
  491.      If you don't close the files, eventually you may exceed a system
  492.      limit on the number of open files in one process.  So close each
  493.      one when you are finished writing it.
  494.  
  495.    * To make a command finish.  When you redirect output through a pipe,
  496.      the command reading the pipe normally continues to try to read
  497.      input as long as the pipe is open.  Often this means the command
  498.      cannot really do its work until the pipe is closed.  For example,
  499.      if you redirect output to the `mail' program, the message is not
  500.      actually sent until the pipe is closed.
  501.  
  502.    * To run the same program a second time, with the same arguments.
  503.      This is not the same thing as giving more input to the first run!
  504.  
  505.      For example, suppose you pipe output to the `mail' program.  If you
  506.      output several lines redirected to this pipe without closing it,
  507.      they make a single message of several lines.  By contrast, if you
  508.      close the pipe after each line of output, then each line makes a
  509.      separate message.
  510.  
  511.    `close' returns a value of zero if the close succeeded.  Otherwise,
  512. the value will be non-zero.  In this case, `gawk' sets the variable
  513. `ERRNO' to a string describing the error that occurred.
  514.  
  515. 
  516. File: gawk.info,  Node: Special Files,  Prev: Redirection,  Up: Printing
  517.  
  518. Standard I/O Streams
  519. ====================
  520.  
  521.    Running programs conventionally have three input and output streams
  522. already available to them for reading and writing.  These are known as
  523. the "standard input", "standard output", and "standard error output".
  524. These streams are, by default, terminal input and output, but they are
  525. often redirected with the shell, via the `<', `<<', `>', `>>', `>&' and
  526. `|' operators.  Standard error is used only for writing error messages;
  527. the reason we have two separate streams, standard output and standard
  528. error, is so that they can be redirected separately.
  529.  
  530.    In other implementations of `awk', the only way to write an error
  531. message to standard error in an `awk' program is as follows:
  532.  
  533.      print "Serious error detected!\n" | "cat 1>&2"
  534.  
  535. This works by opening a pipeline to a shell command which can access the
  536. standard error stream which it inherits from the `awk' process.  This
  537. is far from elegant, and is also inefficient, since it requires a
  538. separate process.  So people writing `awk' programs have often
  539. neglected to do this.  Instead, they have sent the error messages to the
  540. terminal, like this:
  541.  
  542.      NF != 4 {
  543.         printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/tty"
  544.      }
  545.  
  546. This has the same effect most of the time, but not always: although the
  547. standard error stream is usually the terminal, it can be redirected, and
  548. when that happens, writing to the terminal is not correct.  In fact, if
  549. `awk' is run from a background job, it may not have a terminal at all.
  550. Then opening `/dev/tty' will fail.
  551.  
  552.    `gawk' provides special file names for accessing the three standard
  553. streams.  When you redirect input or output in `gawk', if the file name
  554. matches one of these special names, then `gawk' directly uses the
  555. stream it stands for.
  556.  
  557. `/dev/stdin'
  558.      The standard input (file descriptor 0).
  559.  
  560. `/dev/stdout'
  561.      The standard output (file descriptor 1).
  562.  
  563. `/dev/stderr'
  564.      The standard error output (file descriptor 2).
  565.  
  566. `/dev/fd/N'
  567.      The file associated with file descriptor N.  Such a file must have
  568.      been opened by the program initiating the `awk' execution
  569.      (typically the shell).  Unless you take special pains, only
  570.      descriptors 0, 1 and 2 are available.
  571.  
  572.    The file names `/dev/stdin', `/dev/stdout', and `/dev/stderr' are
  573. aliases for `/dev/fd/0', `/dev/fd/1', and `/dev/fd/2', respectively,
  574. but they are more self-explanatory.
  575.  
  576.    The proper way to write an error message in a `gawk' program is to
  577. use `/dev/stderr', like this:
  578.  
  579.      NF != 4 {
  580.        printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/stderr"
  581.      }
  582.  
  583.    `gawk' also provides special file names that give access to
  584. information about the running `gawk' process.  Each of these "files"
  585. provides a single record of information.  To read them more than once,
  586. you must first close them with the `close' function (*note Closing
  587. Input Files and Pipes: Close Input.).  The filenames are:
  588.  
  589. `/dev/pid'
  590.      Reading this file returns the process ID of the current process,
  591.      in decimal, terminated with a newline.
  592.  
  593. `/dev/ppid'
  594.      Reading this file returns the parent process ID of the current
  595.      process, in decimal, terminated with a newline.
  596.  
  597. `/dev/pgrpid'
  598.      Reading this file returns the process group ID of the current
  599.      process, in decimal, terminated with a newline.
  600.  
  601. `/dev/user'
  602.      Reading this file returns a single record terminated with a
  603.      newline.  The fields are separated with blanks.  The fields
  604.      represent the following information:
  605.  
  606.     `$1'
  607.           The value of the `getuid' system call.
  608.  
  609.     `$2'
  610.           The value of the `geteuid' system call.
  611.  
  612.     `$3'
  613.           The value of the `getgid' system call.
  614.  
  615.     `$4'
  616.           The value of the `getegid' system call.
  617.  
  618.      If there are any additional fields, they are the group IDs
  619.      returned by `getgroups' system call.  (Multiple groups may not be
  620.      supported on all systems.)
  621.  
  622.    These special file names may be used on the command line as data
  623. files, as well as for I/O redirections within an `awk' program.  They
  624. may not be used as source files with the `-f' option.
  625.  
  626.    Recognition of these special file names is disabled if `gawk' is in
  627. compatibility mode (*note Invoking `awk': Command Line.).
  628.  
  629.      *Caution*:  Unless your system actually has a `/dev/fd' directory
  630.      (or any of the other above listed special files), the
  631.      interpretation of these file names is done by `gawk' itself.  For
  632.      example, using `/dev/fd/4' for output will actually write on file
  633.      descriptor 4, and not on a new file descriptor that was `dup''ed
  634.      from file descriptor 4.  Most of the time this does not matter;
  635.      however, it is important to *not* close any of the files related
  636.      to file descriptors 0, 1, and 2.  If you do close one of these
  637.      files, unpredictable behavior will result.
  638.  
  639. 
  640. File: gawk.info,  Node: One-liners,  Next: Patterns,  Prev: Printing,  Up: Top
  641.  
  642. Useful "One-liners"
  643. *******************
  644.  
  645.    Useful `awk' programs are often short, just a line or two.  Here is a
  646. collection of useful, short programs to get you started.  Some of these
  647. programs contain constructs that haven't been covered yet.  The
  648. description of the program will give you a good idea of what is going
  649. on, but please read the rest of the manual to become an `awk' expert!
  650.  
  651.    Since you are reading this in Info, each line of the example code is
  652. enclosed in quotes, to represent text that you would type literally.
  653. The examples themselves represent shell commands that use single quotes
  654. to keep the shell from interpreting the contents of the program.  When
  655. reading the examples, focus on the text between the open and close
  656. quotes.
  657.  
  658. `awk '{ if (NF > max) max = NF }'
  659. `     END { print max }''
  660.      This program prints the maximum number of fields on any input line.
  661.  
  662. `awk 'length($0) > 80''
  663.      This program prints every line longer than 80 characters.  The sole
  664.      rule has a relational expression as its pattern, and has no action
  665.      (so the default action, printing the record, is used).
  666.  
  667. `awk 'NF > 0''
  668.      This program prints every line that has at least one field.  This
  669.      is an easy way to delete blank lines from a file (or rather, to
  670.      create a new file similar to the old file but from which the blank
  671.      lines have been deleted).
  672.  
  673. `awk '{ if (NF > 0) print }''
  674.      This program also prints every line that has at least one field.
  675.      Here we allow the rule to match every line, then decide in the
  676.      action whether to print.
  677.  
  678. `awk 'BEGIN { for (i = 1; i <= 7; i++)'
  679. `               print int(101 * rand()) }''
  680.      This program prints 7 random numbers from 0 to 100, inclusive.
  681.  
  682. `ls -l FILES | awk '{ x += $4 } ; END { print "total bytes: " x }''
  683.      This program prints the total number of bytes used by FILES.
  684.  
  685. `expand FILE | awk '{ if (x < length()) x = length() }'
  686. `                  END { print "maximum line length is " x }''
  687.      This program prints the maximum line length of FILE.  The input is
  688.      piped through the `expand' program to change tabs into spaces, so
  689.      the widths compared are actually the right-margin columns.
  690.  
  691. `awk 'BEGIN { FS = ":" }'
  692. `     { print $1 | "sort" }' /etc/passwd'
  693.      This program prints a sorted list of the login names of all users.
  694.  
  695. `awk '{ nlines++ }'
  696. `     END { print nlines }''
  697.      This programs counts lines in a file.
  698.  
  699. `awk 'END { print NR }''
  700.      This program also counts lines in a file, but lets `awk' do the
  701.      work.
  702.  
  703. `awk '{ print NR, $0 }''
  704.      This program adds line numbers to all its input files, similar to
  705.      `cat -n'.
  706.  
  707. 
  708. File: gawk.info,  Node: Patterns,  Next: Actions,  Prev: One-liners,  Up: Top
  709.  
  710. Patterns
  711. ********
  712.  
  713.    Patterns in `awk' control the execution of rules: a rule is executed
  714. when its pattern matches the current input record.  This chapter tells
  715. all about how to write patterns.
  716.  
  717. * Menu:
  718.  
  719. * Kinds of Patterns::           A list of all kinds of patterns.
  720.                                 The following subsections describe
  721.                                 them in detail.
  722. * Regexp::                      Regular expressions such as `/foo/'.
  723. * Comparison Patterns::         Comparison expressions such as `$1 > 10'.
  724. * Boolean Patterns::            Combining comparison expressions.
  725. * Expression Patterns::         Any expression can be used as a pattern.
  726. * Ranges::                      Pairs of patterns specify record ranges.
  727. * BEGIN/END::                   Specifying initialization and cleanup rules.
  728. * Empty::                       The empty pattern, which matches every record.
  729.  
  730. 
  731. File: gawk.info,  Node: Kinds of Patterns,  Next: Regexp,  Prev: Patterns,  Up: Patterns
  732.  
  733. Kinds of Patterns
  734. =================
  735.  
  736.    Here is a summary of the types of patterns supported in `awk'.
  737.  
  738. `/REGULAR EXPRESSION/'
  739.      A regular expression as a pattern.  It matches when the text of the
  740.      input record fits the regular expression.  (*Note Regular
  741.      Expressions as Patterns: Regexp.)
  742.  
  743. `EXPRESSION'
  744.      A single expression.  It matches when its value, converted to a
  745.      number, is nonzero (if a number) or nonnull (if a string).  (*Note
  746.      Expressions as Patterns: Expression Patterns.)
  747.  
  748. `PAT1, PAT2'
  749.      A pair of patterns separated by a comma, specifying a range of
  750.      records.  (*Note Specifying Record Ranges with Patterns: Ranges.)
  751.  
  752. `BEGIN'
  753. `END'
  754.      Special patterns to supply start-up or clean-up information to
  755.      `awk'.  (*Note `BEGIN' and `END' Special Patterns: BEGIN/END.)
  756.  
  757. `NULL'
  758.      The empty pattern matches every input record.  (*Note The Empty
  759.      Pattern: Empty.)
  760.  
  761. 
  762. File: gawk.info,  Node: Regexp,  Next: Comparison Patterns,  Prev: Kinds of Patterns,  Up: Patterns
  763.  
  764. Regular Expressions as Patterns
  765. ===============================
  766.  
  767.    A "regular expression", or "regexp", is a way of describing a class
  768. of strings.  A regular expression enclosed in slashes (`/') is an `awk'
  769. pattern that matches every input record whose text belongs to that
  770. class.
  771.  
  772.    The simplest regular expression is a sequence of letters, numbers, or
  773. both.  Such a regexp matches any string that contains that sequence.
  774. Thus, the regexp `foo' matches any string containing `foo'.  Therefore,
  775. the pattern `/foo/' matches any input record containing `foo'.  Other
  776. kinds of regexps let you specify more complicated classes of strings.
  777.  
  778. * Menu:
  779.  
  780. * Regexp Usage::                How to Use Regular Expressions
  781. * Regexp Operators::            Regular Expression Operators
  782. * Case-sensitivity::            How to do case-insensitive matching.
  783.  
  784. 
  785. File: gawk.info,  Node: Regexp Usage,  Next: Regexp Operators,  Prev: Regexp,  Up: Regexp
  786.  
  787. How to Use Regular Expressions
  788. ------------------------------
  789.  
  790.    A regular expression can be used as a pattern by enclosing it in
  791. slashes.  Then the regular expression is matched against the entire
  792. text of each record.  (Normally, it only needs to match some part of
  793. the text in order to succeed.)  For example, this prints the second
  794. field of each record that contains `foo' anywhere:
  795.  
  796.      awk '/foo/ { print $2 }' BBS-list
  797.  
  798.    Regular expressions can also be used in comparison expressions.  Then
  799. you can specify the string to match against; it need not be the entire
  800. current input record.  These comparison expressions can be used as
  801. patterns or in `if', `while', `for', and `do' statements.
  802.  
  803. `EXP ~ /REGEXP/'
  804.      This is true if the expression EXP (taken as a character string)
  805.      is matched by REGEXP.  The following example matches, or selects,
  806.      all input records with the upper-case letter `J' somewhere in the
  807.      first field:
  808.  
  809.           awk '$1 ~ /J/' inventory-shipped
  810.  
  811.      So does this:
  812.  
  813.           awk '{ if ($1 ~ /J/) print }' inventory-shipped
  814.  
  815. `EXP !~ /REGEXP/'
  816.      This is true if the expression EXP (taken as a character string)
  817.      is *not* matched by REGEXP.  The following example matches, or
  818.      selects, all input records whose first field *does not* contain
  819.      the upper-case letter `J':
  820.  
  821.           awk '$1 !~ /J/' inventory-shipped
  822.  
  823.    The right hand side of a `~' or `!~' operator need not be a constant
  824. regexp (i.e., a string of characters between slashes).  It may be any
  825. expression.  The expression is evaluated, and converted if necessary to
  826. a string; the contents of the string are used as the regexp.  A regexp
  827. that is computed in this way is called a "dynamic regexp".  For example:
  828.  
  829.      identifier_regexp = "[A-Za-z_][A-Za-z_0-9]+"
  830.      $0 ~ identifier_regexp
  831.  
  832. sets `identifier_regexp' to a regexp that describes `awk' variable
  833. names, and tests if the input record matches this regexp.
  834.  
  835. 
  836. File: gawk.info,  Node: Regexp Operators,  Next: Case-sensitivity,  Prev: Regexp Usage,  Up: Regexp
  837.  
  838. Regular Expression Operators
  839. ----------------------------
  840.  
  841.    You can combine regular expressions with the following characters,
  842. called "regular expression operators", or "metacharacters", to increase
  843. the power and versatility of regular expressions.
  844.  
  845.    Here is a table of metacharacters.  All characters not listed in the
  846. table stand for themselves.
  847.  
  848. `^'
  849.      This matches the beginning of the string or the beginning of a line
  850.      within the string.  For example:
  851.  
  852.           ^@chapter
  853.  
  854.      matches the `@chapter' at the beginning of a string, and can be
  855.      used to identify chapter beginnings in Texinfo source files.
  856.  
  857. `$'
  858.      This is similar to `^', but it matches only at the end of a string
  859.      or the end of a line within the string.  For example:
  860.  
  861.           p$
  862.  
  863.      matches a record that ends with a `p'.
  864.  
  865. `.'
  866.      This matches any single character except a newline.  For example:
  867.  
  868.           .P
  869.  
  870.      matches any single character followed by a `P' in a string.  Using
  871.      concatenation we can make regular expressions like `U.A', which
  872.      matches any three-character sequence that begins with `U' and ends
  873.      with `A'.
  874.  
  875. `[...]'
  876.      This is called a "character set".  It matches any one of the
  877.      characters that are enclosed in the square brackets.  For example:
  878.  
  879.           [MVX]
  880.  
  881.      matches any one of the characters `M', `V', or `X' in a string.
  882.  
  883.      Ranges of characters are indicated by using a hyphen between the
  884.      beginning and ending characters, and enclosing the whole thing in
  885.      brackets.  For example:
  886.  
  887.           [0-9]
  888.  
  889.      matches any digit.
  890.  
  891.      To include the character `\', `]', `-' or `^' in a character set,
  892.      put a `\' in front of it.  For example:
  893.  
  894.           [d\]]
  895.  
  896.      matches either `d', or `]'.
  897.  
  898.      This treatment of `\' is compatible with other `awk'
  899.      implementations, and is also mandated by the POSIX Command Language
  900.      and Utilities standard.  The regular expressions in `awk' are a
  901.      superset of the POSIX specification for Extended Regular
  902.      Expressions (EREs).  POSIX EREs are based on the regular
  903.      expressions accepted by the traditional `egrep' utility.
  904.  
  905.      In `egrep' syntax, backslash is not syntactically special within
  906.      square brackets.  This means that special tricks have to be used to
  907.      represent the characters `]', `-' and `^' as members of a
  908.      character set.
  909.  
  910.      In `egrep' syntax, to match `-', write it as `---', which is a
  911.      range containing only `-'.  You may also give `-' as the first or
  912.      last character in the set.  To match `^', put it anywhere except
  913.      as the first character of a set.  To match a `]', make it the
  914.      first character in the set.  For example:
  915.  
  916.           []d^]
  917.  
  918.      matches either `]', `d' or `^'.
  919.  
  920. `[^ ...]'
  921.      This is a "complemented character set".  The first character after
  922.      the `[' *must* be a `^'.  It matches any characters *except* those
  923.      in the square brackets (or newline).  For example:
  924.  
  925.           [^0-9]
  926.  
  927.      matches any character that is not a digit.
  928.  
  929. `|'
  930.      This is the "alternation operator" and it is used to specify
  931.      alternatives.  For example:
  932.  
  933.           ^P|[0-9]
  934.  
  935.      matches any string that matches either `^P' or `[0-9]'.  This
  936.      means it matches any string that contains a digit or starts with
  937.      `P'.
  938.  
  939.      The alternation applies to the largest possible regexps on either
  940.      side.
  941.  
  942. `(...)'
  943.      Parentheses are used for grouping in regular expressions as in
  944.      arithmetic.  They can be used to concatenate regular expressions
  945.      containing the alternation operator, `|'.
  946.  
  947. `*'
  948.      This symbol means that the preceding regular expression is to be
  949.      repeated as many times as possible to find a match.  For example:
  950.  
  951.           ph*
  952.  
  953.      applies the `*' symbol to the preceding `h' and looks for matches
  954.      to one `p' followed by any number of `h's.  This will also match
  955.      just `p' if no `h's are present.
  956.  
  957.      The `*' repeats the *smallest* possible preceding expression.
  958.      (Use parentheses if you wish to repeat a larger expression.)  It
  959.      finds as many repetitions as possible.  For example:
  960.  
  961.           awk '/\(c[ad][ad]*r x\)/ { print }' sample
  962.  
  963.      prints every record in the input containing a string of the form
  964.      `(car x)', `(cdr x)', `(cadr x)', and so on.
  965.  
  966. `+'
  967.      This symbol is similar to `*', but the preceding expression must be
  968.      matched at least once.  This means that:
  969.  
  970.           wh+y
  971.  
  972.      would match `why' and `whhy' but not `wy', whereas `wh*y' would
  973.      match all three of these strings.  This is a simpler way of
  974.      writing the last `*' example:
  975.  
  976.           awk '/\(c[ad]+r x\)/ { print }' sample
  977.  
  978. `?'
  979.      This symbol is similar to `*', but the preceding expression can be
  980.      matched once or not at all.  For example:
  981.  
  982.           fe?d
  983.  
  984.      will match `fed' and `fd', but nothing else.
  985.  
  986. `\'
  987.      This is used to suppress the special meaning of a character when
  988.      matching.  For example:
  989.  
  990.           \$
  991.  
  992.      matches the character `$'.
  993.  
  994.      The escape sequences used for string constants (*note Constant
  995.      Expressions: Constants.) are valid in regular expressions as well;
  996.      they are also introduced by a `\'.
  997.  
  998.    In regular expressions, the `*', `+', and `?' operators have the
  999. highest precedence, followed by concatenation, and finally by `|'.  As
  1000. in arithmetic, parentheses can change how operators are grouped.
  1001.  
  1002. 
  1003. File: gawk.info,  Node: Case-sensitivity,  Prev: Regexp Operators,  Up: Regexp
  1004.  
  1005. Case-sensitivity in Matching
  1006. ----------------------------
  1007.  
  1008.    Case is normally significant in regular expressions, both when
  1009. matching ordinary characters (i.e., not metacharacters), and inside
  1010. character sets.  Thus a `w' in a regular expression matches only a
  1011. lower case `w' and not an upper case `W'.
  1012.  
  1013.    The simplest way to do a case-independent match is to use a character
  1014. set: `[Ww]'.  However, this can be cumbersome if you need to use it
  1015. often; and it can make the regular expressions harder for humans to
  1016. read.  There are two other alternatives that you might prefer.
  1017.  
  1018.    One way to do a case-insensitive match at a particular point in the
  1019. program is to convert the data to a single case, using the `tolower' or
  1020. `toupper' built-in string functions (which we haven't discussed yet;
  1021. *note Built-in Functions for String Manipulation: String Functions.).
  1022. For example:
  1023.  
  1024.      tolower($1) ~ /foo/  { ... }
  1025.  
  1026. converts the first field to lower case before matching against it.
  1027.  
  1028.    Another method is to set the variable `IGNORECASE' to a nonzero
  1029. value (*note Built-in Variables::.).  When `IGNORECASE' is not zero,
  1030. *all* regexp operations ignore case.  Changing the value of
  1031. `IGNORECASE' dynamically controls the case sensitivity of your program
  1032. as it runs.  Case is significant by default because `IGNORECASE' (like
  1033. most variables) is initialized to zero.
  1034.  
  1035.      x = "aB"
  1036.      if (x ~ /ab/) ...   # this test will fail
  1037.      
  1038.      IGNORECASE = 1
  1039.      if (x ~ /ab/) ...   # now it will succeed
  1040.  
  1041.    In general, you cannot use `IGNORECASE' to make certain rules
  1042. case-insensitive and other rules case-sensitive, because there is no way
  1043. to set `IGNORECASE' just for the pattern of a particular rule.  To do
  1044. this, you must use character sets or `tolower'.  However, one thing you
  1045. can do only with `IGNORECASE' is turn case-sensitivity on or off
  1046. dynamically for all the rules at once.
  1047.  
  1048.    `IGNORECASE' can be set on the command line, or in a `BEGIN' rule.
  1049. Setting `IGNORECASE' from the command line is a way to make a program
  1050. case-insensitive without having to edit it.
  1051.  
  1052.    The value of `IGNORECASE' has no effect if `gawk' is in
  1053. compatibility mode (*note Invoking `awk': Command Line.).  Case is
  1054. always significant in compatibility mode.
  1055.  
  1056. 
  1057. File: gawk.info,  Node: Comparison Patterns,  Next: Boolean Patterns,  Prev: Regexp,  Up: Patterns
  1058.  
  1059. Comparison Expressions as Patterns
  1060. ==================================
  1061.  
  1062.    "Comparison patterns" test relationships such as equality between
  1063. two strings or numbers.  They are a special case of expression patterns
  1064. (*note Expressions as Patterns: Expression Patterns.).  They are written
  1065. with "relational operators", which are a superset of those in C.  Here
  1066. is a table of them:
  1067.  
  1068. `X < Y'
  1069.      True if X is less than Y.
  1070.  
  1071. `X <= Y'
  1072.      True if X is less than or equal to Y.
  1073.  
  1074. `X > Y'
  1075.      True if X is greater than Y.
  1076.  
  1077. `X >= Y'
  1078.      True if X is greater than or equal to Y.
  1079.  
  1080. `X == Y'
  1081.      True if X is equal to Y.
  1082.  
  1083. `X != Y'
  1084.      True if X is not equal to Y.
  1085.  
  1086. `X ~ Y'
  1087.      True if X matches the regular expression described by Y.
  1088.  
  1089. `X !~ Y'
  1090.      True if X does not match the regular expression described by Y.
  1091.  
  1092.    The operands of a relational operator are compared as numbers if they
  1093. are both numbers.  Otherwise they are converted to, and compared as,
  1094. strings (*note Conversion of Strings and Numbers: Conversion., for the
  1095. detailed rules).  Strings are compared by comparing the first character
  1096. of each, then the second character of each, and so on, until there is a
  1097. difference.  If the two strings are equal until the shorter one runs
  1098. out, the shorter one is considered to be less than the longer one.
  1099. Thus, `"10"' is less than `"9"', and `"abc"' is less than `"abcd"'.
  1100.  
  1101.    The left operand of the `~' and `!~' operators is a string.  The
  1102. right operand is either a constant regular expression enclosed in
  1103. slashes (`/REGEXP/'), or any expression, whose string value is used as
  1104. a dynamic regular expression (*note How to Use Regular Expressions:
  1105. Regexp Usage.).
  1106.  
  1107.    The following example prints the second field of each input record
  1108. whose first field is precisely `foo'.
  1109.  
  1110.      awk '$1 == "foo" { print $2 }' BBS-list
  1111.  
  1112. Contrast this with the following regular expression match, which would
  1113. accept any record with a first field that contains `foo':
  1114.  
  1115.      awk '$1 ~ "foo" { print $2 }' BBS-list
  1116.  
  1117. or, equivalently, this one:
  1118.  
  1119.      awk '$1 ~ /foo/ { print $2 }' BBS-list
  1120.  
  1121. 
  1122. File: gawk.info,  Node: Boolean Patterns,  Next: Expression Patterns,  Prev: Comparison Patterns,  Up: Patterns
  1123.  
  1124. Boolean Operators and Patterns
  1125. ==============================
  1126.  
  1127.    A "boolean pattern" is an expression which combines other patterns
  1128. using the "boolean operators" "or" (`||'), "and" (`&&'), and "not"
  1129. (`!').  Whether the boolean pattern matches an input record depends on
  1130. whether its subpatterns match.
  1131.  
  1132.    For example, the following command prints all records in the input
  1133. file `BBS-list' that contain both `2400' and `foo'.
  1134.  
  1135.      awk '/2400/ && /foo/' BBS-list
  1136.  
  1137.    The following command prints all records in the input file
  1138. `BBS-list' that contain *either* `2400' or `foo', or both.
  1139.  
  1140.      awk '/2400/ || /foo/' BBS-list
  1141.  
  1142.    The following command prints all records in the input file
  1143. `BBS-list' that do *not* contain the string `foo'.
  1144.  
  1145.      awk '! /foo/' BBS-list
  1146.  
  1147.    Note that boolean patterns are a special case of expression patterns
  1148. (*note Expressions as Patterns: Expression Patterns.); they are
  1149. expressions that use the boolean operators.  *Note Boolean Expressions:
  1150. Boolean Ops, for complete information on the boolean operators.
  1151.  
  1152.    The subpatterns of a boolean pattern can be constant regular
  1153. expressions, comparisons, or any other `awk' expressions.  Range
  1154. patterns are not expressions, so they cannot appear inside boolean
  1155. patterns.  Likewise, the special patterns `BEGIN' and `END', which
  1156. never match any input record, are not expressions and cannot appear
  1157. inside boolean patterns.
  1158.  
  1159. 
  1160. File: gawk.info,  Node: Expression Patterns,  Next: Ranges,  Prev: Boolean Patterns,  Up: Patterns
  1161.  
  1162. Expressions as Patterns
  1163. =======================
  1164.  
  1165.    Any `awk' expression is also valid as an `awk' pattern.  Then the
  1166. pattern "matches" if the expression's value is nonzero (if a number) or
  1167. nonnull (if a string).
  1168.  
  1169.    The expression is reevaluated each time the rule is tested against a
  1170. new input record.  If the expression uses fields such as `$1', the
  1171. value depends directly on the new input record's text; otherwise, it
  1172. depends only on what has happened so far in the execution of the `awk'
  1173. program, but that may still be useful.
  1174.  
  1175.    Comparison patterns are actually a special case of this.  For
  1176. example, the expression `$5 == "foo"' has the value 1 when the value of
  1177. `$5' equals `"foo"', and 0 otherwise; therefore, this expression as a
  1178. pattern matches when the two values are equal.
  1179.  
  1180.    Boolean patterns are also special cases of expression patterns.
  1181.  
  1182.    A constant regexp as a pattern is also a special case of an
  1183. expression pattern.  `/foo/' as an expression has the value 1 if `foo'
  1184. appears in the current input record; thus, as a pattern, `/foo/'
  1185. matches any record containing `foo'.
  1186.  
  1187.    Other implementations of `awk' that are not yet POSIX compliant are
  1188. less general than `gawk': they allow comparison expressions, and
  1189. boolean combinations thereof (optionally with parentheses), but not
  1190. necessarily other kinds of expressions.
  1191.  
  1192. 
  1193. File: gawk.info,  Node: Ranges,  Next: BEGIN/END,  Prev: Expression Patterns,  Up: Patterns
  1194.  
  1195. Specifying Record Ranges with Patterns
  1196. ======================================
  1197.  
  1198.    A "range pattern" is made of two patterns separated by a comma, of
  1199. the form `BEGPAT, ENDPAT'.  It matches ranges of consecutive input
  1200. records.  The first pattern BEGPAT controls where the range begins, and
  1201. the second one ENDPAT controls where it ends.  For example,
  1202.  
  1203.      awk '$1 == "on", $1 == "off"'
  1204.  
  1205. prints every record between `on'/`off' pairs, inclusive.
  1206.  
  1207.    A range pattern starts out by matching BEGPAT against every input
  1208. record; when a record matches BEGPAT, the range pattern becomes "turned
  1209. on".  The range pattern matches this record.  As long as it stays
  1210. turned on, it automatically matches every input record read.  It also
  1211. matches ENDPAT against every input record; when that succeeds, the
  1212. range pattern is turned off again for the following record.  Now it
  1213. goes back to checking BEGPAT against each record.
  1214.  
  1215.    The record that turns on the range pattern and the one that turns it
  1216. off both match the range pattern.  If you don't want to operate on
  1217. these records, you can write `if' statements in the rule's action to
  1218. distinguish them.
  1219.  
  1220.    It is possible for a pattern to be turned both on and off by the same
  1221. record, if both conditions are satisfied by that record.  Then the
  1222. action is executed for just that record.
  1223.  
  1224. 
  1225. File: gawk.info,  Node: BEGIN/END,  Next: Empty,  Prev: Ranges,  Up: Patterns
  1226.  
  1227. `BEGIN' and `END' Special Patterns
  1228. ==================================
  1229.  
  1230.    `BEGIN' and `END' are special patterns.  They are not used to match
  1231. input records.  Rather, they are used for supplying start-up or
  1232. clean-up information to your `awk' script.  A `BEGIN' rule is executed,
  1233. once, before the first input record has been read.  An `END' rule is
  1234. executed, once, after all the input has been read.  For example:
  1235.  
  1236.      awk 'BEGIN { print "Analysis of `foo'" }
  1237.           /foo/ { ++foobar }
  1238.           END   { print "`foo' appears " foobar " times." }' BBS-list
  1239.  
  1240.    This program finds the number of records in the input file `BBS-list'
  1241. that contain the string `foo'.  The `BEGIN' rule prints a title for the
  1242. report.  There is no need to use the `BEGIN' rule to initialize the
  1243. counter `foobar' to zero, as `awk' does this for us automatically
  1244. (*note Variables::.).
  1245.  
  1246.    The second rule increments the variable `foobar' every time a record
  1247. containing the pattern `foo' is read.  The `END' rule prints the value
  1248. of `foobar' at the end of the run.
  1249.  
  1250.    The special patterns `BEGIN' and `END' cannot be used in ranges or
  1251. with boolean operators (indeed, they cannot be used with any operators).
  1252.  
  1253.    An `awk' program may have multiple `BEGIN' and/or `END' rules.  They
  1254. are executed in the order they appear, all the `BEGIN' rules at
  1255. start-up and all the `END' rules at termination.
  1256.  
  1257.    Multiple `BEGIN' and `END' sections are useful for writing library
  1258. functions, since each library can have its own `BEGIN' or `END' rule to
  1259. do its own initialization and/or cleanup.  Note that the order in which
  1260. library functions are named on the command line controls the order in
  1261. which their `BEGIN' and `END' rules are executed.  Therefore you have
  1262. to be careful to write such rules in library files so that the order in
  1263. which they are executed doesn't matter.  *Note Invoking `awk': Command
  1264. Line, for more information on using library functions.
  1265.  
  1266.    If an `awk' program only has a `BEGIN' rule, and no other rules,
  1267. then the program exits after the `BEGIN' rule has been run.  (Older
  1268. versions of `awk' used to keep reading and ignoring input until end of
  1269. file was seen.)  However, if an `END' rule exists as well, then the
  1270. input will be read, even if there are no other rules in the program.
  1271. This is necessary in case the `END' rule checks the `NR' variable.
  1272.  
  1273.    `BEGIN' and `END' rules must have actions; there is no default
  1274. action for these rules since there is no current record when they run.
  1275.  
  1276. 
  1277. File: gawk.info,  Node: Empty,  Prev: BEGIN/END,  Up: Patterns
  1278.  
  1279. The Empty Pattern
  1280. =================
  1281.  
  1282.    An empty pattern is considered to match *every* input record.  For
  1283. example, the program:
  1284.  
  1285.      awk '{ print $1 }' BBS-list
  1286.  
  1287. prints the first field of every record.
  1288.  
  1289.