home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / gawk-2.15.6-bin.lha / info / gawk.info-6 (.txt) < prev    next >
GNU Info File  |  1996-10-12  |  49KB  |  906 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: I/O Functions,  Next: Time Functions,  Prev: String Functions,  Up: Built-in
  21. Built-in Functions for Input/Output
  22. ===================================
  23. `close(FILENAME)'
  24.      Close the file FILENAME, for input or output.  The argument may
  25.      alternatively be a shell command that was used for redirecting to
  26.      or from a pipe; then the pipe is closed.
  27.      *Note Closing Input Files and Pipes: Close Input, regarding closing
  28.      input files and pipes.  *Note Closing Output Files and Pipes:
  29.      Close Output, regarding closing output files and pipes.
  30. `system(COMMAND)'
  31.      The system function allows the user to execute operating system
  32.      commands and then return to the `awk' program.  The `system'
  33.      function executes the command given by the string COMMAND.  It
  34.      returns, as its value, the status returned by the command that was
  35.      executed.
  36.      For example, if the following fragment of code is put in your `awk'
  37.      program:
  38.           END {
  39.                system("mail -s 'awk run done' operator < /dev/null")
  40.           }
  41.      the system operator will be sent mail when the `awk' program
  42.      finishes processing input and begins its end-of-input processing.
  43.      Note that much the same result can be obtained by redirecting
  44.      `print' or `printf' into a pipe.  However, if your `awk' program
  45.      is interactive, `system' is useful for cranking up large
  46.      self-contained programs, such as a shell or an editor.
  47.      Some operating systems cannot implement the `system' function.
  48.      `system' causes a fatal error if it is not supported.
  49. Controlling Output Buffering with `system'
  50. ------------------------------------------
  51.    Many utility programs will "buffer" their output; they save
  52. information to be written to a disk file or terminal in memory, until
  53. there is enough to be written in one operation.  This is often more
  54. efficient than writing every little bit of information as soon as it is
  55. ready.  However, sometimes it is necessary to force a program to
  56. "flush" its buffers; that is, write the information to its destination,
  57. even if a buffer is not full.  You can do this from your `awk' program
  58. by calling `system' with a null string as its argument:
  59.      system("")   # flush output
  60. `gawk' treats this use of the `system' function as a special case, and
  61. is smart enough not to run a shell (or other command interpreter) with
  62. the empty command.  Therefore, with `gawk', this idiom is not only
  63. useful, it is efficient.  While this idiom should work with other `awk'
  64. implementations, it will not necessarily avoid starting an unnecessary
  65. shell.
  66. File: gawk.info,  Node: Time Functions,  Prev: I/O Functions,  Up: Built-in
  67. Functions for Dealing with Time Stamps
  68. ======================================
  69.    A common use for `awk' programs is the processing of log files.  Log
  70. files often contain time stamp information, indicating when a
  71. particular log record was written.  Many programs log their time stamp
  72. in the form returned by the `time' system call, which is the number of
  73. seconds since a particular epoch.  On POSIX systems, it is the number
  74. of seconds since Midnight, January 1, 1970, UTC.
  75.    In order to make it easier to process such log files, and to easily
  76. produce useful reports, `gawk' provides two functions for working with
  77. time stamps.  Both of these are `gawk' extensions; they are not
  78. specified in the POSIX standard, nor are they in any other known version
  79. of `awk'.
  80. `systime()'
  81.      This function returns the current time as the number of seconds
  82.      since the system epoch.  On POSIX systems, this is the number of
  83.      seconds since Midnight, January 1, 1970, UTC.  It may be a
  84.      different number on other systems.
  85. `strftime(FORMAT, TIMESTAMP)'
  86.      This function returns a string.  It is similar to the function of
  87.      the same name in the ANSI C standard library.  The time specified
  88.      by TIMESTAMP is used to produce a string, based on the contents of
  89.      the FORMAT string.
  90.    The `systime' function allows you to compare a time stamp from a log
  91. file with the current time of day.  In particular, it is easy to
  92. determine how long ago a particular record was logged.  It also allows
  93. you to produce log records using the "seconds since the epoch" format.
  94.    The `strftime' function allows you to easily turn a time stamp into
  95. human-readable information.  It is similar in nature to the `sprintf'
  96. function, copying non-format specification characters verbatim to the
  97. returned string, and substituting date and time values for format
  98. specifications in the FORMAT string.  If no TIMESTAMP argument is
  99. supplied, `gawk' will use the current time of day as the time stamp.
  100.    `strftime' is guaranteed by the ANSI C standard to support the
  101. following date format specifications:
  102.      The locale's abbreviated weekday name.
  103.      The locale's full weekday name.
  104.      The locale's abbreviated month name.
  105.      The locale's full month name.
  106.      The locale's "appropriate" date and time representation.
  107.      The day of the month as a decimal number (01-31).
  108.      The hour (24-hour clock) as a decimal number (00-23).
  109.      The hour (12-hour clock) as a decimal number (01-12).
  110.      The day of the year as a decimal number (001-366).
  111.      The month as a decimal number (01-12).
  112.      The minute as a decimal number (00-59).
  113.      The locale's equivalent of the AM/PM designations associated with
  114.      a 12-hour clock.
  115.      The second as a decimal number (00-61).  (Occasionally there are
  116.      minutes in a year with one or two leap seconds, which is why the
  117.      seconds can go from 0 all the way to 61.)
  118.      The week number of the year (the first Sunday as the first day of
  119.      week 1) as a decimal number (00-53).
  120.      The weekday as a decimal number (0-6).  Sunday is day 0.
  121.      The week number of the year (the first Monday as the first day of
  122.      week 1) as a decimal number (00-53).
  123.      The locale's "appropriate" date representation.
  124.      The locale's "appropriate" time representation.
  125.      The year without century as a decimal number (00-99).
  126.      The year with century as a decimal number.
  127.      The time zone name or abbreviation, or no characters if no time
  128.      zone is determinable.
  129.      A literal `%'.
  130.    If a conversion specifier is not one of the above, the behavior is
  131. undefined.  (This is because the ANSI standard for C leaves the
  132. behavior of the C version of `strftime' undefined, and `gawk' will use
  133. the system's version of `strftime' if it's there.  Typically, the
  134. conversion specifier will either not appear in the returned string, or
  135. it will appear literally.)
  136.    Informally, a "locale" is the geographic place in which a program is
  137. meant to run.  For example, a common way to abbreviate the date
  138. September 4, 1991 in the United States would be "9/4/91".  In many
  139. countries in Europe, however, it would be abbreviated "4.9.91".  Thus,
  140. the `%x' specification in a `"US"' locale might produce `9/4/91', while
  141. in a `"EUROPE"' locale, it might produce `4.9.91'.  The ANSI C standard
  142. defines a default `"C"' locale, which is an environment that is typical
  143. of what most C programmers are used to.
  144.    A public-domain C version of `strftime' is shipped with `gawk' for
  145. systems that are not yet fully ANSI-compliant.  If that version is used
  146. to compile `gawk' (*note Installing `gawk': Installation.), then the
  147. following additional format specifications are available:
  148.      Equivalent to specifying `%m/%d/%y'.
  149.      The day of the month, padded with a blank if it is only one digit.
  150.      Equivalent to `%b', above.
  151.      A newline character (ASCII LF).
  152.      Equivalent to specifying `%I:%M:%S %p'.
  153.      Equivalent to specifying `%H:%M'.
  154.      Equivalent to specifying `%H:%M:%S'.
  155.      A TAB character.
  156.      is replaced by the hour (24-hour clock) as a decimal number (0-23).
  157.      Single digit numbers are padded with a blank.
  158.      is replaced by the hour (12-hour clock) as a decimal number (1-12).
  159.      Single digit numbers are padded with a blank.
  160.      The century, as a number between 00 and 99.
  161.      is replaced by the weekday as a decimal number [1 (Monday)-7].
  162.      is replaced by the week number of the year (the first Monday as
  163.      the first day of week 1) as a decimal number (01-53).  The method
  164.      for determining the week number is as specified by ISO 8601 (to
  165.      wit: if the week containing January 1 has four or more days in the
  166.      new year, then it is week 1, otherwise it is week 53 of the
  167.      previous year and the next week is week 1).
  168. `%Ec %EC %Ex %Ey %EY %Od %Oe %OH %OI'
  169. `%Om %OM %OS %Ou %OU %OV %Ow %OW %Oy'
  170.      These are "alternate representations" for the specifications that
  171.      use only the second letter (`%c', `%C', and so on).  They are
  172.      recognized, but their normal representations are used.  (These
  173.      facilitate compliance with the POSIX `date' utility.)
  174.      The date in VMS format (e.g. 20-JUN-1991).
  175.    Here are two examples that use `strftime'.  The first is an `awk'
  176. version of the C `ctime' function.  (This is a user defined function,
  177. which we have not discussed yet.  *Note User-defined Functions:
  178. User-defined, for more information.)
  179.      # ctime.awk
  180.      #
  181.      # awk version of C ctime(3) function
  182.      
  183.      function ctime(ts,    format)
  184.      {
  185.          format = "%a %b %e %H:%M:%S %Z %Y"
  186.          if (ts == 0)
  187.              ts = systime()         # use current time as default
  188.          return strftime(format, ts)
  189.      }
  190.    This next example is an `awk' implementation of the POSIX `date'
  191. utility.  Normally, the `date' utility prints the current date and time
  192. of day in a well known format.  However, if you provide an argument to
  193. it that begins with a `+', `date' will copy non-format specifier
  194. characters to the standard output, and will interpret the current time
  195. according to the format specifiers in the string.  For example:
  196.      date '+Today is %A, %B %d, %Y.'
  197. might print
  198.      Today is Thursday, July 11, 1991.
  199.    Here is the `awk' version of the `date' utility.
  200.      #! /bin/gawk -f
  201.      #
  202.      # date --- implement the P1003.2 Draft 11 'date' command
  203.      #
  204.      # Bug: does not recognize the -u argument.
  205.      
  206.      BEGIN    \
  207.      {
  208.          format = "%a %b %e %H:%M:%S %Z %Y"
  209.          exitval = 0
  210.      
  211.          if (ARGC > 2)
  212.              exitval = 1
  213.          else if (ARGC == 2) {
  214.              format = ARGV[1]
  215.              if (format ~ /^\+/)
  216.                  format = substr(format, 2)    # remove leading +
  217.          }
  218.          print strftime(format)
  219.          exit exitval
  220.      }
  221. File: gawk.info,  Node: User-defined,  Next: Built-in Variables,  Prev: Built-in,  Up: Top
  222. User-defined Functions
  223. **********************
  224.    Complicated `awk' programs can often be simplified by defining your
  225. own functions.  User-defined functions can be called just like built-in
  226. ones (*note Function Calls::.), but it is up to you to define them--to
  227. tell `awk' what they should do.
  228. * Menu:
  229. * Definition Syntax::           How to write definitions and what they mean.
  230. * Function Example::            An example function definition and
  231.                                 what it does.
  232. * Function Caveats::            Things to watch out for.
  233. * Return Statement::            Specifying the value a function returns.
  234. File: gawk.info,  Node: Definition Syntax,  Next: Function Example,  Prev: User-defined,  Up: User-defined
  235. Syntax of Function Definitions
  236. ==============================
  237.    Definitions of functions can appear anywhere between the rules of the
  238. `awk' program.  Thus, the general form of an `awk' program is extended
  239. to include sequences of rules *and* user-defined function definitions.
  240.    The definition of a function named NAME looks like this:
  241.      function NAME (PARAMETER-LIST) {
  242.           BODY-OF-FUNCTION
  243.      }
  244. NAME is the name of the function to be defined.  A valid function name
  245. is like a valid variable name: a sequence of letters, digits and
  246. underscores, not starting with a digit.  Functions share the same pool
  247. of names as variables and arrays.
  248.    PARAMETER-LIST is a list of the function's arguments and local
  249. variable names, separated by commas.  When the function is called, the
  250. argument names are used to hold the argument values given in the call.
  251. The local variables are initialized to the null string.
  252.    The BODY-OF-FUNCTION consists of `awk' statements.  It is the most
  253. important part of the definition, because it says what the function
  254. should actually *do*.  The argument names exist to give the body a way
  255. to talk about the arguments; local variables, to give the body places
  256. to keep temporary values.
  257.    Argument names are not distinguished syntactically from local
  258. variable names; instead, the number of arguments supplied when the
  259. function is called determines how many argument variables there are.
  260. Thus, if three argument values are given, the first three names in
  261. PARAMETER-LIST are arguments, and the rest are local variables.
  262.    It follows that if the number of arguments is not the same in all
  263. calls to the function, some of the names in PARAMETER-LIST may be
  264. arguments on some occasions and local variables on others.  Another way
  265. to think of this is that omitted arguments default to the null string.
  266.    Usually when you write a function you know how many names you intend
  267. to use for arguments and how many you intend to use as locals.  By
  268. convention, you should write an extra space between the arguments and
  269. the locals, so other people can follow how your function is supposed to
  270. be used.
  271.    During execution of the function body, the arguments and local
  272. variable values hide or "shadow" any variables of the same names used
  273. in the rest of the program.  The shadowed variables are not accessible
  274. in the function definition, because there is no way to name them while
  275. their names have been taken away for the local variables.  All other
  276. variables used in the `awk' program can be referenced or set normally
  277. in the function definition.
  278.    The arguments and local variables last only as long as the function
  279. body is executing.  Once the body finishes, the shadowed variables come
  280. back.
  281.    The function body can contain expressions which call functions.  They
  282. can even call this function, either directly or by way of another
  283. function.  When this happens, we say the function is "recursive".
  284.    There is no need in `awk' to put the definition of a function before
  285. all uses of the function.  This is because `awk' reads the entire
  286. program before starting to execute any of it.
  287.    In many `awk' implementations, the keyword `function' may be
  288. abbreviated `func'.  However, POSIX only specifies the use of the
  289. keyword `function'.  This actually has some practical implications.  If
  290. `gawk' is in POSIX-compatibility mode (*note Invoking `awk': Command
  291. Line.), then the following statement will *not* define a function:
  292.      func foo() { a = sqrt($1) ; print a }
  293. Instead it defines a rule that, for each record, concatenates the value
  294. of the variable `func' with the return value of the function `foo', and
  295. based on the truth value of the result, executes the corresponding
  296. action.  This is probably not what was desired.  (`awk' accepts this
  297. input as syntactically valid, since functions may be used before they
  298. are defined in `awk' programs.)
  299. File: gawk.info,  Node: Function Example,  Next: Function Caveats,  Prev: Definition Syntax,  Up: User-defined
  300. Function Definition Example
  301. ===========================
  302.    Here is an example of a user-defined function, called `myprint', that
  303. takes a number and prints it in a specific format.
  304.      function myprint(num)
  305.      {
  306.           printf "%6.3g\n", num
  307.      }
  308. To illustrate, here is an `awk' rule which uses our `myprint' function:
  309.      $3 > 0     { myprint($3) }
  310. This program prints, in our special format, all the third fields that
  311. contain a positive number in our input.  Therefore, when given:
  312.       1.2   3.4    5.6   7.8
  313.       9.10 11.12 -13.14 15.16
  314.      17.18 19.20  21.22 23.24
  315. this program, using our function to format the results, prints:
  316.         5.6
  317.        21.2
  318.    Here is a rather contrived example of a recursive function.  It
  319. prints a string backwards:
  320.      function rev (str, len) {
  321.          if (len == 0) {
  322.              printf "\n"
  323.              return
  324.          }
  325.          printf "%c", substr(str, len, 1)
  326.          rev(str, len - 1)
  327.      }
  328. File: gawk.info,  Node: Function Caveats,  Next: Return Statement,  Prev: Function Example,  Up: User-defined
  329. Calling User-defined Functions
  330. ==============================
  331.    "Calling a function" means causing the function to run and do its
  332. job.  A function call is an expression, and its value is the value
  333. returned by the function.
  334.    A function call consists of the function name followed by the
  335. arguments in parentheses.  What you write in the call for the arguments
  336. are `awk' expressions; each time the call is executed, these
  337. expressions are evaluated, and the values are the actual arguments.  For
  338. example, here is a call to `foo' with three arguments (the first being
  339. a string concatenation):
  340.      foo(x y, "lose", 4 * z)
  341.      *Caution:* whitespace characters (spaces and tabs) are not allowed
  342.      between the function name and the open-parenthesis of the argument
  343.      list.  If you write whitespace by mistake, `awk' might think that
  344.      you mean to concatenate a variable with an expression in
  345.      parentheses.  However, it notices that you used a function name
  346.      and not a variable name, and reports an error.
  347.    When a function is called, it is given a *copy* of the values of its
  348. arguments.  This is called "call by value".  The caller may use a
  349. variable as the expression for the argument, but the called function
  350. does not know this: it only knows what value the argument had.  For
  351. example, if you write this code:
  352.      foo = "bar"
  353.      z = myfunc(foo)
  354. then you should not think of the argument to `myfunc' as being "the
  355. variable `foo'."  Instead, think of the argument as the string value,
  356. `"bar"'.
  357.    If the function `myfunc' alters the values of its local variables,
  358. this has no effect on any other variables.  In particular, if `myfunc'
  359. does this:
  360.      function myfunc (win) {
  361.        print win
  362.        win = "zzz"
  363.        print win
  364.      }
  365. to change its first argument variable `win', this *does not* change the
  366. value of `foo' in the caller.  The role of `foo' in calling `myfunc'
  367. ended when its value, `"bar"', was computed.  If `win' also exists
  368. outside of `myfunc', the function body cannot alter this outer value,
  369. because it is shadowed during the execution of `myfunc' and cannot be
  370. seen or changed from there.
  371.    However, when arrays are the parameters to functions, they are *not*
  372. copied.  Instead, the array itself is made available for direct
  373. manipulation by the function.  This is usually called "call by
  374. reference".  Changes made to an array parameter inside the body of a
  375. function *are* visible outside that function.  This can be *very*
  376. dangerous if you do not watch what you are doing.  For example:
  377.      function changeit (array, ind, nvalue) {
  378.           array[ind] = nvalue
  379.      }
  380.      
  381.      BEGIN {
  382.                 a[1] = 1 ; a[2] = 2 ; a[3] = 3
  383.                 changeit(a, 2, "two")
  384.                 printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3]
  385.            }
  386. prints `a[1] = 1, a[2] = two, a[3] = 3', because calling `changeit'
  387. stores `"two"' in the second element of `a'.
  388. File: gawk.info,  Node: Return Statement,  Prev: Function Caveats,  Up: User-defined
  389. The `return' Statement
  390. ======================
  391.    The body of a user-defined function can contain a `return' statement.
  392. This statement returns control to the rest of the `awk' program.  It
  393. can also be used to return a value for use in the rest of the `awk'
  394. program.  It looks like this:
  395.      return EXPRESSION
  396.    The EXPRESSION part is optional.  If it is omitted, then the returned
  397. value is undefined and, therefore, unpredictable.
  398.    A `return' statement with no value expression is assumed at the end
  399. of every function definition.  So if control reaches the end of the
  400. function body, then the function returns an unpredictable value.  `awk'
  401. will not warn you if you use the return value of such a function; you
  402. will simply get unpredictable or unexpected results.
  403.    Here is an example of a user-defined function that returns a value
  404. for the largest number among the elements of an array:
  405.      function maxelt (vec,   i, ret) {
  406.           for (i in vec) {
  407.                if (ret == "" || vec[i] > ret)
  408.                     ret = vec[i]
  409.           }
  410.           return ret
  411.      }
  412. You call `maxelt' with one argument, which is an array name.  The local
  413. variables `i' and `ret' are not intended to be arguments; while there
  414. is nothing to stop you from passing two or three arguments to `maxelt',
  415. the results would be strange.  The extra space before `i' in the
  416. function parameter list is to indicate that `i' and `ret' are not
  417. supposed to be arguments.  This is a convention which you should follow
  418. when you define functions.
  419.    Here is a program that uses our `maxelt' function.  It loads an
  420. array, calls `maxelt', and then reports the maximum number in that
  421. array:
  422.      awk '
  423.      function maxelt (vec,   i, ret) {
  424.           for (i in vec) {
  425.                if (ret == "" || vec[i] > ret)
  426.                     ret = vec[i]
  427.           }
  428.           return ret
  429.      }
  430.      
  431.      # Load all fields of each record into nums.
  432.      {
  433.                for(i = 1; i <= NF; i++)
  434.                     nums[NR, i] = $i
  435.      }
  436.      
  437.      END {
  438.           print maxelt(nums)
  439.      }'
  440.    Given the following input:
  441.       1 5 23 8 16
  442.      44 3 5 2 8 26
  443.      256 291 1396 2962 100
  444.      -6 467 998 1101
  445.      99385 11 0 225
  446. our program tells us (predictably) that:
  447.      99385
  448. is the largest number in our array.
  449. File: gawk.info,  Node: Built-in Variables,  Next: Command Line,  Prev: User-defined,  Up: Top
  450. Built-in Variables
  451. ******************
  452.    Most `awk' variables are available for you to use for your own
  453. purposes; they never change except when your program assigns values to
  454. them, and never affect anything except when your program examines them.
  455.    A few variables have special built-in meanings.  Some of them `awk'
  456. examines automatically, so that they enable you to tell `awk' how to do
  457. certain things.  Others are set automatically by `awk', so that they
  458. carry information from the internal workings of `awk' to your program.
  459.    This chapter documents all the built-in variables of `gawk'.  Most
  460. of them are also documented in the chapters where their areas of
  461. activity are described.
  462. * Menu:
  463. * User-modified::               Built-in variables that you change
  464.                                 to control `awk'.
  465. * Auto-set::                    Built-in variables where `awk'
  466.                                 gives you information.
  467. File: gawk.info,  Node: User-modified,  Next: Auto-set,  Prev: Built-in Variables,  Up: Built-in Variables
  468. Built-in Variables that Control `awk'
  469. =====================================
  470.    This is a list of the variables which you can change to control how
  471. `awk' does certain things.
  472. `CONVFMT'
  473.      This string is used by `awk' to control conversion of numbers to
  474.      strings (*note Conversion of Strings and Numbers: Conversion.).
  475.      It works by being passed, in effect, as the first argument to the
  476.      `sprintf' function.  Its default value is `"%.6g"'.  `CONVFMT' was
  477.      introduced by the POSIX standard.
  478. `FIELDWIDTHS'
  479.      This is a space separated list of columns that tells `gawk' how to
  480.      manage input with fixed, columnar boundaries.  It is an
  481.      experimental feature that is still evolving.  Assigning to
  482.      `FIELDWIDTHS' overrides the use of `FS' for field splitting.
  483.      *Note Reading Fixed-width Data: Constant Size, for more
  484.      information.
  485.      If `gawk' is in compatibility mode (*note Invoking `awk': Command
  486.      Line.), then `FIELDWIDTHS' has no special meaning, and field
  487.      splitting operations are done based exclusively on the value of
  488.      `FS'.
  489.      `FS' is the input field separator (*note Specifying how Fields are
  490.      Separated: Field Separators.).  The value is a single-character
  491.      string or a multi-character regular expression that matches the
  492.      separations between fields in an input record.
  493.      The default value is `" "', a string consisting of a single space.
  494.      As a special exception, this value actually means that any
  495.      sequence of spaces and tabs is a single separator.  It also causes
  496.      spaces and tabs at the beginning or end of a line to be ignored.
  497.      You can set the value of `FS' on the command line using the `-F'
  498.      option:
  499.           awk -F, 'PROGRAM' INPUT-FILES
  500.      If `gawk' is using `FIELDWIDTHS' for field-splitting, assigning a
  501.      value to `FS' will cause `gawk' to return to the normal,
  502.      regexp-based, field splitting.
  503. `IGNORECASE'
  504.      If `IGNORECASE' is nonzero, then *all* regular expression matching
  505.      is done in a case-independent fashion.  In particular, regexp
  506.      matching with `~' and `!~', and the `gsub' `index', `match',
  507.      `split' and `sub' functions all ignore case when doing their
  508.      particular regexp operations.  *Note:* since field splitting with
  509.      the value of the `FS' variable is also a regular expression
  510.      operation, that too is done with case ignored.  *Note
  511.      Case-sensitivity in Matching: Case-sensitivity.
  512.      If `gawk' is in compatibility mode (*note Invoking `awk': Command
  513.      Line.), then `IGNORECASE' has no special meaning, and regexp
  514.      operations are always case-sensitive.
  515. `OFMT'
  516.      This string is used by `awk' to control conversion of numbers to
  517.      strings (*note Conversion of Strings and Numbers: Conversion.) for
  518.      printing with the `print' statement.  It works by being passed, in
  519.      effect, as the first argument to the `sprintf' function.  Its
  520.      default value is `"%.6g"'.  Earlier versions of `awk' also used
  521.      `OFMT' to specify the format for converting numbers to strings in
  522.      general expressions; this has been taken over by `CONVFMT'.
  523. `OFS'
  524.      This is the output field separator (*note Output Separators::.).
  525.      It is output between the fields output by a `print' statement.  Its
  526.      default value is `" "', a string consisting of a single space.
  527. `ORS'
  528.      This is the output record separator.  It is output at the end of
  529.      every `print' statement.  Its default value is a string containing
  530.      a single newline character, which could be written as `"\n"'.
  531.      (*Note Output Separators::.)
  532.      This is `awk''s input record separator.  Its default value is a
  533.      string containing a single newline character, which means that an
  534.      input record consists of a single line of text.  (*Note How Input
  535.      is Split into Records: Records.)
  536. `SUBSEP'
  537.      `SUBSEP' is the subscript separator.  It has the default value of
  538.      `"\034"', and is used to separate the parts of the name of a
  539.      multi-dimensional array.  Thus, if you access `foo[12,3]', it
  540.      really accesses `foo["12\0343"]' (*note Multi-dimensional Arrays:
  541.      Multi-dimensional.).
  542. File: gawk.info,  Node: Auto-set,  Prev: User-modified,  Up: Built-in Variables
  543. Built-in Variables that Convey Information
  544. ==========================================
  545.    This is a list of the variables that are set automatically by `awk'
  546. on certain occasions so as to provide information to your program.
  547. `ARGC'
  548. `ARGV'
  549.      The command-line arguments available to `awk' programs are stored
  550.      in an array called `ARGV'.  `ARGC' is the number of command-line
  551.      arguments present.  *Note Invoking `awk': Command Line.  `ARGV' is
  552.      indexed from zero to `ARGC - 1'.  For example:
  553.           awk 'BEGIN {
  554.                  for (i = 0; i < ARGC; i++)
  555.                      print ARGV[i]
  556.                }' inventory-shipped BBS-list
  557.      In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
  558.      `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.  The
  559.      value of `ARGC' is 3, one more than the index of the last element
  560.      in `ARGV' since the elements are numbered from zero.
  561.      The names `ARGC' and `ARGV', as well the convention of indexing
  562.      the array from 0 to `ARGC - 1', are derived from the C language's
  563.      method of accessing command line arguments.
  564.      Notice that the `awk' program is not entered in `ARGV'.  The other
  565.      special command line options, with their arguments, are also not
  566.      entered.  But variable assignments on the command line *are*
  567.      treated as arguments, and do show up in the `ARGV' array.
  568.      Your program can alter `ARGC' and the elements of `ARGV'.  Each
  569.      time `awk' reaches the end of an input file, it uses the next
  570.      element of `ARGV' as the name of the next input file.  By storing a
  571.      different string there, your program can change which files are
  572.      read.  You can use `"-"' to represent the standard input.  By
  573.      storing additional elements and incrementing `ARGC' you can cause
  574.      additional files to be read.
  575.      If you decrease the value of `ARGC', that eliminates input files
  576.      from the end of the list.  By recording the old value of `ARGC'
  577.      elsewhere, your program can treat the eliminated arguments as
  578.      something other than file names.
  579.      To eliminate a file from the middle of the list, store the null
  580.      string (`""') into `ARGV' in place of the file's name.  As a
  581.      special feature, `awk' ignores file names that have been replaced
  582.      with the null string.
  583. `ARGIND'
  584.      The index in `ARGV' of the current file being processed.  Every
  585.      time `gawk' opens a new data file for processing, it sets `ARGIND'
  586.      to the index in `ARGV' of the file name.  Thus, the condition
  587.      `FILENAME == ARGV[ARGIND]' is always true.
  588.      This variable is useful in file processing; it allows you to tell
  589.      how far along you are in the list of data files, and to
  590.      distinguish between multiple successive instances of the same
  591.      filename on the command line.
  592.      While you can change the value of `ARGIND' within your `awk'
  593.      program, `gawk' will automatically set it to a new value when the
  594.      next file is opened.
  595.      This variable is a `gawk' extension; in other `awk' implementations
  596.      it is not special.
  597. `ENVIRON'
  598.      This is an array that contains the values of the environment.  The
  599.      array indices are the environment variable names; the values are
  600.      the values of the particular environment variables.  For example,
  601.      `ENVIRON["HOME"]' might be `/u/close'.  Changing this array does
  602.      not affect the environment passed on to any programs that `awk'
  603.      may spawn via redirection or the `system' function.  (In a future
  604.      version of `gawk', it may do so.)
  605.      Some operating systems may not have environment variables.  On
  606.      such systems, the array `ENVIRON' is empty.
  607. `ERRNO'
  608.      If a system error occurs either doing a redirection for `getline',
  609.      during a read for `getline', or during a `close' operation, then
  610.      `ERRNO' will contain a string describing the error.
  611.      This variable is a `gawk' extension; in other `awk' implementations
  612.      it is not special.
  613. `FILENAME'
  614.      This is the name of the file that `awk' is currently reading.  If
  615.      `awk' is reading from the standard input (in other words, there
  616.      are no files listed on the command line), `FILENAME' is set to
  617.      `"-"'.  `FILENAME' is changed each time a new file is read (*note
  618.      Reading Input Files: Reading Files.).
  619. `FNR'
  620.      `FNR' is the current record number in the current file.  `FNR' is
  621.      incremented each time a new record is read (*note Explicit Input
  622.      with `getline': Getline.).  It is reinitialized to 0 each time a
  623.      new input file is started.
  624.      `NF' is the number of fields in the current input record.  `NF' is
  625.      set each time a new record is read, when a new field is created,
  626.      or when `$0' changes (*note Examining Fields: Fields.).
  627.      This is the number of input records `awk' has processed since the
  628.      beginning of the program's execution.  (*note How Input is Split
  629.      into Records: Records.).  `NR' is set each time a new record is
  630.      read.
  631. `RLENGTH'
  632.      `RLENGTH' is the length of the substring matched by the `match'
  633.      function (*note Built-in Functions for String Manipulation: String
  634.      Functions.).  `RLENGTH' is set by invoking the `match' function.
  635.      Its value is the length of the matched string, or -1 if no match
  636.      was found.
  637. `RSTART'
  638.      `RSTART' is the start-index in characters of the substring matched
  639.      by the `match' function (*note Built-in Functions for String
  640.      Manipulation: String Functions.).  `RSTART' is set by invoking the
  641.      `match' function.  Its value is the position of the string where
  642.      the matched substring starts, or 0 if no match was found.
  643. File: gawk.info,  Node: Command Line,  Next: Language History,  Prev: Built-in Variables,  Up: Top
  644. Invoking `awk'
  645. **************
  646.    There are two ways to run `awk': with an explicit program, or with
  647. one or more program files.  Here are templates for both of them; items
  648. enclosed in `[...]' in these templates are optional.
  649.    Besides traditional one-letter POSIX-style options, `gawk' also
  650. supports GNU long named options.
  651.      awk [POSIX OR GNU STYLE OPTIONS] -f progfile [`--'] FILE ...
  652.      awk [POSIX OR GNU STYLE OPTIONS] [`--'] 'PROGRAM' FILE ...
  653. * Menu:
  654. * Options::                     Command line options and their meanings.
  655. * Other Arguments::             Input file names and variable assignments.
  656. * AWKPATH Variable::            Searching directories for `awk' programs.
  657. * Obsolete::                    Obsolete Options and/or features.
  658. * Undocumented::                Undocumented Options and Features.
  659. File: gawk.info,  Node: Options,  Next: Other Arguments,  Prev: Command Line,  Up: Command Line
  660. Command Line Options
  661. ====================
  662.    Options begin with a minus sign, and consist of a single character.
  663. GNU style long named options consist of two minus signs and a keyword
  664. that can be abbreviated if the abbreviation allows the option to be
  665. uniquely identified.  If the option takes an argument, then the keyword
  666. is immediately followed by an equals sign (`=') and the argument's
  667. value.  For brevity, the discussion below only refers to the
  668. traditional short options; however the long and short options are
  669. interchangeable in all contexts.
  670.    Each long named option for `gawk' has a corresponding POSIX-style
  671. option.  The options and their meanings are as follows:
  672. `-F FS'
  673. `--field-separator=FS'
  674.      Sets the `FS' variable to FS (*note Specifying how Fields are
  675.      Separated: Field Separators.).
  676. `-f SOURCE-FILE'
  677. `--file=SOURCE-FILE'
  678.      Indicates that the `awk' program is to be found in SOURCE-FILE
  679.      instead of in the first non-option argument.
  680. `-v VAR=VAL'
  681. `--assign=VAR=VAL'
  682.      Sets the variable VAR to the value VAL *before* execution of the
  683.      program begins.  Such variable values are available inside the
  684.      `BEGIN' rule (see below for a fuller explanation).
  685.      The `-v' option can only set one variable, but you can use it more
  686.      than once, setting another variable each time, like this:
  687.      `-v foo=1 -v bar=2'.
  688. `-W GAWK-OPT'
  689.      Following the POSIX standard, options that are implementation
  690.      specific are supplied as arguments to the `-W' option.  With
  691.      `gawk', these arguments may be separated by commas, or quoted and
  692.      separated by whitespace.  Case is ignored when processing these
  693.      options.  These options also have corresponding GNU style long
  694.      named options.  The following `gawk'-specific options are
  695.      available:
  696.     `-W compat'
  697.     `--compat'
  698.           Specifies "compatibility mode", in which the GNU extensions in
  699.           `gawk' are disabled, so that `gawk' behaves just like Unix
  700.           `awk'.  *Note Extensions in `gawk' not in POSIX `awk':
  701.           POSIX/GNU, which summarizes the extensions.  Also see *Note
  702.           Downward Compatibility and Debugging: Compatibility Mode.
  703.     `-W copyleft'
  704.     `-W copyright'
  705.     `--copyleft'
  706.     `--copyright'
  707.           Print the short version of the General Public License.  This
  708.           option may disappear in a future version of `gawk'.
  709.     `-W help'
  710.     `-W usage'
  711.     `--help'
  712.     `--usage'
  713.           Print a "usage" message summarizing the short and long style
  714.           options that `gawk' accepts, and then exit.
  715.     `-W lint'
  716.     `--lint'
  717.           Provide warnings about constructs that are dubious or
  718.           non-portable to other `awk' implementations.  Some warnings
  719.           are issued when `gawk' first reads your program.  Others are
  720.           issued at run-time, as your program executes.
  721.     `-W posix'
  722.     `--posix'
  723.           Operate in strict POSIX mode.  This disables all `gawk'
  724.           extensions (just like `-W compat'), and adds the following
  725.           additional restrictions:
  726.              * `\x' escape sequences are not recognized (*note Constant
  727.                Expressions: Constants.).
  728.              * The synonym `func' for the keyword `function' is not
  729.                recognized (*note Syntax of Function Definitions:
  730.                Definition Syntax.).
  731.              * The operators `**' and `**=' cannot be used in place of
  732.                `^' and `^=' (*note Arithmetic Operators: Arithmetic
  733.                Ops., and also *note Assignment Expressions: Assignment
  734.                Ops.).
  735.              * Specifying `-Ft' on the command line does not set the
  736.                value of `FS' to be a single tab character (*note
  737.                Specifying how Fields are Separated: Field Separators.).
  738.           Although you can supply both `-W compat' and `-W posix' on the
  739.           command line, `-W posix' will take precedence.
  740.     `-W source=PROGRAM-TEXT'
  741.     `--source=PROGRAM-TEXT'
  742.           Program source code is taken from the PROGRAM-TEXT.  This
  743.           option allows you to mix `awk' source code in files with
  744.           program source code that you would enter on the command line.
  745.           This is particularly useful when you have library functions
  746.           that you wish to use from your command line programs (*note
  747.           The `AWKPATH' Environment Variable: AWKPATH Variable.).
  748.     `-W version'
  749.     `--version'
  750.           Prints version information for this particular copy of `gawk'.
  751.           This is so you can determine if your copy of `gawk' is up to
  752.           date with respect to whatever the Free Software Foundation is
  753.           currently distributing.  This option may disappear in a
  754.           future version of `gawk'.
  755.      Signals the end of the command line options.  The following
  756.      arguments are not treated as options even if they begin with `-'.
  757.      This interpretation of `--' follows the POSIX argument parsing
  758.      conventions.
  759.      This is useful if you have file names that start with `-', or in
  760.      shell scripts, if you have file names that will be specified by
  761.      the user which could start with `-'.
  762.    Any other options are flagged as invalid with a warning message, but
  763. are otherwise ignored.
  764.    In compatibility mode, as a special case, if the value of FS supplied
  765. to the `-F' option is `t', then `FS' is set to the tab character
  766. (`"\t"').  This is only true for `-W compat', and not for `-W posix'
  767. (*note Specifying how Fields are Separated: Field Separators.).
  768.    If the `-f' option is *not* used, then the first non-option command
  769. line argument is expected to be the program text.
  770.    The `-f' option may be used more than once on the command line.  If
  771. it is, `awk' reads its program source from all of the named files, as
  772. if they had been concatenated together into one big file.  This is
  773. useful for creating libraries of `awk' functions.  Useful functions can
  774. be written once, and then retrieved from a standard place, instead of
  775. having to be included into each individual program.  You can still type
  776. in a program at the terminal and use library functions, by specifying
  777. `-f /dev/tty'.  `awk' will read a file from the terminal to use as part
  778. of the `awk' program.  After typing your program, type `Control-d' (the
  779. end-of-file character) to terminate it.  (You may also use `-f -' to
  780. read program source from the standard input, but then you will not be
  781. able to also use the standard input as a source of data.)
  782.    Because it is clumsy using the standard `awk' mechanisms to mix
  783. source file and command line `awk' programs, `gawk' provides the
  784. `--source' option.  This does not require you to pre-empt the standard
  785. input for your source code, and allows you to easily mix command line
  786. and library source code (*note The `AWKPATH' Environment Variable:
  787. AWKPATH Variable.).
  788.    If no `-f' or `--source' option is specified, then `gawk' will use
  789. the first non-option command line argument as the text of the program
  790. source code.
  791. File: gawk.info,  Node: Other Arguments,  Next: AWKPATH Variable,  Prev: Options,  Up: Command Line
  792. Other Command Line Arguments
  793. ============================
  794.    Any additional arguments on the command line are normally treated as
  795. input files to be processed in the order specified.  However, an
  796. argument that has the form `VAR=VALUE', means to assign the value VALUE
  797. to the variable VAR--it does not specify a file at all.
  798.    All these arguments are made available to your `awk' program in the
  799. `ARGV' array (*note Built-in Variables::.).  Command line options and
  800. the program text (if present) are omitted from the `ARGV' array.  All
  801. other arguments, including variable assignments, are included.
  802.    The distinction between file name arguments and variable-assignment
  803. arguments is made when `awk' is about to open the next input file.  At
  804. that point in execution, it checks the "file name" to see whether it is
  805. really a variable assignment; if so, `awk' sets the variable instead of
  806. reading a file.
  807.    Therefore, the variables actually receive the specified values after
  808. all previously specified files have been read.  In particular, the
  809. values of variables assigned in this fashion are *not* available inside
  810. a `BEGIN' rule (*note `BEGIN' and `END' Special Patterns: BEGIN/END.),
  811. since such rules are run before `awk' begins scanning the argument list.
  812. The values given on the command line are processed for escape sequences
  813. (*note Constant Expressions: Constants.).
  814.    In some earlier implementations of `awk', when a variable assignment
  815. occurred before any file names, the assignment would happen *before*
  816. the `BEGIN' rule was executed.  Some applications came to depend upon
  817. this "feature."  When `awk' was changed to be more consistent, the `-v'
  818. option was added to accommodate applications that depended upon this
  819. old behavior.
  820.    The variable assignment feature is most useful for assigning to
  821. variables such as `RS', `OFS', and `ORS', which control input and
  822. output formats, before scanning the data files.  It is also useful for
  823. controlling state if multiple passes are needed over a data file.  For
  824. example:
  825.      awk 'pass == 1  { PASS 1 STUFF }
  826.           pass == 2  { PASS 2 STUFF }' pass=1 datafile pass=2 datafile
  827.    Given the variable assignment feature, the `-F' option is not
  828. strictly necessary.  It remains for historical compatibility.
  829. File: gawk.info,  Node: AWKPATH Variable,  Next: Obsolete,  Prev: Other Arguments,  Up: Command Line
  830. The `AWKPATH' Environment Variable
  831. ==================================
  832.    The previous section described how `awk' program files can be named
  833. on the command line with the `-f' option.  In some `awk'
  834. implementations, you must supply a precise path name for each program
  835. file, unless the file is in the current directory.
  836.    But in `gawk', if the file name supplied in the `-f' option does not
  837. contain a `/', then `gawk' searches a list of directories (called the
  838. "search path"), one by one, looking for a file with the specified name.
  839.    The search path is actually a string consisting of directory names
  840. separated by colons.  `gawk' gets its search path from the `AWKPATH'
  841. environment variable.  If that variable does not exist, `gawk' uses the
  842. default path, which is `.:/local/lib/awk:/ade/lib/awk'.  (Programs
  843. written by system administrators should use an `AWKPATH' variable that
  844. does not include the current directory, `.'.)
  845.    The search path feature is particularly useful for building up
  846. libraries of useful `awk' functions.  The library files can be placed
  847. in a standard directory that is in the default path, and then specified
  848. on the command line with a short file name.  Otherwise, the full file
  849. name would have to be typed for each file.
  850.    By combining the `--source' and `-f' options, your command line
  851. `awk' programs can use facilities in `awk' library files.
  852.    Path searching is not done if `gawk' is in compatibility mode.  This
  853. is true for both `-W compat' and `-W posix'.  *Note Command Line
  854. Options: Options.
  855.    *Note:* if you want files in the current directory to be found, you
  856. must include the current directory in the path, either by writing `.'
  857. as an entry in the path, or by writing a null entry in the path.  (A
  858. null entry is indicated by starting or ending the path with a colon, or
  859. by placing two colons next to each other (`::').)  If the current
  860. directory is not included in the path, then files cannot be found in
  861. the current directory.  This path search mechanism is identical to the
  862. shell's.
  863. File: gawk.info,  Node: Obsolete,  Next: Undocumented,  Prev: AWKPATH Variable,  Up: Command Line
  864. Obsolete Options and/or Features
  865. ================================
  866.    This section describes features and/or command line options from the
  867. previous release of `gawk' that are either not available in the current
  868. version, or that are still supported but deprecated (meaning that they
  869. will *not* be in the next release).
  870.    For version 2.15 of `gawk', the following command line options from
  871. version 2.11.1 are no longer recognized.
  872.      Use `-W compat' instead.
  873.      Use `-W version' instead.
  874.      Use `-W copyright' instead.
  875.      These options produce an "unrecognized option" error message but
  876.      have no effect on the execution of `gawk'.  The POSIX standard now
  877.      specifies traditional `awk' regular expressions for the `awk'
  878.      utility.
  879.    The public-domain version of `strftime' that is distributed with
  880. `gawk' changed for the 2.14 release.  The `%V' conversion specifier
  881. that used to generate the date in VMS format was changed to `%v'.  This
  882. is because the POSIX standard for the `date' utility now specifies a
  883. `%V' conversion specifier.  *Note Functions for Dealing with Time
  884. Stamps: Time Functions, for details.
  885. File: gawk.info,  Node: Undocumented,  Prev: Obsolete,  Up: Command Line
  886. Undocumented Options and Features
  887. =================================
  888.    This section intentionally left blank.
  889. File: gawk.info,  Node: Language History,  Next: Installation,  Prev: Command Line,  Up: Top
  890. The Evolution of the `awk' Language
  891. ***********************************
  892.    This manual describes the GNU implementation of `awk', which is
  893. patterned after the POSIX specification.  Many `awk' users are only
  894. familiar with the original `awk' implementation in Version 7 Unix,
  895. which is also the basis for the version in Berkeley Unix (through
  896. 4.3-Reno).  This chapter briefly describes the evolution of the `awk'
  897. language.
  898. * Menu:
  899. * V7/S5R3.1::                   The major changes between V7 and
  900.                                 System V Release 3.1.
  901. * S5R4::                        Minor changes between System V
  902.                                 Releases 3.1 and 4.
  903. * POSIX::                       New features from the POSIX standard.
  904. * POSIX/GNU::                   The extensions in `gawk'
  905.                                 not in POSIX `awk'.
  906.