home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / gawk-2.15.6-bin.lha / info / gawk.info-5 (.txt) < prev    next >
GNU Info File  |  1996-10-12  |  49KB  |  959 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: For Statement,  Next: Break Statement,  Prev: Do Statement,  Up: Statements
  21. The `for' Statement
  22. ===================
  23.    The `for' statement makes it more convenient to count iterations of a
  24. loop.  The general form of the `for' statement looks like this:
  25.      for (INITIALIZATION; CONDITION; INCREMENT)
  26.        BODY
  27. This statement starts by executing INITIALIZATION.  Then, as long as
  28. CONDITION is true, it repeatedly executes BODY and then INCREMENT.
  29. Typically INITIALIZATION sets a variable to either zero or one,
  30. INCREMENT adds 1 to it, and CONDITION compares it against the desired
  31. number of iterations.
  32.    Here is an example of a `for' statement:
  33.      awk '{ for (i = 1; i <= 3; i++)
  34.                print $i
  35.      }'
  36. This prints the first three fields of each input record, one field per
  37. line.
  38.    In the `for' statement, BODY stands for any statement, but
  39. INITIALIZATION, CONDITION and INCREMENT are just expressions.  You
  40. cannot set more than one variable in the INITIALIZATION part unless you
  41. use a multiple assignment statement such as `x = y = 0', which is
  42. possible only if all the initial values are equal.  (But you can
  43. initialize additional variables by writing their assignments as
  44. separate statements preceding the `for' loop.)
  45.    The same is true of the INCREMENT part; to increment additional
  46. variables, you must write separate statements at the end of the loop.
  47. The C compound expression, using C's comma operator, would be useful in
  48. this context, but it is not supported in `awk'.
  49.    Most often, INCREMENT is an increment expression, as in the example
  50. above.  But this is not required; it can be any expression whatever.
  51. For example, this statement prints all the powers of 2 between 1 and
  52.      for (i = 1; i <= 100; i *= 2)
  53.        print i
  54.    Any of the three expressions in the parentheses following the `for'
  55. may be omitted if there is nothing to be done there.  Thus,
  56. `for (;x > 0;)' is equivalent to `while (x > 0)'.  If the CONDITION is
  57. omitted, it is treated as TRUE, effectively yielding an "infinite loop"
  58. (i.e., a loop that will never terminate).
  59.    In most cases, a `for' loop is an abbreviation for a `while' loop,
  60. as shown here:
  61.      INITIALIZATION
  62.      while (CONDITION) {
  63.        BODY
  64.        INCREMENT
  65.      }
  66. The only exception is when the `continue' statement (*note The
  67. `continue' Statement: Continue Statement.) is used inside the loop;
  68. changing a `for' statement to a `while' statement in this way can
  69. change the effect of the `continue' statement inside the loop.
  70.    There is an alternate version of the `for' loop, for iterating over
  71. all the indices of an array:
  72.      for (i in array)
  73.          DO SOMETHING WITH array[i]
  74. *Note Arrays in `awk': Arrays, for more information on this version of
  75. the `for' loop.
  76.    The `awk' language has a `for' statement in addition to a `while'
  77. statement because often a `for' loop is both less work to type and more
  78. natural to think of.  Counting the number of iterations is very common
  79. in loops.  It can be easier to think of this counting as part of
  80. looping rather than as something to do inside the loop.
  81.    The next section has more complicated examples of `for' loops.
  82. File: gawk.info,  Node: Break Statement,  Next: Continue Statement,  Prev: For Statement,  Up: Statements
  83. The `break' Statement
  84. =====================
  85.    The `break' statement jumps out of the innermost `for', `while', or
  86. `do'-`while' loop that encloses it.  The following example finds the
  87. smallest divisor of any integer, and also identifies prime numbers:
  88.      awk '# find smallest divisor of num
  89.           { num = $1
  90.             for (div = 2; div*div <= num; div++)
  91.               if (num % div == 0)
  92.                 break
  93.             if (num % div == 0)
  94.               printf "Smallest divisor of %d is %d\n", num, div
  95.             else
  96.               printf "%d is prime\n", num  }'
  97.    When the remainder is zero in the first `if' statement, `awk'
  98. immediately "breaks out" of the containing `for' loop.  This means that
  99. `awk' proceeds immediately to the statement following the loop and
  100. continues processing.  (This is very different from the `exit'
  101. statement which stops the entire `awk' program.  *Note The `exit'
  102. Statement: Exit Statement.)
  103.    Here is another program equivalent to the previous one.  It
  104. illustrates how the CONDITION of a `for' or `while' could just as well
  105. be replaced with a `break' inside an `if':
  106.      awk '# find smallest divisor of num
  107.           { num = $1
  108.             for (div = 2; ; div++) {
  109.               if (num % div == 0) {
  110.                 printf "Smallest divisor of %d is %d\n", num, div
  111.                 break
  112.               }
  113.               if (div*div > num) {
  114.                 printf "%d is prime\n", num
  115.                 break
  116.               }
  117.             }
  118.      }'
  119. File: gawk.info,  Node: Continue Statement,  Next: Next Statement,  Prev: Break Statement,  Up: Statements
  120. The `continue' Statement
  121. ========================
  122.    The `continue' statement, like `break', is used only inside `for',
  123. `while', and `do'-`while' loops.  It skips over the rest of the loop
  124. body, causing the next cycle around the loop to begin immediately.
  125. Contrast this with `break', which jumps out of the loop altogether.
  126. Here is an example:
  127.      # print names that don't contain the string "ignore"
  128.      
  129.      # first, save the text of each line
  130.      { names[NR] = $0 }
  131.      
  132.      # print what we're interested in
  133.      END {
  134.         for (x in names) {
  135.             if (names[x] ~ /ignore/)
  136.                 continue
  137.             print names[x]
  138.         }
  139.      }
  140.    If one of the input records contains the string `ignore', this
  141. example skips the print statement for that record, and continues back to
  142. the first statement in the loop.
  143.    This is not a practical example of `continue', since it would be
  144. just as easy to write the loop like this:
  145.      for (x in names)
  146.        if (names[x] !~ /ignore/)
  147.          print names[x]
  148.    The `continue' statement in a `for' loop directs `awk' to skip the
  149. rest of the body of the loop, and resume execution with the
  150. increment-expression of the `for' statement.  The following program
  151. illustrates this fact:
  152.      awk 'BEGIN {
  153.           for (x = 0; x <= 20; x++) {
  154.               if (x == 5)
  155.                   continue
  156.               printf ("%d ", x)
  157.           }
  158.           print ""
  159.      }'
  160. This program prints all the numbers from 0 to 20, except for 5, for
  161. which the `printf' is skipped.  Since the increment `x++' is not
  162. skipped, `x' does not remain stuck at 5.  Contrast the `for' loop above
  163. with the `while' loop:
  164.      awk 'BEGIN {
  165.           x = 0
  166.           while (x <= 20) {
  167.               if (x == 5)
  168.                   continue
  169.               printf ("%d ", x)
  170.               x++
  171.           }
  172.           print ""
  173.      }'
  174. This program loops forever once `x' gets to 5.
  175.    As described above, the `continue' statement has no meaning when
  176. used outside the body of a loop.  However, although it was never
  177. documented, historical implementations of `awk' have treated the
  178. `continue' statement outside of a loop as if it were a `next' statement
  179. (*note The `next' Statement: Next Statement.).  By default, `gawk'
  180. silently supports this usage.  However, if `-W posix' has been
  181. specified on the command line (*note Invoking `awk': Command Line.), it
  182. will be treated as an error, since the POSIX standard specifies that
  183. `continue' should only be used inside the body of a loop.
  184. File: gawk.info,  Node: Next Statement,  Next: Next File Statement,  Prev: Continue Statement,  Up: Statements
  185. The `next' Statement
  186. ====================
  187.    The `next' statement forces `awk' to immediately stop processing the
  188. current record and go on to the next record.  This means that no
  189. further rules are executed for the current record.  The rest of the
  190. current rule's action is not executed either.
  191.    Contrast this with the effect of the `getline' function (*note
  192. Explicit Input with `getline': Getline.).  That too causes `awk' to
  193. read the next record immediately, but it does not alter the flow of
  194. control in any way.  So the rest of the current action executes with a
  195. new input record.
  196.    At the highest level, `awk' program execution is a loop that reads
  197. an input record and then tests each rule's pattern against it.  If you
  198. think of this loop as a `for' statement whose body contains the rules,
  199. then the `next' statement is analogous to a `continue' statement: it
  200. skips to the end of the body of this implicit loop, and executes the
  201. increment (which reads another record).
  202.    For example, if your `awk' program works only on records with four
  203. fields, and you don't want it to fail when given bad input, you might
  204. use this rule near the beginning of the program:
  205.      NF != 4 {
  206.        printf("line %d skipped: doesn't have 4 fields", FNR) > "/dev/stderr"
  207.        next
  208.      }
  209. so that the following rules will not see the bad record.  The error
  210. message is redirected to the standard error output stream, as error
  211. messages should be.  *Note Standard I/O Streams: Special Files.
  212.    According to the POSIX standard, the behavior is undefined if the
  213. `next' statement is used in a `BEGIN' or `END' rule.  `gawk' will treat
  214. it as a syntax error.
  215.    If the `next' statement causes the end of the input to be reached,
  216. then the code in the `END' rules, if any, will be executed.  *Note
  217. `BEGIN' and `END' Special Patterns: BEGIN/END.
  218. File: gawk.info,  Node: Next File Statement,  Next: Exit Statement,  Prev: Next Statement,  Up: Statements
  219. The `next file' Statement
  220. =========================
  221.    The `next file' statement is similar to the `next' statement.
  222. However, instead of abandoning processing of the current record, the
  223. `next file' statement instructs `awk' to stop processing the current
  224. data file.
  225.    Upon execution of the `next file' statement, `FILENAME' is updated
  226. to the name of the next data file listed on the command line, `FNR' is
  227. reset to 1, and processing starts over with the first rule in the
  228. progam.  *Note Built-in Variables::.
  229.    If the `next file' statement causes the end of the input to be
  230. reached, then the code in the `END' rules, if any, will be executed.
  231. *Note `BEGIN' and `END' Special Patterns: BEGIN/END.
  232.    The `next file' statement is a `gawk' extension; it is not
  233. (currently) available in any other `awk' implementation.  You can
  234. simulate its behavior by creating a library file named `nextfile.awk',
  235. with the following contents.  (This sample program uses user-defined
  236. functions, a feature that has not been presented yet.  *Note
  237. User-defined Functions: User-defined, for more information.)
  238.      # nextfile --- function to skip remaining records in current file
  239.      
  240.      # this should be read in before the "main" awk program
  241.      
  242.      function nextfile() { _abandon_ = FILENAME; next }
  243.      
  244.      _abandon_ == FILENAME && FNR > 1   { next }
  245.      _abandon_ == FILENAME && FNR == 1  { _abandon_ = "" }
  246.    The `nextfile' function simply sets a "private" variable(1) to the
  247. name of the current data file, and then retrieves the next record.
  248. Since this file is read before the main `awk' program, the rules that
  249. follows the function definition will be executed before the rules in
  250. the main program.  The first rule continues to skip records as long as
  251. the name of the input file has not changed, and this is not the first
  252. record in the file.  This rule is sufficient most of the time.  But
  253. what if the *same* data file is named twice in a row on the command
  254. line?  This rule would not process the data file the second time.  The
  255. second rule catches this case: If the data file name is what was being
  256. skipped, but `FNR' is 1, then this is the second time the file is being
  257. processed, and it should not be skipped.
  258.    The `next file' statement would be useful if you have many data
  259. files to process, and due to the nature of the data, you expect that you
  260. would not want to process every record in the file.  In order to move
  261. on to the next data file, you would have to continue scanning the
  262. unwanted records (as described above).  The `next file' statement
  263. accomplishes this much more efficiently.
  264.    ---------- Footnotes ----------
  265.    (1)  Since all variables in `awk' are global, this program uses the
  266. common practice of prefixing the variable name with an underscore.  In
  267. fact, it also suffixes the variable name with an underscore, as extra
  268. insurance against using a variable name that might be used in some
  269. other library file.
  270. File: gawk.info,  Node: Exit Statement,  Prev: Next File Statement,  Up: Statements
  271. The `exit' Statement
  272. ====================
  273.    The `exit' statement causes `awk' to immediately stop executing the
  274. current rule and to stop processing input; any remaining input is
  275. ignored.
  276.    If an `exit' statement is executed from a `BEGIN' rule the program
  277. stops processing everything immediately.  No input records are read.
  278. However, if an `END' rule is present, it is executed (*note `BEGIN' and
  279. `END' Special Patterns: BEGIN/END.).
  280.    If `exit' is used as part of an `END' rule, it causes the program to
  281. stop immediately.
  282.    An `exit' statement that is part of an ordinary rule (that is, not
  283. part of a `BEGIN' or `END' rule) stops the execution of any further
  284. automatic rules, but the `END' rule is executed if there is one.  If
  285. you do not want the `END' rule to do its job in this case, you can set
  286. a variable to nonzero before the `exit' statement, and check that
  287. variable in the `END' rule.
  288.    If an argument is supplied to `exit', its value is used as the exit
  289. status code for the `awk' process.  If no argument is supplied, `exit'
  290. returns status zero (success).
  291.    For example, let's say you've discovered an error condition you
  292. really don't know how to handle.  Conventionally, programs report this
  293. by exiting with a nonzero status.  Your `awk' program can do this using
  294. an `exit' statement with a nonzero argument.  Here's an example of this:
  295.      BEGIN {
  296.             if (("date" | getline date_now) < 0) {
  297.               print "Can't get system date" > "/dev/stderr"
  298.               exit 4
  299.             }
  300.      }
  301. File: gawk.info,  Node: Arrays,  Next: Built-in,  Prev: Statements,  Up: Top
  302. Arrays in `awk'
  303. ***************
  304.    An "array" is a table of values, called "elements".  The elements of
  305. an array are distinguished by their indices.  "Indices" may be either
  306. numbers or strings.  Each array has a name, which looks like a variable
  307. name, but must not be in use as a variable name in the same `awk'
  308. program.
  309. * Menu:
  310. * Array Intro::                 Introduction to Arrays
  311. * Reference to Elements::       How to examine one element of an array.
  312. * Assigning Elements::          How to change an element of an array.
  313. * Array Example::               Basic Example of an Array
  314. * Scanning an Array::           A variation of the `for' statement.
  315.                                 It loops through the indices of
  316.                                 an array's existing elements.
  317. * Delete::                      The `delete' statement removes
  318.                                 an element from an array.
  319. * Numeric Array Subscripts::    How to use numbers as subscripts in `awk'.
  320. * Multi-dimensional::           Emulating multi-dimensional arrays in `awk'.
  321. * Multi-scanning::              Scanning multi-dimensional arrays.
  322. File: gawk.info,  Node: Array Intro,  Next: Reference to Elements,  Prev: Arrays,  Up: Arrays
  323. Introduction to Arrays
  324. ======================
  325.    The `awk' language has one-dimensional "arrays" for storing groups
  326. of related strings or numbers.
  327.    Every `awk' array must have a name.  Array names have the same
  328. syntax as variable names; any valid variable name would also be a valid
  329. array name.  But you cannot use one name in both ways (as an array and
  330. as a variable) in one `awk' program.
  331.    Arrays in `awk' superficially resemble arrays in other programming
  332. languages; but there are fundamental differences.  In `awk', you don't
  333. need to specify the size of an array before you start to use it.
  334. Additionally, any number or string in `awk' may be used as an array
  335. index.
  336.    In most other languages, you have to "declare" an array and specify
  337. how many elements or components it contains.  In such languages, the
  338. declaration causes a contiguous block of memory to be allocated for that
  339. many elements.  An index in the array must be a positive integer; for
  340. example, the index 0 specifies the first element in the array, which is
  341. actually stored at the beginning of the block of memory.  Index 1
  342. specifies the second element, which is stored in memory right after the
  343. first element, and so on.  It is impossible to add more elements to the
  344. array, because it has room for only as many elements as you declared.
  345.    A contiguous array of four elements might look like this,
  346. conceptually, if the element values are `8', `"foo"', `""' and `30':
  347.      +---------+---------+--------+---------+
  348.      |    8    |  "foo"  |   ""   |    30   |    value
  349.      +---------+---------+--------+---------+
  350.           0         1         2         3        index
  351. Only the values are stored; the indices are implicit from the order of
  352. the values.  `8' is the value at index 0, because `8' appears in the
  353. position with 0 elements before it.
  354.    Arrays in `awk' are different: they are "associative".  This means
  355. that each array is a collection of pairs: an index, and its
  356. corresponding array element value:
  357.      Element 4     Value 30
  358.      Element 2     Value "foo"
  359.      Element 1     Value 8
  360.      Element 3     Value ""
  361. We have shown the pairs in jumbled order because their order is
  362. irrelevant.
  363.    One advantage of an associative array is that new pairs can be added
  364. at any time.  For example, suppose we add to the above array a tenth
  365. element whose value is `"number ten"'.  The result is this:
  366.      Element 10    Value "number ten"
  367.      Element 4     Value 30
  368.      Element 2     Value "foo"
  369.      Element 1     Value 8
  370.      Element 3     Value ""
  371. Now the array is "sparse" (i.e., some indices are missing): it has
  372. elements 1-4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.
  373.    Another consequence of associative arrays is that the indices don't
  374. have to be positive integers.  Any number, or even a string, can be an
  375. index.  For example, here is an array which translates words from
  376. English into French:
  377.      Element "dog" Value "chien"
  378.      Element "cat" Value "chat"
  379.      Element "one" Value "un"
  380.      Element 1     Value "un"
  381. Here we decided to translate the number 1 in both spelled-out and
  382. numeric form--thus illustrating that a single array can have both
  383. numbers and strings as indices.
  384.    When `awk' creates an array for you, e.g., with the `split' built-in
  385. function, that array's indices are consecutive integers starting at 1.
  386. (*Note Built-in Functions for String Manipulation: String Functions.)
  387. File: gawk.info,  Node: Reference to Elements,  Next: Assigning Elements,  Prev: Array Intro,  Up: Arrays
  388. Referring to an Array Element
  389. =============================
  390.    The principal way of using an array is to refer to one of its
  391. elements.  An array reference is an expression which looks like this:
  392.      ARRAY[INDEX]
  393. Here, ARRAY is the name of an array.  The expression INDEX is the index
  394. of the element of the array that you want.
  395.    The value of the array reference is the current value of that array
  396. element.  For example, `foo[4.3]' is an expression for the element of
  397. array `foo' at index 4.3.
  398.    If you refer to an array element that has no recorded value, the
  399. value of the reference is `""', the null string.  This includes elements
  400. to which you have not assigned any value, and elements that have been
  401. deleted (*note The `delete' Statement: Delete.).  Such a reference
  402. automatically creates that array element, with the null string as its
  403. value.  (In some cases, this is unfortunate, because it might waste
  404. memory inside `awk').
  405.    You can find out if an element exists in an array at a certain index
  406. with the expression:
  407.      INDEX in ARRAY
  408. This expression tests whether or not the particular index exists,
  409. without the side effect of creating that element if it is not present.
  410. The expression has the value 1 (true) if `ARRAY[INDEX]' exists, and 0
  411. (false) if it does not exist.
  412.    For example, to test whether the array `frequencies' contains the
  413. index `"2"', you could write this statement:
  414.      if ("2" in frequencies) print "Subscript \"2\" is present."
  415.    Note that this is *not* a test of whether or not the array
  416. `frequencies' contains an element whose *value* is `"2"'.  (There is no
  417. way to do that except to scan all the elements.)  Also, this *does not*
  418. create `frequencies["2"]', while the following (incorrect) alternative
  419. would do so:
  420.      if (frequencies["2"] != "") print "Subscript \"2\" is present."
  421. File: gawk.info,  Node: Assigning Elements,  Next: Array Example,  Prev: Reference to Elements,  Up: Arrays
  422. Assigning Array Elements
  423. ========================
  424.    Array elements are lvalues: they can be assigned values just like
  425. `awk' variables:
  426.      ARRAY[SUBSCRIPT] = VALUE
  427. Here ARRAY is the name of your array.  The expression SUBSCRIPT is the
  428. index of the element of the array that you want to assign a value.  The
  429. expression VALUE is the value you are assigning to that element of the
  430. array.
  431. File: gawk.info,  Node: Array Example,  Next: Scanning an Array,  Prev: Assigning Elements,  Up: Arrays
  432. Basic Example of an Array
  433. =========================
  434.    The following program takes a list of lines, each beginning with a
  435. line number, and prints them out in order of line number.  The line
  436. numbers are not in order, however, when they are first read:  they are
  437. scrambled.  This program sorts the lines by making an array using the
  438. line numbers as subscripts.  It then prints out the lines in sorted
  439. order of their numbers.  It is a very simple program, and gets confused
  440. if it encounters repeated numbers, gaps, or lines that don't begin with
  441. a number.
  442.      {
  443.        if ($1 > max)
  444.          max = $1
  445.        arr[$1] = $0
  446.      }
  447.      
  448.      END {
  449.        for (x = 1; x <= max; x++)
  450.          print arr[x]
  451.      }
  452.    The first rule keeps track of the largest line number seen so far;
  453. it also stores each line into the array `arr', at an index that is the
  454. line's number.
  455.    The second rule runs after all the input has been read, to print out
  456. all the lines.
  457.    When this program is run with the following input:
  458.      5  I am the Five man
  459.      2  Who are you?  The new number two!
  460.      4  . . . And four on the floor
  461.      1  Who is number one?
  462.      3  I three you.
  463. its output is this:
  464.      1  Who is number one?
  465.      2  Who are you?  The new number two!
  466.      3  I three you.
  467.      4  . . . And four on the floor
  468.      5  I am the Five man
  469.    If a line number is repeated, the last line with a given number
  470. overrides the others.
  471.    Gaps in the line numbers can be handled with an easy improvement to
  472. the program's `END' rule:
  473.      END {
  474.        for (x = 1; x <= max; x++)
  475.          if (x in arr)
  476.            print arr[x]
  477.      }
  478. File: gawk.info,  Node: Scanning an Array,  Next: Delete,  Prev: Array Example,  Up: Arrays
  479. Scanning all Elements of an Array
  480. =================================
  481.    In programs that use arrays, often you need a loop that executes
  482. once for each element of an array.  In other languages, where arrays are
  483. contiguous and indices are limited to positive integers, this is easy:
  484. the largest index is one less than the length of the array, and you can
  485. find all the valid indices by counting from zero up to that value.  This
  486. technique won't do the job in `awk', since any number or string may be
  487. an array index.  So `awk' has a special kind of `for' statement for
  488. scanning an array:
  489.      for (VAR in ARRAY)
  490.        BODY
  491. This loop executes BODY once for each different value that your program
  492. has previously used as an index in ARRAY, with the variable VAR set to
  493. that index.
  494.    Here is a program that uses this form of the `for' statement.  The
  495. first rule scans the input records and notes which words appear (at
  496. least once) in the input, by storing a 1 into the array `used' with the
  497. word as index.  The second rule scans the elements of `used' to find
  498. all the distinct words that appear in the input.  It prints each word
  499. that is more than 10 characters long, and also prints the number of
  500. such words.  *Note Built-in Functions: Built-in, for more information
  501. on the built-in function `length'.
  502.      # Record a 1 for each word that is used at least once.
  503.      {
  504.        for (i = 1; i <= NF; i++)
  505.          used[$i] = 1
  506.      }
  507.      
  508.      # Find number of distinct words more than 10 characters long.
  509.      END {
  510.        for (x in used)
  511.          if (length(x) > 10) {
  512.            ++num_long_words
  513.            print x
  514.        }
  515.        print num_long_words, "words longer than 10 characters"
  516.      }
  517. *Note Sample Program::, for a more detailed example of this type.
  518.    The order in which elements of the array are accessed by this
  519. statement is determined by the internal arrangement of the array
  520. elements within `awk' and cannot be controlled or changed.  This can
  521. lead to problems if new elements are added to ARRAY by statements in
  522. BODY; you cannot predict whether or not the `for' loop will reach them.
  523. Similarly, changing VAR inside the loop can produce strange results.
  524. It is best to avoid such things.
  525. File: gawk.info,  Node: Delete,  Next: Numeric Array Subscripts,  Prev: Scanning an Array,  Up: Arrays
  526. The `delete' Statement
  527. ======================
  528.    You can remove an individual element of an array using the `delete'
  529. statement:
  530.      delete ARRAY[INDEX]
  531.    You can not refer to an array element after it has been deleted; it
  532. is as if you had never referred to it and had never given it any value.
  533. You can no longer obtain any value the element once had.
  534.    Here is an example of deleting elements in an array:
  535.      for (i in frequencies)
  536.        delete frequencies[i]
  537. This example removes all the elements from the array `frequencies'.
  538.    If you delete an element, a subsequent `for' statement to scan the
  539. array will not report that element, and the `in' operator to check for
  540. the presence of that element will return 0:
  541.      delete foo[4]
  542.      if (4 in foo)
  543.        print "This will never be printed"
  544.    It is not an error to delete an element which does not exist.
  545. File: gawk.info,  Node: Numeric Array Subscripts,  Next: Multi-dimensional,  Prev: Delete,  Up: Arrays
  546. Using Numbers to Subscript Arrays
  547. =================================
  548.    An important aspect of arrays to remember is that array subscripts
  549. are *always* strings.  If you use a numeric value as a subscript, it
  550. will be converted to a string value before it is used for subscripting
  551. (*note Conversion of Strings and Numbers: Conversion.).
  552.    This means that the value of the `CONVFMT' can potentially affect
  553. how your program accesses elements of an array.  For example:
  554.      a = b = 12.153
  555.      data[a] = 1
  556.      CONVFMT = "%2.2f"
  557.      if (b in data)
  558.          printf "%s is in data", b
  559.      else
  560.          printf "%s is not in data", b
  561. should print `12.15 is not in data'.  The first statement gives both
  562. `a' and `b' the same numeric value.  Assigning to `data[a]' first gives
  563. `a' the string value `"12.153"' (using the default conversion value of
  564. `CONVFMT', `"%.6g"'), and then assigns 1 to `data["12.153"]'.  The
  565. program then changes the value of `CONVFMT'.  The test `(b in data)'
  566. forces `b' to be converted to a string, this time `"12.15"', since the
  567. value of `CONVFMT' only allows two significant digits.  This test fails,
  568. since `"12.15"' is a different string from `"12.153"'.
  569.    According to the rules for conversions (*note Conversion of Strings
  570. and Numbers: Conversion.), integer values are always converted to
  571. strings as integers, no matter what the value of `CONVFMT' may happen
  572. to be.  So the usual case of
  573.      for (i = 1; i <= maxsub; i++)
  574.          do something with array[i]
  575. will work, no matter what the value of `CONVFMT'.
  576.    Like many things in `awk', the majority of the time things work as
  577. you would expect them to work.  But it is useful to have a precise
  578. knowledge of the actual rules, since sometimes they can have a subtle
  579. effect on your programs.
  580. File: gawk.info,  Node: Multi-dimensional,  Next: Multi-scanning,  Prev: Numeric Array Subscripts,  Up: Arrays
  581. Multi-dimensional Arrays
  582. ========================
  583.    A multi-dimensional array is an array in which an element is
  584. identified by a sequence of indices, not a single index.  For example, a
  585. two-dimensional array requires two indices.  The usual way (in most
  586. languages, including `awk') to refer to an element of a two-dimensional
  587. array named `grid' is with `grid[X,Y]'.
  588.    Multi-dimensional arrays are supported in `awk' through
  589. concatenation of indices into one string.  What happens is that `awk'
  590. converts the indices into strings (*note Conversion of Strings and
  591. Numbers: Conversion.) and concatenates them together, with a separator
  592. between them.  This creates a single string that describes the values
  593. of the separate indices.  The combined string is used as a single index
  594. into an ordinary, one-dimensional array.  The separator used is the
  595. value of the built-in variable `SUBSEP'.
  596.    For example, suppose we evaluate the expression `foo[5,12]="value"'
  597. when the value of `SUBSEP' is `"@"'.  The numbers 5 and 12 are
  598. converted to strings and concatenated with an `@' between them,
  599. yielding `"5@12"'; thus, the array element `foo["5@12"]' is set to
  600. `"value"'.
  601.    Once the element's value is stored, `awk' has no record of whether
  602. it was stored with a single index or a sequence of indices.  The two
  603. expressions `foo[5,12]' and `foo[5 SUBSEP 12]' always have the same
  604. value.
  605.    The default value of `SUBSEP' is the string `"\034"', which contains
  606. a nonprinting character that is unlikely to appear in an `awk' program
  607. or in the input data.
  608.    The usefulness of choosing an unlikely character comes from the fact
  609. that index values that contain a string matching `SUBSEP' lead to
  610. combined strings that are ambiguous.  Suppose that `SUBSEP' were `"@"';
  611. then `foo["a@b", "c"]' and `foo["a", "b@c"]' would be indistinguishable
  612. because both would actually be stored as `foo["a@b@c"]'.  Because
  613. `SUBSEP' is `"\034"', such confusion can arise only when an index
  614. contains the character with ASCII code 034, which is a rare event.
  615.    You can test whether a particular index-sequence exists in a
  616. "multi-dimensional" array with the same operator `in' used for single
  617. dimensional arrays.  Instead of a single index as the left-hand operand,
  618. write the whole sequence of indices, separated by commas, in
  619. parentheses:
  620.      (SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY
  621.    The following example treats its input as a two-dimensional array of
  622. fields; it rotates this array 90 degrees clockwise and prints the
  623. result.  It assumes that all lines have the same number of elements.
  624.      awk '{
  625.           if (max_nf < NF)
  626.                max_nf = NF
  627.           max_nr = NR
  628.           for (x = 1; x <= NF; x++)
  629.                vector[x, NR] = $x
  630.      }
  631.      
  632.      END {
  633.           for (x = 1; x <= max_nf; x++) {
  634.                for (y = max_nr; y >= 1; --y)
  635.                     printf("%s ", vector[x, y])
  636.                printf("\n")
  637.           }
  638.      }'
  639. When given the input:
  640.      1 2 3 4 5 6
  641.      2 3 4 5 6 1
  642.      3 4 5 6 1 2
  643.      4 5 6 1 2 3
  644. it produces:
  645.      4 3 2 1
  646.      5 4 3 2
  647.      6 5 4 3
  648.      1 6 5 4
  649.      2 1 6 5
  650.      3 2 1 6
  651. File: gawk.info,  Node: Multi-scanning,  Prev: Multi-dimensional,  Up: Arrays
  652. Scanning Multi-dimensional Arrays
  653. =================================
  654.    There is no special `for' statement for scanning a
  655. "multi-dimensional" array; there cannot be one, because in truth there
  656. are no multi-dimensional arrays or elements; there is only a
  657. multi-dimensional *way of accessing* an array.
  658.    However, if your program has an array that is always accessed as
  659. multi-dimensional, you can get the effect of scanning it by combining
  660. the scanning `for' statement (*note Scanning all Elements of an Array:
  661. Scanning an Array.) with the `split' built-in function (*note Built-in
  662. Functions for String Manipulation: String Functions.).  It works like
  663. this:
  664.      for (combined in ARRAY) {
  665.        split(combined, separate, SUBSEP)
  666.        ...
  667.      }
  668. This finds each concatenated, combined index in the array, and splits it
  669. into the individual indices by breaking it apart where the value of
  670. `SUBSEP' appears.  The split-out indices become the elements of the
  671. array `separate'.
  672.    Thus, suppose you have previously stored in `ARRAY[1, "foo"]'; then
  673. an element with index `"1\034foo"' exists in ARRAY.  (Recall that the
  674. default value of `SUBSEP' contains the character with code 034.)
  675. Sooner or later the `for' statement will find that index and do an
  676. iteration with `combined' set to `"1\034foo"'.  Then the `split'
  677. function is called as follows:
  678.      split("1\034foo", separate, "\034")
  679. The result of this is to set `separate[1]' to 1 and `separate[2]' to
  680. `"foo"'.  Presto, the original sequence of separate indices has been
  681. recovered.
  682. File: gawk.info,  Node: Built-in,  Next: User-defined,  Prev: Arrays,  Up: Top
  683. Built-in Functions
  684. ******************
  685.    "Built-in" functions are functions that are always available for
  686. your `awk' program to call.  This chapter defines all the built-in
  687. functions in `awk'; some of them are mentioned in other sections, but
  688. they are summarized here for your convenience.  (You can also define
  689. new functions yourself.  *Note User-defined Functions: User-defined.)
  690. * Menu:
  691. * Calling Built-in::            How to call built-in functions.
  692. * Numeric Functions::           Functions that work with numbers,
  693.                                 including `int', `sin' and `rand'.
  694. * String Functions::            Functions for string manipulation,
  695.                                 such as `split', `match', and `sprintf'.
  696. * I/O Functions::               Functions for files and shell commands.
  697. * Time Functions::              Functions for dealing with time stamps.
  698. File: gawk.info,  Node: Calling Built-in,  Next: Numeric Functions,  Prev: Built-in,  Up: Built-in
  699. Calling Built-in Functions
  700. ==========================
  701.    To call a built-in function, write the name of the function followed
  702. by arguments in parentheses.  For example, `atan2(y + z, 1)' is a call
  703. to the function `atan2', with two arguments.
  704.    Whitespace is ignored between the built-in function name and the
  705. open-parenthesis, but we recommend that you avoid using whitespace
  706. there.  User-defined functions do not permit whitespace in this way, and
  707. you will find it easier to avoid mistakes by following a simple
  708. convention which always works: no whitespace after a function name.
  709.    Each built-in function accepts a certain number of arguments.  In
  710. most cases, any extra arguments given to built-in functions are
  711. ignored.  The defaults for omitted arguments vary from function to
  712. function and are described under the individual functions.
  713.    When a function is called, expressions that create the function's
  714. actual parameters are evaluated completely before the function call is
  715. performed.  For example, in the code fragment:
  716.      i = 4
  717.      j = sqrt(i++)
  718. the variable `i' is set to 5 before `sqrt' is called with a value of 4
  719. for its actual parameter.
  720. File: gawk.info,  Node: Numeric Functions,  Next: String Functions,  Prev: Calling Built-in,  Up: Built-in
  721. Numeric Built-in Functions
  722. ==========================
  723.    Here is a full list of built-in functions that work with numbers:
  724. `int(X)'
  725.      This gives you the integer part of X, truncated toward 0.  This
  726.      produces the nearest integer to X, located between X and 0.
  727.      For example, `int(3)' is 3, `int(3.9)' is 3, `int(-3.9)' is -3,
  728.      and `int(-3)' is -3 as well.
  729. `sqrt(X)'
  730.      This gives you the positive square root of X.  It reports an error
  731.      if X is negative.  Thus, `sqrt(4)' is 2.
  732. `exp(X)'
  733.      This gives you the exponential of X, or reports an error if X is
  734.      out of range.  The range of values X can have depends on your
  735.      machine's floating point representation.
  736. `log(X)'
  737.      This gives you the natural logarithm of X, if X is positive;
  738.      otherwise, it reports an error.
  739. `sin(X)'
  740.      This gives you the sine of X, with X in radians.
  741. `cos(X)'
  742.      This gives you the cosine of X, with X in radians.
  743. `atan2(Y, X)'
  744.      This gives you the arctangent of `Y / X' in radians.
  745. `rand()'
  746.      This gives you a random number.  The values of `rand' are
  747.      uniformly-distributed between 0 and 1.  The value is never 0 and
  748.      never 1.
  749.      Often you want random integers instead.  Here is a user-defined
  750.      function you can use to obtain a random nonnegative integer less
  751.      than N:
  752.           function randint(n) {
  753.                return int(n * rand())
  754.           }
  755.      The multiplication produces a random real number greater than 0
  756.      and less than N.  We then make it an integer (using `int') between
  757.      0 and `N - 1'.
  758.      Here is an example where a similar function is used to produce
  759.      random integers between 1 and N.  Note that this program will
  760.      print a new random number for each input record.
  761.           awk '
  762.           # Function to roll a simulated die.
  763.           function roll(n) { return 1 + int(rand() * n) }
  764.           
  765.           # Roll 3 six-sided dice and print total number of points.
  766.           {
  767.                 printf("%d points\n", roll(6)+roll(6)+roll(6))
  768.           }'
  769.      *Note:* `rand' starts generating numbers from the same point, or
  770.      "seed", each time you run `awk'.  This means that a program will
  771.      produce the same results each time you run it.  The numbers are
  772.      random within one `awk' run, but predictable from run to run.
  773.      This is convenient for debugging, but if you want a program to do
  774.      different things each time it is used, you must change the seed to
  775.      a value that will be different in each run.  To do this, use
  776.      `srand'.
  777. `srand(X)'
  778.      The function `srand' sets the starting point, or "seed", for
  779.      generating random numbers to the value X.
  780.      Each seed value leads to a particular sequence of "random" numbers.
  781.      Thus, if you set the seed to the same value a second time, you
  782.      will get the same sequence of "random" numbers again.
  783.      If you omit the argument X, as in `srand()', then the current date
  784.      and time of day are used for a seed.  This is the way to get random
  785.      numbers that are truly unpredictable.
  786.      The return value of `srand' is the previous seed.  This makes it
  787.      easy to keep track of the seeds for use in consistently reproducing
  788.      sequences of random numbers.
  789. File: gawk.info,  Node: String Functions,  Next: I/O Functions,  Prev: Numeric Functions,  Up: Built-in
  790. Built-in Functions for String Manipulation
  791. ==========================================
  792.    The functions in this section look at or change the text of one or
  793. more strings.
  794. `index(IN, FIND)'
  795.      This searches the string IN for the first occurrence of the string
  796.      FIND, and returns the position in characters where that occurrence
  797.      begins in the string IN.  For example:
  798.           awk 'BEGIN { print index("peanut", "an") }'
  799.      prints `3'.  If FIND is not found, `index' returns 0.  (Remember
  800.      that string indices in `awk' start at 1.)
  801. `length(STRING)'
  802.      This gives you the number of characters in STRING.  If STRING is a
  803.      number, the length of the digit string representing that number is
  804.      returned.  For example, `length("abcde")' is 5.  By contrast,
  805.      `length(15 * 35)' works out to 3.  How?  Well, 15 * 35 = 525, and
  806.      525 is then converted to the string `"525"', which has three
  807.      characters.
  808.      If no argument is supplied, `length' returns the length of `$0'.
  809.      In older versions of `awk', you could call the `length' function
  810.      without any parentheses.  Doing so is marked as "deprecated" in the
  811.      POSIX standard.  This means that while you can do this in your
  812.      programs, it is a feature that can eventually be removed from a
  813.      future version of the standard.  Therefore, for maximal
  814.      portability of your `awk' programs you should always supply the
  815.      parentheses.
  816. `match(STRING, REGEXP)'
  817.      The `match' function searches the string, STRING, for the longest,
  818.      leftmost substring matched by the regular expression, REGEXP.  It
  819.      returns the character position, or "index", of where that
  820.      substring begins (1, if it starts at the beginning of STRING).  If
  821.      no match if found, it returns 0.
  822.      The `match' function sets the built-in variable `RSTART' to the
  823.      index.  It also sets the built-in variable `RLENGTH' to the length
  824.      in characters of the matched substring.  If no match is found,
  825.      `RSTART' is set to 0, and `RLENGTH' to -1.
  826.      For example:
  827.           awk '{
  828.                  if ($1 == "FIND")
  829.                    regex = $2
  830.                  else {
  831.                    where = match($0, regex)
  832.                    if (where)
  833.                      print "Match of", regex, "found at", where, "in", $0
  834.                  }
  835.           }'
  836.      This program looks for lines that match the regular expression
  837.      stored in the variable `regex'.  This regular expression can be
  838.      changed.  If the first word on a line is `FIND', `regex' is
  839.      changed to be the second word on that line.  Therefore, given:
  840.           FIND fo*bar
  841.           My program was a foobar
  842.           But none of it would doobar
  843.           FIND Melvin
  844.           JF+KM
  845.           This line is property of The Reality Engineering Co.
  846.           This file created by Melvin.
  847.      `awk' prints:
  848.           Match of fo*bar found at 18 in My program was a foobar
  849.           Match of Melvin found at 26 in This file created by Melvin.
  850. `split(STRING, ARRAY, FIELDSEP)'
  851.      This divides STRING into pieces separated by FIELDSEP, and stores
  852.      the pieces in ARRAY.  The first piece is stored in `ARRAY[1]', the
  853.      second piece in `ARRAY[2]', and so forth.  The string value of the
  854.      third argument, FIELDSEP, is a regexp describing where to split
  855.      STRING (much as `FS' can be a regexp describing where to split
  856.      input records).  If the FIELDSEP is omitted, the value of `FS' is
  857.      used.  `split' returns the number of elements created.
  858.      The `split' function, then, splits strings into pieces in a manner
  859.      similar to the way input lines are split into fields.  For example:
  860.           split("auto-da-fe", a, "-")
  861.      splits the string `auto-da-fe' into three fields using `-' as the
  862.      separator.  It sets the contents of the array `a' as follows:
  863.           a[1] = "auto"
  864.           a[2] = "da"
  865.           a[3] = "fe"
  866.      The value returned by this call to `split' is 3.
  867.      As with input field-splitting, when the value of FIELDSEP is `"
  868.      "', leading and trailing whitespace is ignored, and the elements
  869.      are separated by runs of whitespace.
  870. `sprintf(FORMAT, EXPRESSION1,...)'
  871.      This returns (without printing) the string that `printf' would
  872.      have printed out with the same arguments (*note Using `printf'
  873.      Statements for Fancier Printing: Printf.).  For example:
  874.           sprintf("pi = %.2f (approx.)", 22/7)
  875.      returns the string `"pi = 3.14 (approx.)"'.
  876. `sub(REGEXP, REPLACEMENT, TARGET)'
  877.      The `sub' function alters the value of TARGET.  It searches this
  878.      value, which should be a string, for the leftmost substring
  879.      matched by the regular expression, REGEXP, extending this match as
  880.      far as possible.  Then the entire string is changed by replacing
  881.      the matched text with REPLACEMENT.  The modified string becomes
  882.      the new value of TARGET.
  883.      This function is peculiar because TARGET is not simply used to
  884.      compute a value, and not just any expression will do: it must be a
  885.      variable, field or array reference, so that `sub' can store a
  886.      modified value there.  If this argument is omitted, then the
  887.      default is to use and alter `$0'.
  888.      For example:
  889.           str = "water, water, everywhere"
  890.           sub(/at/, "ith", str)
  891.      sets `str' to `"wither, water, everywhere"', by replacing the
  892.      leftmost, longest occurrence of `at' with `ith'.
  893.      The `sub' function returns the number of substitutions made (either
  894.      one or zero).
  895.      If the special character `&' appears in REPLACEMENT, it stands for
  896.      the precise substring that was matched by REGEXP.  (If the regexp
  897.      can match more than one string, then this precise substring may
  898.      vary.)  For example:
  899.           awk '{ sub(/candidate/, "& and his wife"); print }'
  900.      changes the first occurrence of `candidate' to `candidate and his
  901.      wife' on each input line.
  902.      Here is another example:
  903.           awk 'BEGIN {
  904.                   str = "daabaaa"
  905.                   sub(/a*/, "c&c", str)
  906.                   print str
  907.           }'
  908.      prints `dcaacbaaa'.  This show how `&' can represent a non-constant
  909.      string, and also illustrates the "leftmost, longest" rule.
  910.      The effect of this special character (`&') can be turned off by
  911.      putting a backslash before it in the string.  As usual, to insert
  912.      one backslash in the string, you must write two backslashes.
  913.      Therefore, write `\\&' in a string constant to include a literal
  914.      `&' in the replacement.  For example, here is how to replace the
  915.      first `|' on each line with an `&':
  916.           awk '{ sub(/\|/, "\\&"); print }'
  917.      *Note:* as mentioned above, the third argument to `sub' must be an
  918.      lvalue.  Some versions of `awk' allow the third argument to be an
  919.      expression which is not an lvalue.  In such a case, `sub' would
  920.      still search for the pattern and return 0 or 1, but the result of
  921.      the substitution (if any) would be thrown away because there is no
  922.      place to put it.  Such versions of `awk' accept expressions like
  923.      this:
  924.           sub(/USA/, "United States", "the USA and Canada")
  925.      But that is considered erroneous in `gawk'.
  926. `gsub(REGEXP, REPLACEMENT, TARGET)'
  927.      This is similar to the `sub' function, except `gsub' replaces
  928.      *all* of the longest, leftmost, *nonoverlapping* matching
  929.      substrings it can find.  The `g' in `gsub' stands for "global,"
  930.      which means replace everywhere.  For example:
  931.           awk '{ gsub(/Britain/, "United Kingdom"); print }'
  932.      replaces all occurrences of the string `Britain' with `United
  933.      Kingdom' for all input records.
  934.      The `gsub' function returns the number of substitutions made.  If
  935.      the variable to be searched and altered, TARGET, is omitted, then
  936.      the entire input record, `$0', is used.
  937.      As in `sub', the characters `&' and `\' are special, and the third
  938.      argument must be an lvalue.
  939. `substr(STRING, START, LENGTH)'
  940.      This returns a LENGTH-character-long substring of STRING, starting
  941.      at character number START.  The first character of a string is
  942.      character number one.  For example, `substr("washington", 5, 3)'
  943.      returns `"ing"'.
  944.      If LENGTH is not present, this function returns the whole suffix of
  945.      STRING that begins at character number START.  For example,
  946.      `substr("washington", 5)' returns `"ington"'.  This is also the
  947.      case if LENGTH is greater than the number of characters remaining
  948.      in the string, counting from character number START.
  949. `tolower(STRING)'
  950.      This returns a copy of STRING, with each upper-case character in
  951.      the string replaced with its corresponding lower-case character.
  952.      Nonalphabetic characters are left unchanged.  For example,
  953.      `tolower("MiXeD cAsE 123")' returns `"mixed case 123"'.
  954. `toupper(STRING)'
  955.      This returns a copy of STRING, with each lower-case character in
  956.      the string replaced with its corresponding upper-case character.
  957.      Nonalphabetic characters are left unchanged.  For example,
  958.      `toupper("MiXeD cAsE 123")' returns `"MIXED CASE 123"'.
  959.