home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / unix / volume22 / gawk2.11 / part04 / gawk.texinfo.05 next >
Encoding:
Text File  |  1990-06-07  |  48.5 KB  |  1,364 lines

  1. If a line number is repeated, the last line with a given number overrides
  2. the others.
  3.  
  4. Gaps in the line numbers can be handled with an easy improvement to the
  5. program's @code{END} rule:
  6.  
  7. @example
  8. END @{
  9.   for (x = 1; x <= max; x++)
  10.     if (x in arr)
  11.       print arr[x]
  12. @}
  13. @end example
  14.  
  15. @node Scanning an Array, Delete, Array Example, Arrays
  16. @section Scanning All Elements of an Array
  17. @cindex @code{for (x in @dots{})}
  18. @cindex arrays, special @code{for} statement
  19. @cindex scanning an array
  20.  
  21. In programs that use arrays, often you need a loop that executes
  22. once for each element of an array.  In other languages, where arrays are
  23. contiguous and indices are limited to positive integers, this is
  24. easy: the largest index is one less than the length of the array, and you can
  25. find all the valid indices by counting from zero up to that value.  This
  26. technique won't do the job in @code{awk}, since any number or string
  27. may be an array index.  So @code{awk} has a special kind of @code{for}
  28. statement for scanning an array:
  29.  
  30. @example
  31. for (@var{var} in @var{array})
  32.   @var{body}
  33. @end example
  34.  
  35. @noindent
  36. This loop executes @var{body} once for each different value that your
  37. program has previously used as an index in @var{array}, with the
  38. variable @var{var} set to that index.@refill
  39.  
  40. Here is a program that uses this form of the @code{for} statement.  The
  41. first rule scans the input records and notes which words appear (at
  42. least once) in the input, by storing a 1 into the array @code{used} with
  43. the word as index.  The second rule scans the elements of @code{used} to
  44. find all the distinct words that appear in the input.  It prints each
  45. word that is more than 10 characters long, and also prints the number of
  46. such words.  @xref{Built-in}, for more information on the built-in
  47. function @code{length}.
  48.  
  49. @example
  50. # Record a 1 for each word that is used at least once.
  51. @{
  52.   for (i = 0; i < NF; i++)
  53.     used[$i] = 1
  54. @}
  55.  
  56. # Find number of distinct words more than 10 characters long.
  57. END @{
  58.   num_long_words = 0
  59.   for (x in used)
  60.     if (length(x) > 10) @{
  61.       ++num_long_words
  62.       print x
  63.   @}
  64.   print num_long_words, "words longer than 10 characters"
  65. @}
  66. @end example
  67.  
  68. @noindent
  69. @xref{Sample Program}, for a more detailed example of this type.
  70.  
  71. The order in which elements of the array are accessed by this statement
  72. is determined by the internal arrangement of the array elements within
  73. @code{awk} and cannot be controlled or changed.  This can lead to
  74. problems if new elements are added to @var{array} by statements in
  75. @var{body}; you cannot predict whether or not the @code{for} loop will
  76. reach them.  Similarly, changing @var{var} inside the loop can produce
  77. strange results.  It is best to avoid such things.@refill
  78.  
  79. @node Delete, Multi-dimensional, Scanning an Array, Arrays
  80. @section The @code{delete} Statement
  81. @cindex @code{delete} statement
  82. @cindex deleting elements of arrays
  83. @cindex removing elements of arrays
  84. @cindex arrays, deleting an element
  85.  
  86. You can remove an individual element of an array using the @code{delete}
  87. statement:
  88.  
  89. @example
  90. delete @var{array}[@var{index}]
  91. @end example
  92.  
  93. When an array element is deleted, it is as if you had never referred to it
  94. and had never given it any value.  Any value the element formerly had
  95. can no longer be obtained.
  96.  
  97. Here is an example of deleting elements in an array:
  98.  
  99. @example
  100. for (i in frequencies)
  101.   delete frequencies[i]
  102. @end example
  103.  
  104. @noindent
  105. This example removes all the elements from the array @code{frequencies}.
  106.  
  107. If you delete an element, a subsequent @code{for} statement to scan the array
  108. will not report that element, and the @code{in} operator to check for
  109. the presence of that element will return 0:
  110.  
  111. @example
  112. delete foo[4]
  113. if (4 in foo)
  114.   print "This will never be printed"
  115. @end example
  116.  
  117. @node Multi-dimensional, Multi-scanning, Delete, Arrays
  118. @section Multi-dimensional Arrays
  119.  
  120. @cindex subscripts, multi-dimensional in arrays
  121. @cindex arrays, multi-dimensional subscripts
  122. @cindex multi-dimensional subscripts
  123. A multi-dimensional array is an array in which an element is identified
  124. by a sequence of indices, not a single index.  For example, a
  125. two-dimensional array requires two indices.  The usual way (in most
  126. languages, including @code{awk}) to refer to an element of a
  127. two-dimensional array named @code{grid} is with
  128. @code{grid[@var{x},@var{y}]}.
  129.  
  130. @vindex SUBSEP
  131. Multi-dimensional arrays are supported in @code{awk} through
  132. concatenation of indices into one string.  What happens is that
  133. @code{awk} converts the indices into strings (@pxref{Conversion}) and
  134. concatenates them together, with a separator between them.  This creates
  135. a single string that describes the values of the separate indices.  The
  136. combined string is used as a single index into an ordinary,
  137. one-dimensional array.  The separator used is the value of the built-in
  138. variable @code{SUBSEP}.
  139.  
  140. For example, suppose we evaluate the expression @code{foo[5,12]="value"}
  141. when the value of @code{SUBSEP} is @code{"@@"}.  The numbers 5 and 12 are
  142. concatenated with a comma between them, yielding @code{"5@@12"}; thus,
  143. the array element @code{foo["5@@12"]} is set to @code{"value"}.
  144.  
  145. Once the element's value is stored, @code{awk} has no record of whether
  146. it was stored with a single index or a sequence of indices.  The two
  147. expressions @code{foo[5,12]} and @w{@code{foo[5 SUBSEP 12]}} always have
  148. the same value.
  149.  
  150. The default value of @code{SUBSEP} is actually the string @code{"\034"},
  151. which contains a nonprinting character that is unlikely to appear in an
  152. @code{awk} program or in the input data.
  153.  
  154. The usefulness of choosing an unlikely character comes from the fact
  155. that index values that contain a string matching @code{SUBSEP} lead to
  156. combined strings that are ambiguous.  Suppose that @code{SUBSEP} were
  157. @code{"@@"}; then @w{@code{foo["a@@b", "c"]}} and @w{@code{foo["a",
  158. "b@@c"]}} would be indistinguishable because both would actually be
  159. stored as @code{foo["a@@b@@c"]}.  Because @code{SUBSEP} is
  160. @code{"\034"}, such confusion can actually happen only when an index
  161. contains the character with ASCII code 034, which is a rare
  162. event.@refill
  163.  
  164. You can test whether a particular index-sequence exists in a
  165. ``multi-dimensional'' array with the same operator @code{in} used for single
  166. dimensional arrays.  Instead of a single index as the left-hand operand,
  167. write the whole sequence of indices, separated by commas, in
  168. parentheses:@refill
  169.  
  170. @example
  171. (@var{subscript1}, @var{subscript2}, @dots{}) in @var{array}
  172. @end example
  173.  
  174. The following example treats its input as a two-dimensional array of
  175. fields; it rotates this array 90 degrees clockwise and prints the
  176. result.  It assumes that all lines have the same number of
  177. elements.
  178.  
  179. @example
  180. awk '@{
  181.      if (max_nf < NF)
  182.           max_nf = NF
  183.      max_nr = NR
  184.      for (x = 1; x <= NF; x++)
  185.           vector[x, NR] = $x
  186. @}
  187.  
  188. END @{
  189.      for (x = 1; x <= max_nf; x++) @{
  190.           for (y = max_nr; y >= 1; --y)
  191.                printf("%s ", vector[x, y])
  192.           printf("\n")
  193.      @}
  194. @}'
  195. @end example
  196.  
  197. @noindent
  198. When given the input:
  199.  
  200. @example
  201. 1 2 3 4 5 6
  202. 2 3 4 5 6 1
  203. 3 4 5 6 1 2
  204. 4 5 6 1 2 3
  205. @end example
  206.  
  207. @noindent
  208. it produces:
  209.  
  210. @example
  211. 4 3 2 1
  212. 5 4 3 2
  213. 6 5 4 3
  214. 1 6 5 4
  215. 2 1 6 5
  216. 3 2 1 6
  217. @end example
  218.  
  219. @node Multi-scanning, , Multi-dimensional, Arrays
  220. @section Scanning Multi-dimensional Arrays
  221.  
  222. There is no special @code{for} statement for scanning a
  223. ``multi-dimensional'' array; there cannot be one, because in truth there
  224. are no multi-dimensional arrays or elements; there is only a
  225. multi-dimensional @emph{way of accessing} an array.
  226.  
  227. However, if your program has an array that is always accessed as
  228. multi-dimensional, you can get the effect of scanning it by combining
  229. the scanning @code{for} statement (@pxref{Scanning an Array}) with the
  230. @code{split} built-in function (@pxref{String Functions}).  It works
  231. like this:
  232.  
  233. @example
  234. for (combined in @var{array}) @{
  235.   split(combined, separate, SUBSEP)
  236.   @dots{}
  237. @}
  238. @end example
  239.  
  240. @noindent
  241. This finds each concatenated, combined index in the array, and splits it
  242. into the individual indices by breaking it apart where the value of
  243. @code{SUBSEP} appears.  The split-out indices become the elements of
  244. the array @code{separate}.
  245.  
  246. Thus, suppose you have previously stored in @code{@var{array}[1,
  247. "foo"]}; then an element with index @code{"1\034foo"} exists in
  248. @var{array}.  (Recall that the default value of @code{SUBSEP} contains
  249. the character with code 034.)  Sooner or later the @code{for} statement
  250. will find that index and do an iteration with @code{combined} set to
  251. @code{"1\034foo"}.  Then the @code{split} function is called as
  252. follows:
  253.  
  254. @example
  255. split("1\034foo", separate, "\034")
  256. @end example
  257.  
  258. @noindent
  259. The result of this is to set @code{separate[1]} to 1 and @code{separate[2]}
  260. to @code{"foo"}.  Presto, the original sequence of separate indices has
  261. been recovered.
  262.  
  263. @node Built-in, User-defined, Arrays, Top
  264. @chapter Built-in Functions
  265.  
  266. @cindex built-in functions
  267. @dfn{Built-in} functions are functions that are always available for
  268. your @code{awk} program to call.  This chapter defines all the built-in
  269. functions in @code{awk}; some of them are mentioned in other sections,
  270. but they are summarized here for your convenience.  (You can also define
  271. new functions yourself.  @xref{User-defined}.)
  272.  
  273. @menu
  274. * Calling Built-in::   How to call built-in functions.
  275.  
  276. * Numeric Functions::  Functions that work with numbers,
  277.                        including @code{int}, @code{sin} and @code{rand}.
  278.  
  279. * String Functions::   Functions for string manipulation,
  280.                        such as @code{split}, @code{match}, and @code{sprintf}.
  281.  
  282. * I/O Functions::      Functions for files and shell commands
  283. @end menu
  284.  
  285. @node Calling Built-in, Numeric Functions, Built-in, Built-in
  286. @section Calling Built-in Functions
  287.  
  288. To call a built-in function, write the name of the function followed
  289. by arguments in parentheses.  For example, @code{atan2(y + z, 1)}
  290. is a call to the function @code{atan2}, with two arguments.
  291.  
  292. Whitespace is ignored between the built-in function name and the
  293. open-parenthesis, but we recommend that you avoid using whitespace
  294. there.  User-defined functions do not permit whitespace in this way, and
  295. you will find it easier to avoid mistakes by following a simple
  296. convention which always works: no whitespace after a function name.
  297.  
  298. Each built-in function accepts a certain number of arguments.  In most
  299. cases, any extra arguments given to built-in functions are ignored.  The
  300. defaults for omitted arguments vary from function to function and are
  301. described under the individual functions.
  302.  
  303. When a function is called, expressions that create the function's actual
  304. parameters are evaluated completely before the function call is performed.
  305. For example, in the code fragment:
  306.  
  307. @example
  308. i = 4
  309. j = sqrt(i++)
  310. @end example
  311.  
  312. @noindent
  313. the variable @code{i} is set to 5 before @code{sqrt} is called
  314. with a value of 4 for its actual parameter.
  315.  
  316. @node Numeric Functions, String Functions, Calling Built-in, Built-in
  317. @section Numeric Built-in Functions
  318.  
  319. Here is a full list of built-in functions that work with numbers:
  320.  
  321. @table @code
  322. @item int(@var{x})
  323. This gives you the integer part of @var{x}, truncated toward 0.  This
  324. produces the nearest integer to @var{x}, located between @var{x} and 0.
  325.  
  326. For example, @code{int(3)} is 3, @code{int(3.9)} is 3, @code{int(-3.9)}
  327. is @minus{}3, and @code{int(-3)} is @minus{}3 as well.@refill
  328.  
  329. @item sqrt(@var{x})
  330. This gives you the positive square root of @var{x}.  It reports an error
  331. if @var{x} is negative.  Thus, @code{sqrt(4)} is 2.@refill
  332.  
  333. @item exp(@var{x})
  334. This gives you the exponential of @var{x}, or reports an error if
  335. @var{x} is out of range.  The range of values @var{x} can have depends
  336. on your machine's floating point representation.@refill
  337.  
  338. @item log(@var{x})
  339. This gives you the natural logarithm of @var{x}, if @var{x} is positive;
  340. otherwise, it reports an error.@refill
  341.  
  342. @item sin(@var{x})
  343. This gives you the sine of @var{x}, with @var{x} in radians.
  344.  
  345. @item cos(@var{x})
  346. This gives you the cosine of @var{x}, with @var{x} in radians.
  347.  
  348. @item atan2(@var{y}, @var{x})
  349. This gives you the arctangent of @code{@var{y} / @var{x}}, with the
  350. quotient understood in radians.
  351.  
  352. @item rand()
  353. This gives you a random number.  The values of @code{rand} are
  354. uniformly-distributed between 0 and 1.  The value is never 0 and never
  355. 1.
  356.  
  357. Often you want random integers instead.  Here is a user-defined function
  358. you can use to obtain a random nonnegative integer less than @var{n}:
  359.  
  360. @example
  361. function randint(n) @{
  362.      return int(n * rand())
  363. @}
  364. @end example
  365.  
  366. @noindent
  367. The multiplication produces a random real number greater than 0 and less
  368. than @var{n}.  We then make it an integer (using @code{int}) between 0
  369. and @code{@var{n} @minus{} 1}.
  370.  
  371. Here is an example where a similar function is used to produce
  372. random integers between 1 and @var{n}:
  373.  
  374. @example
  375. awk '
  376. # Function to roll a simulated die.
  377. function roll(n) @{ return 1 + int(rand() * n) @}
  378.  
  379. # Roll 3 six-sided dice and print total number of points.
  380. @{
  381.       printf("%d points\n", roll(6)+roll(6)+roll(6))
  382. @}'
  383. @end example
  384.  
  385. @strong{Note:} @code{rand} starts generating numbers from the same
  386. point, or @dfn{seed}, each time you run @code{awk}.  This means that
  387. a program will produce the same results each time you run it.
  388. The numbers are random within one @code{awk} run, but predictable
  389. from run to run.  This is convenient for debugging, but if you want
  390. a program to do different things each time it is used, you must change
  391. the seed to a value that will be different in each run.  To do this,
  392. use @code{srand}.
  393.  
  394. @item srand(@var{x})
  395. The function @code{srand} sets the starting point, or @dfn{seed},
  396. for generating random numbers to the value @var{x}.
  397.  
  398. Each seed value leads to a particular sequence of ``random'' numbers.
  399. Thus, if you set the seed to the same value a second time, you will get
  400. the same sequence of ``random'' numbers again.
  401.  
  402. If you omit the argument @var{x}, as in @code{srand()}, then the current
  403. date and time of day are used for a seed.  This is the way to get random
  404. numbers that are truly unpredictable.
  405.  
  406. The return value of @code{srand} is the previous seed.  This makes it
  407. easy to keep track of the seeds for use in consistently reproducing
  408. sequences of random numbers.
  409. @end table
  410.  
  411. @node String Functions, I/O Functions, Numeric Functions, Built-in
  412. @section Built-in Functions for String Manipulation
  413.  
  414.   The functions in this section look at the text of one or more
  415. strings.
  416.  
  417. @table @code
  418. @item index(@var{in}, @var{find})
  419. @findex match
  420. This searches the string @var{in} for the first occurrence of the string
  421. @var{find}, and returns the position where that occurrence begins in the
  422. string @var{in}.  For example:@refill
  423.  
  424. @example
  425. awk 'BEGIN @{ print index("peanut", "an") @}'
  426. @end example
  427.  
  428. @noindent
  429. prints @samp{3}.  If @var{find} is not found, @code{index} returns 0.
  430.  
  431. @item length(@var{string})
  432. @findex length
  433. This gives you the number of characters in @var{string}.  If
  434. @var{string} is a number, the length of the digit string representing
  435. that number is returned.  For example, @code{length("abcde")} is 5.  By
  436. contrast, @code{length(15 * 35)} works out to 3.  How?  Well, 15 * 35 =
  437. 525, and 525 is then converted to the string @samp{"525"}, which has
  438. three characters.
  439.  
  440. If no argument is supplied, @code{length} returns the length of @code{$0}.
  441.  
  442. @item match(@var{string}, @var{regexp})
  443. @findex match
  444. The @code{match} function searches the string, @var{string}, for the
  445. longest, leftmost substring matched by the regular expression,
  446. @var{regexp}.  It returns the character position, or @dfn{index}, of
  447. where that substring begins (1, if it starts at the beginning of
  448. @var{string}).  If no match if found, it returns 0.
  449.  
  450. @vindex RSTART
  451. @vindex RLENGTH
  452. The @code{match} function sets the built-in variable @code{RSTART} to
  453. the index.  It also sets the built-in variable @code{RLENGTH} to the
  454. length of the matched substring.  If no match is found, @code{RSTART}
  455. is set to 0, and @code{RLENGTH} to @minus{}1.
  456.  
  457. For example:
  458.  
  459. @example
  460. awk '@{
  461.        if ($1 == "FIND")
  462.          regex = $2
  463.        else @{
  464.          where = match($0, regex)
  465.          if (where)
  466.            print "Match of", regex, "found at", where, "in", $0
  467.        @}
  468. @}'
  469. @end example
  470.  
  471. @noindent
  472. This program looks for lines that match the regular expression stored in
  473. the variable @code{regex}.  This regular expression can be changed.  If the
  474. first word on a line is @samp{FIND}, @code{regex} is changed to be the
  475. second word on that line.  Therefore, given:
  476.  
  477. @example
  478. FIND fo*bar
  479. My program was a foobar
  480. But none of it would doobar
  481. FIND Melvin
  482. JF+KM
  483. This line is property of The Reality Engineering Co.
  484. This file created by Melvin.
  485. @end example
  486.  
  487. @noindent
  488. @code{awk} prints:
  489.  
  490. @example
  491. Match of fo*bar found at 18 in My program was a foobar
  492. Match of Melvin found at 26 in This file created by Melvin.
  493. @end example
  494.  
  495. @item split(@var{string}, @var{array}, @var{fieldsep})
  496. @findex split
  497. This divides @var{string} up into pieces separated by @var{fieldsep},
  498. and stores the pieces in @var{array}.  The first piece is stored in
  499. @code{@var{array}[1]}, the second piece in @code{@var{array}[2]}, and so
  500. forth.  The string value of the third argument, @var{fieldsep}, is used
  501. as a regexp to search for to find the places to split @var{string}.  If
  502. the @var{fieldsep} is omitted, the value of @code{FS} is used.
  503. @code{split} returns the number of elements created.@refill
  504.  
  505. The @code{split} function, then, splits strings into pieces in a
  506. manner similar to the way input lines are split into fields.  For example:
  507.  
  508. @example
  509. split("auto-da-fe", a, "-")
  510. @end example
  511.  
  512. @noindent
  513. splits the string @samp{auto-da-fe} into three fields using @samp{-} as the
  514. separator.  It sets the contents of the array @code{a} as follows:
  515.  
  516. @example
  517. a[1] = "auto"
  518. a[2] = "da"
  519. a[3] = "fe"
  520. @end example
  521.  
  522. @noindent
  523. The value returned by this call to @code{split} is 3.
  524.  
  525. @item sprintf(@var{format}, @var{expression1},@dots{})
  526. @findex sprintf
  527. This returns (without printing) the string that @code{printf} would
  528. have printed out with the same arguments (@pxref{Printf}).  For
  529. example:
  530.  
  531. @example
  532. sprintf("pi = %.2f (approx.)", 22/7)
  533. @end example
  534.  
  535. @noindent
  536. returns the string @w{@code{"pi = 3.14 (approx.)"}}.
  537.  
  538. @item sub(@var{regexp}, @var{replacement}, @var{target})
  539. @findex sub
  540. The @code{sub} function alters the value of @var{target}.
  541. It searches this value, which should be a string, for the
  542. leftmost substring matched by the regular expression, @var{regexp},
  543. extending this match as far as possible.  Then the entire string is
  544. changed by replacing the matched text with @var{replacement}.
  545. The modified string becomes the new value of @var{target}.
  546.  
  547. This function is peculiar because @var{target} is not simply
  548. used to compute a value, and not just any expression will do: it
  549. must be a variable, field or array reference, so that @code{sub} can
  550. store a modified value there.  If this argument is omitted, then the
  551. default is to use and alter @code{$0}.
  552.  
  553. For example:@refill
  554.  
  555. @example
  556. str = "water, water, everywhere"
  557. sub(/at/, "ith", str)
  558. @end example
  559.  
  560. @noindent
  561. sets @code{str} to @w{@code{"wither, water, everywhere"}}, by replacing the
  562. leftmost, longest occurrence of @samp{at} with @samp{ith}.
  563.  
  564. The @code{sub} function returns the number of substitutions made (either
  565. one or zero).
  566.  
  567. If the special character @samp{&} appears in @var{replacement}, it
  568. stands for the precise substring that was matched by @var{regexp}.  (If
  569. the regexp can match more than one string, then this precise substring
  570. may vary.)  For example:@refill
  571.  
  572. @example
  573. awk '@{ sub(/candidate/, "& and his wife"); print @}'
  574. @end example
  575.  
  576. @noindent
  577. changes the first occurrence of @samp{candidate} to @samp{candidate
  578. and his wife} on each input line.
  579.  
  580. The effect of this special character can be turned off by putting a
  581. backslash before it in the string.  As usual, to insert one backslash in
  582. the string, you must write two backslashes.  Therefore, write @samp{\\&}
  583. in a string constant to include a literal @samp{&} in the replacement.
  584. For example, here is how to replace the first @samp{|} on each line with
  585. an @samp{&}:@refill
  586.  
  587. @example
  588. awk '@{ sub(/\|/, "\\&"); print @}'
  589. @end example
  590.  
  591. @strong{Note:} as mentioned above, the third argument to @code{sub} must
  592. be an lvalue.  Some versions of @code{awk} allow the third argument to
  593. be an expression which is not an lvalue.  In such a case, @code{sub}
  594. would still search for the pattern and return 0 or 1, but the result of
  595. the substitution (if any) would be thrown away because there is no place
  596. to put it.  Such versions of @code{awk} accept expressions like
  597. this:@refill
  598.  
  599. @example
  600. sub(/USA/, "United States", "the USA and Canada")
  601. @end example
  602.  
  603. @noindent
  604. But that is considered erroneous in @code{gawk}.
  605.  
  606. @item gsub(@var{regexp}, @var{replacement}, @var{target})
  607. @findex gsub
  608. This is similar to the @code{sub} function, except @code{gsub} replaces
  609. @emph{all} of the longest, leftmost, @emph{nonoverlapping} matching
  610. substrings it can find.  The @samp{g} in @code{gsub} stands for
  611. ``global'', which means replace everywhere.  For example:@refill
  612.  
  613. @example
  614. awk '@{ gsub(/Britain/, "United Kingdom"); print @}'
  615. @end example
  616.  
  617. @noindent
  618. replaces all occurrences of the string @samp{Britain} with @samp{United
  619. Kingdom} for all input records.@refill
  620.  
  621. The @code{gsub} function returns the number of substitutions made.  If
  622. the variable to be searched and altered, @var{target}, is
  623. omitted, then the entire input record, @code{$0}, is used.@refill
  624.  
  625. As in @code{sub}, the characters @samp{&} and @samp{\} are special, and
  626. the third argument must be an lvalue.
  627.  
  628. @item substr(@var{string}, @var{start}, @var{length})
  629. @findex substr
  630. This returns a @var{length}-character-long substring of @var{string},
  631. starting at character number @var{start}.  The first character of a
  632. string is character number one.  For example,
  633. @code{substr("washington", 5, 3)} returns @code{"ing"}.@refill
  634.  
  635. If @var{length} is not present, this function returns the whole suffix of
  636. @var{string} that begins at character number @var{start}.  For example,
  637. @code{substr("washington", 5)} returns @code{"ington"}.
  638.  
  639. @item tolower(@var{string})
  640. @findex tolower
  641. This returns a copy of @var{string}, with each upper-case character
  642. in the string replaced with its corresponding lower-case character.
  643. Nonalphabetic characters are left unchanged.  For example,
  644. @code{tolower("MiXeD cAsE 123")} returns @code{"mixed case 123"}.
  645.  
  646. @item toupper(@var{string})
  647. @findex toupper
  648. This returns a copy of @var{string}, with each lower-case character
  649. in the string replaced with its corresponding upper-case character.
  650. Nonalphabetic characters are left unchanged.  For example,
  651. @code{toupper("MiXeD cAsE 123")} returns @code{"MIXED CASE 123"}.
  652. @end table
  653.  
  654. @node I/O Functions, , String Functions, Built-in
  655. @section Built-in Functions For Input/Output
  656.  
  657. @table @code
  658. @item close(@var{filename})
  659. Close the file @var{filename}, for input or output.  The argument may
  660. alternatively be a shell command that was used for redirecting to or
  661. from a pipe; then the pipe is closed.
  662.  
  663. @xref{Close Input}, regarding closing input files and pipes.
  664. @xref{Close Output}, regarding closing output files and pipes.
  665.  
  666. @item system(@var{command})
  667. @findex system
  668. @cindex interaction of @code{awk} with other programs
  669. The system function allows the user to execute operating system commands
  670. and then return to the @code{awk} program.  The @code{system} function
  671. executes the command given by the string @var{command}.  It returns, as
  672. its value, the status returned by the command that was executed.
  673.  
  674. For example, if the following fragment of code is put in your @code{awk}
  675. program:
  676.  
  677. @example
  678. END @{
  679.      system("mail -s 'awk run done' operator < /dev/null")
  680. @}
  681. @end example
  682.  
  683. @noindent
  684. the system operator will be sent mail when the @code{awk} program
  685. finishes processing input and begins its end-of-input processing.
  686.  
  687. Note that much the same result can be obtained by redirecting
  688. @code{print} or @code{printf} into a pipe.  However, if your @code{awk}
  689. program is interactive, @code{system} is useful for cranking up large
  690. self-contained programs, such as a shell or an editor.@refill
  691.  
  692. Some operating systems cannot implement the @code{system} function.
  693. @code{system} causes a fatal error if it is not supported.
  694. @end table
  695.  
  696. @node User-defined, Built-in Variables, Built-in, Top
  697. @chapter User-defined Functions
  698.  
  699. @cindex user-defined functions
  700. @cindex functions, user-defined
  701. Complicated @code{awk} programs can often be simplified by defining
  702. your own functions.  User-defined functions can be called just like
  703. built-in ones (@pxref{Function Calls}), but it is up to you to define
  704. them---to tell @code{awk} what they should do.
  705.  
  706. @menu
  707. * Definition Syntax::   How to write definitions and what they mean.
  708. * Function Example::    An example function definition and what it does.
  709. * Function Caveats::    Things to watch out for.
  710. * Return Statement::    Specifying the value a function returns.
  711. @end menu
  712.  
  713. @node Definition Syntax, Function Example, User-defined, User-defined
  714. @section Syntax of Function Definitions
  715. @cindex defining functions
  716. @cindex function definition
  717.  
  718. Definitions of functions can appear anywhere between the rules of the
  719. @code{awk} program.  Thus, the general form of an @code{awk} program is
  720. extended to include sequences of rules @emph{and} user-defined function
  721. definitions.
  722.  
  723. The definition of a function named @var{name} looks like this:
  724.  
  725. @example
  726. function @var{name} (@var{parameter-list}) @{
  727.      @var{body-of-function}
  728. @}
  729. @end example
  730.  
  731. @noindent
  732. The keyword @code{function} may be abbreviated @code{func}.
  733.  
  734. @var{name} is the name of the function to be defined.  A valid function
  735. name is like a valid variable name: a sequence of letters, digits and
  736. underscores, not starting with a digit.
  737.  
  738. @var{parameter-list} is a list of the function's arguments and local
  739. variable names, separated by commas.  When the function is called,
  740. the argument names are used to hold the argument values given in
  741. the call.  The local variables are initialized to the null string.
  742.  
  743. The @var{body-of-function} consists of @code{awk} statements.  It is the
  744. most important part of the definition, because it says what the function
  745. should actually @emph{do}.  The argument names exist to give the body a
  746. way to talk about the arguments; local variables, to give the body
  747. places to keep temporary values.
  748.  
  749. Argument names are not distinguished syntactically from local variable
  750. names; instead, the number of arguments supplied when the function is
  751. called determines how many argument variables there are.  Thus, if three
  752. argument values are given, the first three names in @var{parameter-list}
  753. are arguments, and the rest are local variables.
  754.  
  755. It follows that if the number of arguments is not the same in all calls
  756. to the function, some of the names in @var{parameter-list} may be
  757. arguments on some occasions and local variables on others.  Another
  758. way to think of this is that omitted arguments default to the
  759. null string.
  760.  
  761. Usually when you write a function you know how many names you intend to
  762. use for arguments and how many you intend to use as locals.  By
  763. convention, you should write an extra space between the arguments and
  764. the locals, so that other people can follow how your function is
  765. supposed to be used.
  766.  
  767. During execution of the function body, the arguments and local variable
  768. values hide or @dfn{shadow} any variables of the same names used in the
  769. rest of the program.  The shadowed variables are not accessible in the
  770. function definition, because there is no way to name them while their
  771. names have been taken away for the local variables.  All other variables
  772. used in the @code{awk} program can be referenced or set normally in the
  773. function definition.
  774.  
  775. The arguments and local variables last only as long as the function body
  776. is executing.  Once the body finishes, the shadowed variables come back.
  777.  
  778. The function body can contain expressions which call functions.  They
  779. can even call this function, either directly or by way of another
  780. function.  When this happens, we say the function is @dfn{recursive}.
  781.  
  782. There is no need in @code{awk} to put the definition of a function
  783. before all uses of the function.  This is because @code{awk} reads the
  784. entire program before starting to execute any of it.
  785.  
  786. @node Function Example, Function Caveats, Definition Syntax, User-defined
  787. @section Function Definition Example
  788.  
  789. Here is an example of a user-defined function, called @code{myprint}, that
  790. takes a number and prints it in a specific format.
  791.  
  792. @example
  793. function myprint(num)
  794. @{
  795.      printf "%6.3g\n", num
  796. @}
  797. @end example
  798.  
  799. @noindent
  800. To illustrate, here is an @code{awk} rule which uses our @code{myprint}
  801. function:
  802.  
  803. @example
  804. $3 > 0     @{ myprint($3) @}
  805. @end example
  806.  
  807. @noindent
  808. This program prints, in our special format, all the third fields that
  809. contain a positive number in our input.  Therefore, when given:
  810.  
  811. @example
  812.  1.2   3.4   5.6   7.8
  813.  9.10 11.12 13.14 15.16
  814. 17.18 19.20 21.22 23.24
  815. @end example
  816.  
  817. @noindent
  818. this program, using our function to format the results, prints:
  819.  
  820. @example
  821.    5.6
  822.   13.1
  823.   21.2
  824. @end example
  825.  
  826. Here is a rather contrived example of a recursive function.  It prints a
  827. string backwards:
  828.  
  829. @example
  830. function rev (str, len) @{
  831.     if (len == 0) @{
  832.         printf "\n"
  833.         return
  834.     @}
  835.     printf "%c", substr(str, len, 1)
  836.     rev(str, len - 1)
  837. @}
  838. @end example
  839.  
  840. @node Function Caveats, Return Statement, Function Example, User-defined
  841. @section Calling User-defined Functions
  842.  
  843. @dfn{Calling a function} means causing the function to run and do its job.
  844. A function call is an expression, and its value is the value returned by
  845. the function.
  846.  
  847. A function call consists of the function name followed by the arguments
  848. in parentheses.  What you write in the call for the arguments are
  849. @code{awk} expressions; each time the call is executed, these
  850. expressions are evaluated, and the values are the actual arguments.  For
  851. example, here is a call to @code{foo} with three arguments:
  852.  
  853. @example
  854. foo(x y, "lose", 4 * z)
  855. @end example
  856.  
  857. @strong{Note:} whitespace characters (spaces and tabs) are not allowed
  858. between the function name and the open-parenthesis of the argument list.
  859. If you write whitespace by mistake, @code{awk} might think that you mean
  860. to concatenate a variable with an expression in parentheses.  However, it
  861. notices that you used a function name and not a variable name, and reports
  862. an error.
  863.  
  864. @cindex call by value
  865. When a function is called, it is given a @emph{copy} of the values of
  866. its arguments.  This is called @dfn{call by value}.  The caller may use
  867. a variable as the expression for the argument, but the called function
  868. does not know this: all it knows is what value the argument had.  For
  869. example, if you write this code:
  870.  
  871. @example
  872. foo = "bar"
  873. z = myfunc(foo)
  874. @end example
  875.  
  876. @noindent
  877. then you should not think of the argument to @code{myfunc} as being
  878. ``the variable @code{foo}''.  Instead, think of the argument as the
  879. string value, @code{"bar"}.
  880.  
  881. If the function @code{myfunc} alters the values of its local variables,
  882. this has no effect on any other variables.  In particular, if @code{myfunc}
  883. does this:
  884.  
  885. @example
  886. function myfunc (win) @{
  887.   print win
  888.   win = "zzz"
  889.   print win
  890. @}
  891. @end example
  892.  
  893. @noindent
  894. to change its first argument variable @code{win}, this @emph{does not}
  895. change the value of @code{foo} in the caller.  The role of @code{foo} in
  896. calling @code{myfunc} ended when its value, @code{"bar"}, was computed.
  897. If @code{win} also exists outside of @code{myfunc}, the function body
  898. cannot alter this outer value, because it is shadowed during the
  899. execution of @code{myfunc} and cannot be seen or changed from there.
  900.  
  901. @cindex call by reference
  902. However, when arrays are the parameters to functions, they are @emph{not}
  903. copied.  Instead, the array itself is made available for direct manipulation
  904. by the function.  This is usually called @dfn{call by reference}.
  905. Changes made to an array parameter inside the body of a function @emph{are}
  906. visible outside that function.  @emph{This can be very dangerous if you don't
  907. watch what you are doing.}  For example:@refill
  908.  
  909. @example
  910. function changeit (array, ind, nvalue) @{
  911.      array[ind] = nvalue
  912. @}
  913.  
  914. BEGIN @{
  915.            a[1] = 1 ; a[2] = 2 ; a[3] = 3
  916.            changeit(a, 2, "two")
  917.            printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3]
  918.       @}
  919. @end example
  920.  
  921. @noindent
  922. prints @samp{a[1] = 1, a[2] = two, a[3] = 3}, because calling
  923. @code{changeit} stores @code{"two"} in the second element of @code{a}.
  924.  
  925. @node Return Statement, , Function Caveats, User-defined
  926. @section The @code{return} Statement
  927. @cindex @code{return} statement
  928.  
  929. The body of a user-defined function can contain a @code{return} statement.
  930. This statement returns control to the rest of the @code{awk} program.  It
  931. can also be used to return a value for use in the rest of the @code{awk}
  932. program.  It looks like this:@refill
  933.  
  934. @example
  935. return @var{expression}
  936. @end example
  937.  
  938. The @var{expression} part is optional.  If it is omitted, then the returned
  939. value is undefined and, therefore, unpredictable.
  940.  
  941. A @code{return} statement with no value expression is assumed at the end of
  942. every function definition.  So if control reaches the end of the function
  943. definition, then the function returns an unpredictable value.
  944.  
  945. Here is an example of a user-defined function that returns a value
  946. for the largest number among the elements of an array:@refill
  947.  
  948. @example
  949. function maxelt (vec,   i, ret) @{
  950.      for (i in vec) @{
  951.           if (ret == "" || vec[i] > ret)
  952.                ret = vec[i]
  953.      @}
  954.      return ret
  955. @}
  956. @end example
  957.  
  958. @noindent
  959. You call @code{maxelt} with one argument, an array name.  The local
  960. variables @code{i} and @code{ret} are not intended to be arguments;
  961. while there is nothing to stop you from passing two or three arguments
  962. to @code{maxelt}, the results would be strange.  The extra space before
  963. @code{i} in the function parameter list is to indicate that @code{i} and
  964. @code{ret} are not supposed to be arguments.  This is a convention which
  965. you should follow when you define functions.
  966.  
  967. Here is a program that uses our @code{maxelt} function.  It loads an
  968. array, calls @code{maxelt}, and then reports the maximum number in that
  969. array:@refill
  970.  
  971. @example
  972. awk '
  973. function maxelt (vec,   i, ret) @{
  974.      for (i in vec) @{
  975.           if (ret == "" || vec[i] > ret)
  976.                ret = vec[i]
  977.      @}
  978.      return ret
  979. @}
  980.  
  981. # Load all fields of each record into nums.
  982. @{
  983.           for(i = 1; i <= NF; i++)
  984.                nums[NR, i] = $i
  985. @}
  986.  
  987. END @{
  988.      print maxelt(nums)
  989. @}'
  990. @end example
  991.  
  992. Given the following input:
  993.  
  994. @example
  995.  1 5 23 8 16
  996. 44 3 5 2 8 26
  997. 256 291 1396 2962 100
  998. -6 467 998 1101
  999. 99385 11 0 225
  1000. @end example
  1001.  
  1002. @noindent
  1003. our program tells us (predictably) that:
  1004.  
  1005. @example
  1006. 99385
  1007. @end example
  1008.  
  1009. @noindent
  1010. is the largest number in our array.
  1011.  
  1012. @node Built-in Variables, Command Line, User-defined, Top
  1013. @chapter Built-in Variables
  1014. @cindex built-in variables
  1015.  
  1016. Most @code{awk} variables are available for you to use for your own
  1017. purposes; they never change except when your program assigns them, and
  1018. never affect anything except when your program examines them.
  1019.  
  1020. A few variables have special built-in meanings.  Some of them @code{awk}
  1021. examines automatically, so that they enable you to tell @code{awk} how
  1022. to do certain things.  Others are set automatically by @code{awk}, so
  1023. that they carry information from the internal workings of @code{awk} to
  1024. your program.
  1025.  
  1026. This chapter documents all the built-in variables of @code{gawk}.  Most
  1027. of them are also documented in the chapters where their areas of
  1028. activity are described.
  1029.  
  1030. @menu
  1031. * User-modified::  Built-in variables that you change to control @code{awk}.
  1032.  
  1033. * Auto-set::       Built-in variables where @code{awk} gives you information.
  1034. @end menu
  1035.  
  1036. @node User-modified, Auto-set, Built-in Variables, Built-in Variables
  1037. @section Built-in Variables That Control @code{awk}
  1038. @cindex built-in variables, user modifiable
  1039.  
  1040. This is a list of the variables which you can change to control how
  1041. @code{awk} does certain things.
  1042.  
  1043. @table @code
  1044. @c it's unadvisable to have multiple index entries for the same name
  1045. @c since in Info there is no way to distinguish the two.
  1046. @c @vindex FS
  1047. @item FS
  1048. @code{FS} is the input field separator (@pxref{Field Separators}).
  1049. The value is a single-character string or a multi-character regular
  1050. expression that matches the separations between fields in an input
  1051. record.
  1052.  
  1053. The default value is @w{@code{" "}}, a string consisting of a single
  1054. space.  As a special exception, this value actually means that any
  1055. sequence of spaces and tabs is a single separator.  It also causes
  1056. spaces and tabs at the beginning or end of a line to be ignored.
  1057.  
  1058. You can set the value of @code{FS} on the command line using the
  1059. @samp{-F} option:
  1060.  
  1061. @example
  1062. awk -F, '@var{program}' @var{input-files}
  1063. @end example
  1064.  
  1065. @item IGNORECASE
  1066. @c @vindex IGNORECASE
  1067. If @code{IGNORECASE} is nonzero, then @emph{all} regular expression
  1068. matching is done in a case-independent fashion.  In particular, regexp
  1069. matching with @samp{~} and @samp{!~}, and the @code{gsub} @code{index},
  1070. @code{match}, @code{split} and @code{sub} functions all ignore case when
  1071. doing their particular regexp operations.  @strong{Note:} since field
  1072. splitting with the value of the @code{FS} variable is also a regular
  1073. expression operation, that too is done with case ignored.
  1074. @xref{Case-sensitivity}.
  1075.  
  1076. If @code{gawk} is in compatibility mode (@pxref{Command Line}), then
  1077. @code{IGNORECASE} has no special meaning, and regexp operations are
  1078. always case-sensitive.@refill
  1079.  
  1080. @item OFMT
  1081. @c @vindex OFMT
  1082. This string is used by @code{awk} to control conversion of numbers to
  1083. strings (@pxref{Conversion}).  It works by being passed, in effect, as
  1084. the first argument to the @code{sprintf} function.  Its default value
  1085. is @code{"%.6g"}.@refill
  1086.  
  1087. @item OFS
  1088. @c @vindex OFS
  1089. This is the output field separator (@pxref{Output Separators}).  It is
  1090. output between the fields output by a @code{print} statement.  Its
  1091. default value is @w{@code{" "}}, a string consisting of a single space.
  1092.  
  1093. @item ORS
  1094. @c @vindex ORS
  1095. This is the output record separator.  It is output at the end of every
  1096. @code{print} statement.  Its default value is a string containing a
  1097. single newline character, which could be written as @code{"\n"}.
  1098. (@xref{Output Separators}).@refill
  1099.  
  1100. @item RS
  1101. @c @vindex RS
  1102. This is @code{awk}'s record separator.  Its default value is a string
  1103. containing a single newline character, which means that an input record
  1104. consists of a single line of text.  (@xref{Records}.)@refill
  1105.  
  1106. @item SUBSEP
  1107. @c @vindex SUBSEP
  1108. @code{SUBSEP} is a subscript separator.  It has the default value of
  1109. @code{"\034"}, and is used to separate the parts of the name of a
  1110. multi-dimensional array.  Thus, if you access @code{foo[12,3]}, it
  1111. really accesses @code{foo["12\0343"]}.  (@xref{Multi-dimensional}).@refill
  1112. @end table
  1113.  
  1114. @node Auto-set, , User-modified, Built-in Variables
  1115. @section Built-in Variables That Convey Information to You
  1116.  
  1117. This is a list of the variables that are set automatically by @code{awk}
  1118. on certain occasions so as to provide information for your program.
  1119.  
  1120. @table @code
  1121. @item ARGC
  1122. @itemx ARGV
  1123. @c @vindex ARGC
  1124. @c @vindex ARGV
  1125. The command-line arguments available to @code{awk} are stored in an
  1126. array called @code{ARGV}.  @code{ARGC} is the number of command-line
  1127. arguments present.  @code{ARGV} is indexed from zero to @w{@code{ARGC - 1}}.
  1128. @xref{Command Line}.  For example:
  1129.  
  1130. @example
  1131. awk '@{ print ARGV[$1] @}' inventory-shipped BBS-list
  1132. @end example
  1133.  
  1134. @noindent
  1135. In this example, @code{ARGV[0]} contains @code{"awk"}, @code{ARGV[1]}
  1136. contains @code{"inventory-shipped"}, and @code{ARGV[2]} contains
  1137. @code{"BBS-list"}.  The value of @code{ARGC} is 3, one more than the
  1138. index of the last element in @code{ARGV} since the elements are numbered
  1139. from zero.@refill
  1140.  
  1141. Notice that the @code{awk} program is not entered in @code{ARGV}.  The
  1142. other special command line options, with their arguments, are also not
  1143. entered.  But variable assignments on the command line @emph{are}
  1144. treated as arguments, and do show up in the @code{ARGV} array.
  1145.  
  1146. Your program can alter @code{ARGC} and the elements of @code{ARGV}.
  1147. Each time @code{awk} reaches the end of an input file, it uses the next
  1148. element of @code{ARGV} as the name of the next input file.  By storing a
  1149. different string there, your program can change which files are read.
  1150. You can use @code{"-"} to represent the standard input.  By storing
  1151. additional elements and incrementing @code{ARGC} you can cause
  1152. additional files to be read.
  1153.  
  1154. If you decrease the value of @code{ARGC}, that eliminates input files
  1155. from the end of the list.  By recording the old value of @code{ARGC}
  1156. elsewhere, your program can treat the eliminated arguments as
  1157. something other than file names.
  1158.  
  1159. To eliminate a file from the middle of the list, store the null string
  1160. (@code{""}) into @code{ARGV} in place of the file's name.  As a
  1161. special feature, @code{awk} ignores file names that have been
  1162. replaced with the null string.
  1163.  
  1164. @item ENVIRON
  1165. @vindex ENVIRON
  1166. This is an array that contains the values of the environment.  The array
  1167. indices are the environment variable names; the values are the values of
  1168. the particular environment variables.  For example,
  1169. @code{ENVIRON["HOME"]} might be @file{/u/close}.  Changing this array
  1170. does not affect the environment passed on to any programs that
  1171. @code{awk} may spawn via redirection or the @code{system} function.
  1172. (In a future version of @code{gawk}, it may do so.)
  1173.  
  1174. Some operating systems may not have environment variables.
  1175. On such systems, the array @code{ENVIRON} is empty.
  1176.  
  1177. @item FILENAME
  1178. @c @vindex FILENAME
  1179. This is the name of the file that @code{awk} is currently reading.
  1180. If @code{awk} is reading from the standard input (in other words,
  1181. there are no files listed on the command line),
  1182. @code{FILENAME} is set to @code{"-"}.
  1183. @code{FILENAME} is changed each time a new file is read (@pxref{Reading
  1184. Files}).@refill
  1185.  
  1186. @item FNR
  1187. @c @vindex FNR
  1188. @code{FNR} is the current record number in the current file.  @code{FNR} is
  1189. incremented each time a new record is read (@pxref{Getline}).
  1190. It is reinitialized to 0 each time a new input file is started.
  1191.  
  1192. @item NF
  1193. @c @vindex NF
  1194. @code{NF} is the number of fields in the current input record.
  1195. @code{NF} is set each time a new record is read, when a new field is
  1196. created, or when @code{$0} changes (@pxref{Fields}).@refill
  1197.  
  1198. @item NR
  1199. @c @vindex NR
  1200. This is the number of input records @code{awk} has processed since
  1201. the beginning of the program's execution.  (@pxref{Records}).
  1202. @code{NR} is set each time a new record is read.@refill
  1203.  
  1204. @item RLENGTH
  1205. @c @vindex RLENGTH
  1206. @code{RLENGTH} is the length of the substring matched by the
  1207. @code{match} function (@pxref{String Functions}).  @code{RLENGTH} is set
  1208. by invoking the @code{match} function.  Its value is the length of the
  1209. matched string, or @minus{}1 if no match was found.@refill
  1210.  
  1211. @item RSTART
  1212. @c @vindex RSTART
  1213. @code{RSTART} is the start-index of the substring matched by the
  1214. @code{match} function (@pxref{String Functions}).  @code{RSTART} is set
  1215. by invoking the @code{match} function.  Its value is the position of the
  1216. string where the matched substring starts, or 0 if no match was
  1217. found.@refill
  1218. @end table
  1219.  
  1220. @node Command Line, Language History, Built-in Variables, Top
  1221. @c node-name, next, previous, up
  1222. @chapter Invocation of @code{awk}
  1223. @cindex command line
  1224. @cindex invocation of @code{gawk}
  1225. @cindex arguments, command line
  1226. @cindex options, command line
  1227.  
  1228. There are two ways to run @code{awk}: with an explicit program, or with
  1229. one or more program files.  Here are templates for both of them; items
  1230. enclosed in @samp{@r{[}@dots{}@r{]}} in these templates are optional.
  1231.  
  1232. @example
  1233. awk @r{[@code{-F@var{fs}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} '@var{program}' @var{file} @dots{}
  1234. awk @r{[@code{-F@var{fs}}] @code{-f @var{source-file}} [@code{-f @var{source-file} @dots{}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} @var{file} @dots{}
  1235. @end example
  1236.  
  1237. @menu
  1238. * Options::             Command line options and their meanings.
  1239. * Other Arguments::     Input file names and variable assignments.
  1240. * AWKPATH Variable::    Searching directories for @code{awk} programs.
  1241. @end menu
  1242.  
  1243. @node Options, Other Arguments, Command Line, Command Line
  1244. @section Command Line Options
  1245.  
  1246. Options begin with a minus sign, and consist of a single character.
  1247. The options and their meanings are as follows:
  1248.  
  1249. @table @code
  1250. @item -F@var{fs}
  1251. Sets the @code{FS} variable to @var{fs} (@pxref{Field Separators}).
  1252.  
  1253. @item -f @var{source-file}
  1254. Indicates that the @code{awk} program is to be found in @var{source-file}
  1255. instead of in the first non-option argument.
  1256.  
  1257. @item -v @var{var}=@var{val}
  1258. @cindex @samp{-v} option
  1259. Sets the variable @var{var} to the value @var{val} @emph{before}
  1260. execution of the program begins.  Such variable values are available
  1261. inside the @code{BEGIN} rule (see below for a fuller explanation).
  1262.  
  1263. The @samp{-v} option only has room to set one variable, but you can use
  1264. it more than once, setting another variable each time, like this:
  1265. @samp{@w{-v foo=1} @w{-v bar=2}}.
  1266.  
  1267. @item -a
  1268. Specifies use of traditional @code{awk} syntax for regular expressions.
  1269. This means that @samp{\} can be used to quote any regular expression
  1270. operators inside of square brackets, just as it can be outside of them.
  1271. This mode is currently the default; the @samp{-a} option is useful in
  1272. shell scripts so that they will not break if the default is changed.
  1273. @xref{Regexp Operators}.
  1274.  
  1275. @item -e
  1276. Specifies use of @code{egrep} syntax for regular expressions.  This
  1277. means that @samp{\} does not serve as a quoting character inside of
  1278. square brackets; ideosyncratic techniques are needed to include various
  1279. special characters within them.  This mode may become the default at
  1280. some time in the future.  @xref{Regexp Operators}.
  1281.  
  1282. @item -c
  1283. @cindex @samp{-c} option
  1284. Specifies @dfn{compatibility mode}, in which the GNU extensions in
  1285. @code{gawk} are disabled, so that @code{gawk} behaves just like Unix
  1286. @code{awk}.  These extensions are noted below, where their usage is
  1287. explained.  @xref{Compatibility Mode}.
  1288.  
  1289. @item -V
  1290. @cindex @samp{-V} option
  1291. Prints version information for this particular copy of @code{gawk}.
  1292. This is so you can determine if your copy of @code{gawk} is up to date
  1293. with respect to whatever the Free Software Foundation is currently
  1294. distributing.  This option may disappear in a future version of @code{gawk}.
  1295.  
  1296. @item -C
  1297. @cindex @samp{-C} option
  1298. Prints the short version of the General Public License.
  1299. This option may disappear in a future version of @code{gawk}.
  1300.  
  1301. @item --
  1302. Signals the end of the command line options.  The following arguments
  1303. are not treated as options even if they begin with @samp{-}.  This
  1304. interpretation of @samp{--} follows the POSIX argument parsing
  1305. conventions.
  1306.  
  1307. This is useful if you have file names that start with @samp{-},
  1308. or in shell scripts, if you have file names that will be specified
  1309. by the user and that might start with @samp{-}.
  1310. @end table
  1311.  
  1312. Any other options are flagged as invalid with a warning message, but
  1313. are otherwise ignored.
  1314.  
  1315. In compatibility mode, as a special case, if the value of @var{fs} supplied
  1316. to the @samp{-F} option is @samp{t}, then @code{FS} is set to the tab
  1317. character (@code{"\t"}).  Also, the @samp{-C} and @samp{-V} options
  1318. are not recognized.@refill
  1319.  
  1320. If the @samp{-f} option is @emph{not} used, then the first non-option
  1321. command line argument is expected to be the program text.
  1322.  
  1323. The @samp{-f} option may be used more than once on the command line.
  1324. Then @code{awk} reads its program source from all of the named files, as
  1325. if they had been concatenated together into one big file.  This is
  1326. useful for creating libraries of @code{awk} functions.  Useful functions
  1327. can be written once, and then retrieved from a standard place, instead
  1328. of having to be included into each individual program.  You can still
  1329. type in a program at the terminal and use library functions, by specifying
  1330. @samp{-f /dev/tty}.  @code{awk} will read a file from the terminal
  1331. to use as part of the @code{awk} program.  After typing your program,
  1332. type @kbd{Control-d} (the end-of-file character) to terminate it.
  1333.  
  1334. @node Other Arguments, AWKPATH Variable, Options, Command Line
  1335. @section Other Command Line Arguments
  1336.  
  1337. Any additional arguments on the command line are normally treated as
  1338. input files to be processed in the order specified.  However, an
  1339. argument that has the form @code{@var{var}=@var{value}}, means to assign
  1340. the value @var{value} to the variable @var{var}---it does not specify a
  1341. file at all.
  1342.  
  1343. @vindex ARGV
  1344. All these arguments are made available to your @code{awk} program in the
  1345. @code{ARGV} array (@pxref{Built-in Variables}).  Command line options
  1346. and the program text (if present) are omitted from the @code{ARGV}
  1347. array.  All other arguments, including variable assignments, are
  1348. included.
  1349.  
  1350. The distinction between file name arguments and variable-assignment
  1351. arguments is made when @code{awk} is about to open the next input file.
  1352. At that point in execution, it checks the ``file name'' to see whether
  1353. it is really a variable assignment; if so, @code{awk} sets the variable
  1354. instead of reading a file.
  1355.  
  1356. Therefore, the variables actually receive the specified values after all
  1357. previously specified files have been read.  In particular, the values of
  1358. variables assigned in this fashion are @emph{not} available inside a
  1359. @code{BEGIN} rule (@pxref{BEGIN/END}), since such rules are run before
  1360. @code{awk} begins scanning the argument list.@refill
  1361.  
  1362. In some earlier implementations of @code{awk}, when a variable assignment
  1363. occurred before any file names, the assignment would happen @emph{before}
  1364.