home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / gawk-2.15.6-bin.lha / info / gawk.info-3 (.txt) < prev    next >
GNU Info File  |  1996-10-12  |  50KB  |  909 lines

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