home *** CD-ROM | disk | FTP | other *** search
/ Garbo / Garbo.cdr / pc / unix / gawk_doc.zoo / gawk-info-3 < prev    next >
Encoding:
Text File  |  1989-04-13  |  48.8 KB  |  1,386 lines

  1. Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
  2. file gawk.texinfo.
  3.  
  4. This file documents `awk', a program that you can use to select
  5. particular records in a file and perform operations upon them.
  6.  
  7. Copyright (C) 1989 Free Software Foundation, Inc.
  8.  
  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.  
  13. Permission is granted to copy and distribute modified versions of
  14. this manual under the conditions for verbatim copying, provided that
  15. the entire resulting derived work is distributed under the terms of a
  16. permission notice identical to this one.
  17.  
  18. Permission is granted to copy and distribute translations of this
  19. manual into another language, under the above conditions for modified
  20. versions, except that this permission notice may be stated in a
  21. translation approved by the Foundation.
  22.  
  23.  
  24. 
  25. File: gawk-info,  Node: Patterns,  Next: Actions,  Prev: One-liners,  Up: Top
  26.  
  27. Patterns
  28. ********
  29.  
  30. Patterns control the execution of rules: a rule is executed when its
  31. pattern matches the input record.  The `awk' language provides
  32. several special patterns that are described in the sections that
  33. follow.  Patterns include:
  34.  
  35. NULL
  36.      The empty pattern, which matches every input record. (*Note The
  37.      Empty Pattern: Empty.)
  38.  
  39. /REGULAR EXPRESSION/
  40.      A regular expression as a pattern.  It matches when the text of
  41.      the input record fits the regular expression.  (*Note Regular
  42.      Expressions as Patterns: Regexp.)
  43.  
  44. CONDEXP
  45.      A single comparison expression.  It matches when it is true. 
  46.      (*Note Comparison Expressions as Patterns: Comparison Patterns.)
  47.  
  48. `BEGIN'
  49. `END'
  50.      Special patterns to supply start--up or clean--up information to
  51.      `awk'.  (*Note Specifying Record Ranges With Patterns: BEGIN/END.)
  52.  
  53. PAT1, PAT2
  54.      A pair of patterns separated by a comma, specifying a range of
  55.      records.  (*Note Specifying Record Ranges With Patterns: Ranges.)
  56.  
  57. CONDEXP1 BOOLEAN CONDEXP2
  58.      A "compound" pattern, which combines expressions with the
  59.      operators `and', `&&', and `or', `||'.  (*Note  Boolean
  60.      Operators and Patterns: Boolean.)
  61.  
  62. ! CONDEXP
  63.      The pattern CONDEXP is evaluated.  Then the `!' performs a
  64.      boolean ``not'' or logical negation operation; if the input line
  65.      matches the pattern in CONDEXP then the associated action is
  66.      *not* executed. If the input line did not match that pattern,
  67.      then the action *is* executed.   (*Note Boolean Operators and
  68.      Patterns: Boolean.)
  69.  
  70. (EXPR)
  71.      Parentheses may be used to control how operators nest.
  72.  
  73. PAT1 ? PAT2 : PAT3
  74.      The first pattern is evaluated.  If it is true, the input line
  75.      is tested against the second pattern, otherwise it is tested
  76.      against the third.  (*Note Conditional Patterns: Conditional
  77.      Patterns.)
  78.  
  79. * Menu:
  80.  
  81. The following subsections describe these forms in detail:
  82.  
  83. * Empty::                The empty pattern, which matches every record.
  84.  
  85. * Regexp::               Regular expressions such as `/foo/'.
  86.  
  87. * Comparison Patterns::  Comparison expressions such as `$1 > 10'.
  88.  
  89. * Boolean::              Combining comparison expressions.
  90.  
  91. * Ranges::               Using pairs of patterns to specify record ranges.
  92.  
  93. * BEGIN/END::            Specifying initialization and cleanup rules.
  94.  
  95. * Conditional Patterns:: Patterns such as `pat1 ? pat2 : pat3'.
  96.  
  97.  
  98. 
  99. File: gawk-info,  Node: Empty,  Next: Regexp,  Up: Patterns
  100.  
  101. The Empty Pattern
  102. =================
  103.  
  104. An empty pattern is considered to match *every* input record.  For
  105. example, the program:
  106.  
  107.      awk '{ print $1 }' BBS-list
  108.  
  109. prints just the first field of every record.
  110.  
  111.  
  112. 
  113. File: gawk-info,  Node: Regexp,  Next: Comparison Patterns,  Prev: Empty,  Up: Patterns
  114.  
  115. Regular Expressions as Patterns
  116. ===============================
  117.  
  118. A "regular expression", or "regexp", is a way of describing classes
  119. of strings.  When enclosed in slashes (`/'), it makes an `awk'
  120. pattern that matches every input record that contains a match for the
  121. regexp.
  122.  
  123. The simplest regular expression is a sequence of letters, numbers, or
  124. both.  Such a regexp matches any string that contains that sequence. 
  125. Thus, the regexp `foo' matches any string containing `foo'.  (More
  126. complicated regexps let you specify classes of similar strings.)
  127.  
  128. * Menu:
  129.  
  130. * Usage: Regexp Usage.          How regexps are used in patterns.
  131. * Operators: Regexp Operators.  How to write a regexp.
  132.  
  133.  
  134. 
  135. File: gawk-info,  Node: Regexp Usage,  Next: Regexp Operators,  Up: Regexp
  136.  
  137. How to use Regular Expressions
  138. ------------------------------
  139.  
  140. When you enclose `foo' in slashes, you get a pattern that matches a
  141. record that contains `foo'.  For example, this prints the second
  142. field of each record that contains `foo' anywhere:
  143.  
  144.      awk '/foo/ { print $2 }' BBS-list
  145.  
  146. Regular expressions can also be used in comparison expressions.  Then
  147. you can specify the string to match against; it need not be the
  148. entire current input record.  These comparison expressions can be
  149. used as patterns or in `if' and `while' statements.
  150.  
  151. `EXP ~ /REGEXP/'
  152.      This is true if the expression EXP (taken as a character string)
  153.      is matched by REGEXP.  The following example matches, or
  154.      selects, all input records with the letter `J' in the first field:
  155.  
  156.           awk '$1 ~ /J/' inventory-shipped
  157.  
  158.      So does this:
  159.  
  160.           awk '{ if ($1 ~ /J/) print }' inventory-shipped
  161.  
  162. `EXP !~ /REGEXP/'
  163.      This is true if the expression EXP (taken as a character string)
  164.      is *not* matched by REGEXP.  The following example matches, or
  165.      selects, all input records whose first field *does not* contain
  166.      the letter `J':
  167.  
  168.           awk '$1 !~ /J/' inventory-shipped
  169.  
  170. The right hand side of a `~' or `!~' operator need not be a constant
  171. regexp (i.e. a string of characters between `/'s).  It can also be
  172. "computed", or "dynamic".  For example:
  173.  
  174.      identifier = "[A-Za-z_][A-Za-z_0-9]+"
  175.      $0 ~ identifier
  176.  
  177. sets `identifier' to a regexp that describes `awk' variable names,
  178. and tests if the input record matches this regexp.
  179.  
  180. A dynamic regexp may actually be any expression.  The expression is
  181. evaluated, and the result is treated as a string that describes a
  182. regular expression.
  183.  
  184.  
  185. 
  186. File: gawk-info,  Node: Regexp Operators,  Prev: Regexp Usage,  Up: Regexp
  187.  
  188. Regular Expression Operators
  189. ----------------------------
  190.  
  191. You can combine regular expressions with the following characters,
  192. called "regular expression operators", or "metacharacters", to
  193. increase the power and versatility of regular expressions.  This is a
  194. table of metacharacters:
  195.  
  196. `\'
  197.      This is used to suppress the special meaning of a character when
  198.      matching.  For example:
  199.  
  200.           \$
  201.  
  202.      matches the character `$'.
  203.  
  204. `^'
  205.      This matches the beginning of the string or the beginning of a
  206.      line within the string.  For example:
  207.  
  208.           ^@chapter
  209.  
  210.      matches the `@chapter' at the beginning of a string, and can be
  211.      used to identify chapter beginnings in Texinfo source files.
  212.  
  213. `$'
  214.      This is similar to `^', but it matches only at the end of a
  215.      string or the end of a line within the string.  For example:
  216.  
  217.           /p$/
  218.  
  219.      as a pattern matches a record that ends with a `p'.
  220.  
  221. `.'
  222.      This matches any single character except a newline.  For example:
  223.  
  224.           .P
  225.  
  226.      matches any single character followed by a `P' in a string. 
  227.      Using concatenation we can make regular expressions like `U.A',
  228.      which matches any three--character string that begins with `U'
  229.      and ends with `A'.
  230.  
  231. `[...]'
  232.      This is called a "character set".  It matches any one of a group
  233.      of characters that are enclosed in the square brackets.  For
  234.      example:
  235.  
  236.           [MVX]
  237.  
  238.      matches any of the characters `M', `V', or `X' in a string.
  239.  
  240.      Ranges of characters are indicated by using a hyphen between the
  241.      beginning and ending characters, and enclosing the whole thing
  242.      in brackets.  For example:
  243.  
  244.           [0-9]
  245.  
  246.      matches any string that contains a digit.
  247.  
  248.      Note that special patterns have to be followed to match the
  249.      characters, `]', `-', and `^' when they are enclosed in the
  250.      square brackets.  To match a `]', make it the first character in
  251.      the set.  For example:
  252.  
  253.           []d]
  254.  
  255.      matches either `]', or `d'.
  256.  
  257.      To match `-', write it as `--', which is a range containing only
  258.      `-'.  You may also make the `-' be the first or last character
  259.      in the set.  To match `^', make it any character except the
  260.      first one of a set.
  261.  
  262. `[^ ...]'
  263.      This is the "complemented character set".  The first character
  264.      after the `[' *must* be a `^'.  This matches any characters
  265.      *except* those in the square brackets.  For example:
  266.  
  267.           [^0-9]
  268.  
  269.      matches any characters that are not digits.
  270.  
  271. `|'
  272.      This is the "alternation operator" and it is used to specify
  273.      alternatives.  For example:
  274.  
  275.           ^P|[0-9]
  276.  
  277.      matches any string that matches either `^P' or `[0-9]'.  This
  278.      means it matches any string that contains a digit or starts with
  279.      `P'.
  280.  
  281. `(...)'
  282.      Parentheses are used for grouping in regular expressions as in
  283.      arithmetic.  They can be used to concatenate regular expressions
  284.      containing the alternation operator, `|'.
  285.  
  286. `*'
  287.      This symbol means that the preceding regular expression is to be
  288.      repeated as many times as possible to find a match.  For example:
  289.  
  290.           ph*
  291.  
  292.      applies the `*' symbol to the preceding `h' and looks for
  293.      matches to one `p' followed by any number of `h''s.  This will
  294.      also match just `p' if no `h''s are present.
  295.  
  296.      The `*' means repeat the *smallest* possible preceding
  297.      expression in order to find a match.  The `awk' language
  298.      processes a `*' by matching as many repetitions as can be found.
  299.      For example:
  300.  
  301.           awk '/\(c[ad][ad]*r x\)/ { print }' sample
  302.  
  303.      matches every record in the input containing a string of the
  304.      form `(car x)', `(cdr x)', `(cadr x)', and so on.
  305.  
  306. `+'
  307.      This symbol is similar to `*', but the preceding expression must
  308.      be matched at least once.  This means that:
  309.  
  310.           wh+y
  311.  
  312.      would match `why' and `whhy' but not `wy', whereas `wh*y' would
  313.      match all three of these strings.  And this is a simpler way of
  314.      writing the last `*' example:
  315.  
  316.           awk '/\(c[ad]+r x\)/ { print }' sample
  317.  
  318. `?'
  319.      This symbol is similar to `*', but the preceding expression can
  320.      be matched once or not at all.  For example:
  321.  
  322.           fe?d
  323.  
  324.      will match `fed' or `fd', but nothing else.
  325.  
  326. In regular expressions, the `*', `+', and `?' operators have the
  327. highest precedence, followed by concatenation, and finally by `|'. 
  328. As in arithmetic, parentheses can change how operators are grouped.
  329.  
  330. Any other character stands for itself.  However, it is important to
  331. note that case in regular expressions *is* significant, both when
  332. matching ordinary (i.e. non--metacharacter) characters, and inside
  333. character sets.  Thus a `w' in a regular expression matches only a
  334. lower case `w' and not either an uppercase or lowercase `w'.  When
  335. you want to do a case--independent match, you have to use a character
  336. set: `[Ww]'.
  337.  
  338.  
  339. 
  340. File: gawk-info,  Node: Comparison Patterns,  Next: Ranges,  Prev: Regexp,  Up: Patterns
  341.  
  342. Comparison Expressions as Patterns
  343. ==================================
  344.  
  345. "Comparison patterns" use "relational operators" to compare strings
  346. or numbers.  The relational operators are the same as in C.  Here is
  347. a table of them:
  348.  
  349. `X < Y'
  350.      True if X is less than Y.
  351.  
  352. `X <= Y'
  353.      True if X is less than or equal to Y.
  354.  
  355. `X > Y'
  356.      True if X is greater than Y.
  357.  
  358. `X >= Y'
  359.      True if X is greater than or equal to Y.
  360.  
  361. `X == Y'
  362.      True if X is equal to Y.
  363.  
  364. `X != Y'
  365.      True if X is not equal to Y.
  366.  
  367. Comparison expressions can be used as patterns to control whether a
  368. rule is executed.  The expression is evaluated for each input record
  369. read, and the pattern is considered matched if the condition is "true".
  370.  
  371. The operands of a relational operator are compared as numbers if they
  372. are both numbers.  Otherwise they are converted to, and compared as,
  373. strings (*note Conversion::.).  Strings are compared by comparing the
  374. first character of each, then the second character of each, and so on.
  375. Thus, `"10"' is less than `"9"'.
  376.  
  377. The following example prints the second field of each input record
  378. whose first field is precisely `foo'.
  379.  
  380.      awk '$1 == "foo" { print $2 }' BBS-list
  381.  
  382. Contrast this with the following regular expression match, which
  383. would accept any record with a first field that contains `foo':
  384.  
  385.      awk '$1 ~ "foo" { print $2 }' BBS-list
  386.  
  387.  
  388. 
  389. File: gawk-info,  Node: Ranges,  Next: BEGIN/END,  Prev: Comparison Patterns,  Up: Patterns
  390.  
  391. Specifying Record Ranges With Patterns
  392. ======================================
  393.  
  394. A "range pattern" is made of two patterns separated by a comma:
  395. `BEGPAT, ENDPAT'.  It matches ranges of consecutive input records. 
  396. The first pattern BEGPAT controls where the range begins, and the
  397. second one ENDPAT controls where it ends.
  398.  
  399. They work as follows: BEGPAT is matched against every input record;
  400. when a record matches BEGPAT, the range pattern becomes "turned on". 
  401. The range pattern matches this record.  As long as it stays turned
  402. on, it automatically matches every input record read.  But meanwhile,
  403. ENDPAT is matched against every input record, and when it matches,
  404. the range pattern is turned off again for the following record.  Now
  405. we go back to checking BEGPAT against each record.  For example:
  406.  
  407.      awk '$1 == "on", $1 == "off"'
  408.  
  409. prints every record between on/off pairs, inclusive.
  410.  
  411. The record that turns on the range pattern and the one that turns it
  412. off both match the range pattern.  If you don't want to operate on
  413. these records, you can write `if' statements in the rule's action to
  414. distinguish them.
  415.  
  416. It is possible for a pattern to be turned both on and off by the same
  417. record, if both conditions are satisfied by that record.  Then the
  418. action is executed for just that record.
  419.  
  420.  
  421. 
  422. File: gawk-info,  Node: BEGIN/END,  Next: Boolean,  Prev: Ranges,  Up: Patterns
  423.  
  424. `BEGIN' and `END' Special Patterns
  425. ==================================
  426.  
  427. `BEGIN' and `END' are special patterns.  They are not used to match
  428. input records.  Rather, they are used for supplying start--up or
  429. clean--up information to your `awk' script.  A `BEGIN' rule is
  430. executed, once, before the first input record has been read.  An
  431. `END' rule is executed, once, after all the input has been read.  For
  432. example:
  433.  
  434.      awk 'BEGIN { print "Analysis of ``foo'' program" }
  435.           /foo/ { ++foobar }
  436.           END   { print "``foo'' appears " foobar " times." }' BBS-list
  437.  
  438. This program finds out how many times the string `foo' appears in the
  439. input file `BBS-list'.  The `BEGIN' pattern prints out a title for
  440. the report.  There is no need to use the `BEGIN' pattern to
  441. initialize the counter `foobar' to zero, as `awk' does this for us
  442. automatically (*note Variables::.).  The second rule increments the
  443. variable `foobar' every time a record containing the pattern `foo' is
  444. read.  The last rule prints out the value of `foobar' at the end of
  445. the run.
  446.  
  447. The special patterns `BEGIN' and `END' do not combine with other
  448. kinds of patterns.
  449.  
  450. An `awk' program may have multiple `BEGIN' and/or `END' rules.  The
  451. contents of multiple `BEGIN' or `END' rules are treated as if they
  452. had been enclosed in a single rule, in the order that the rules are
  453. encountered in the `awk' program.  (This feature was introduced with
  454. the new version of `awk'.)
  455.  
  456. Multiple `BEGIN' and `END' sections are also useful for writing
  457. library functions that need to do initialization and/or cleanup of
  458. their own.  Note that the order in which library functions are named
  459. on the command line will affect the order in which their `BEGIN' and
  460. `END' rules will be executed.  Therefore you have to be careful how
  461. you write your library functions.  (*Note Command Line::, for more
  462. information on using library functions.)
  463.  
  464. If an `awk' program only has a `BEGIN' rule, and no other rules, then
  465. the program will exit after the `BEGIN' rule has been run.  Older
  466. versions of `awk' used to read their input until end of file was
  467. seen.  However, if an `END' rule exists as well, then the input will
  468. be read, even if there are no other rules in the program.
  469.  
  470. `BEGIN' and `END' rules must have actions; there is no default action
  471. for these rules since there is no current record when they run.
  472.  
  473.  
  474. 
  475. File: gawk-info,  Node: Boolean,  Next: Conditional Patterns,  Prev: BEGIN/END,  Up: Patterns
  476.  
  477. Boolean Operators and Patterns
  478. ==============================
  479.  
  480. A boolean pattern is a combination of other patterns using the
  481. boolean operators ``or'' (`||'), ``and'' (`&&'), and ``not'' (`!'),
  482. along with parentheses to control nesting.  Whether the boolean
  483. pattern matches an input record is computed from whether its
  484. subpatterns match.
  485.  
  486. The subpatterns of a boolean pattern can be regular expressions,
  487. matching expressions, comparisons, or other boolean combinations of
  488. such.  Range patterns cannot appear inside boolean operators, since
  489. they don't make sense for classifying a single record, and neither
  490. can the special patterns `BEGIN' and `END', which never match any
  491. input record.
  492.  
  493. Here are descriptions of the three boolean operators.
  494.  
  495. `PAT1 && PAT2'
  496.      Matches if both PAT1 and PAT2 match by themselves.  For example,
  497.      the following command prints all records in the input file
  498.      `BBS-list' that contain both `2400' and `foo'.
  499.  
  500.           awk '/2400/ && /foo/' BBS-list
  501.  
  502.      Whether PAT2 matches is tested only if PAT1 succeeds.  This can
  503.      make a difference when PAT2 contains expressions that have side
  504.      effects: in the case of `/foo/ && ($2 == bar++)', the variable
  505.      `bar' is not incremented if there is no `foo' in the record.
  506.  
  507. `PAT1 || PAT2'
  508.      Matches if at least one of PAT1 and PAT2 matches the current
  509.      input record.  For example, the following command prints all
  510.      records in the input file `BBS-list' that contain *either*
  511.      `2400' or `foo', or both.
  512.  
  513.           awk '/2400/ || /foo/' BBS-list
  514.  
  515.      Whether PAT2 matches is tested only if PAT1 fails to match. 
  516.      This can make a difference when PAT2 contains expressions that
  517.      have side effects.
  518.  
  519. `!PAT'
  520.      Matches if PAT does not match.  For example, the following
  521.      command prints all records in the input file `BBS-list' that do
  522.      *not* contain the string `foo'.
  523.  
  524.           awk '! /foo/' BBS-list
  525.  
  526. Note that boolean patterns are built from other patterns just as
  527. boolean expressions are built from other expressions (*note Boolean
  528. Ops::.).  Any boolean expression is also a valid boolean pattern. 
  529. But the converse is not true: simple regular expression patterns such
  530. as `/foo/' are not allowed in boolean expressions.  Regular
  531. expressions can appear in boolean expressions only in conjunction
  532. with the matching operators, `~' and `!~'.
  533.  
  534.  
  535. 
  536. File: gawk-info,  Node: Conditional Patterns,  Prev: Boolean,  Up: Patterns
  537.  
  538. Conditional Patterns
  539. ====================
  540.  
  541. Patterns may use a "conditional expression" much like the conditional
  542. expression of the C language.  This takes the form:
  543.  
  544.      PAT1 ? PAT2 : PAT3
  545.  
  546. The first pattern is evaluated.  If it evaluates to TRUE, then the
  547. input record is tested against PAT2.  Otherwise it is tested against
  548. PAT3.  The conditional pattern matches if PAT2 or PAT3 (whichever one
  549. is selected) matches.
  550.  
  551.  
  552. 
  553. File: gawk-info,  Node: Actions,  Next: Expressions,  Prev: Patterns,  Up: Top
  554.  
  555. Actions: The Basics
  556. *******************
  557.  
  558. The "action" part of an `awk' rule tells `awk' what to do once a
  559. match for the pattern is found.  An action consists of one or more
  560. `awk' "statements", enclosed in curly braces (`{' and `}').  The
  561. curly braces must be used even if the action contains only one
  562. statement, or even if it contains no statements at all.  Action
  563. statements are separated by newlines or semicolons.
  564.  
  565. Besides the print statements already covered (*note Printing::.),
  566. there are four kinds of action statements: expressions, control
  567. statements, compound statements, and function definitions.
  568.  
  569.    * "Expressions" include assignments, arithmetic, function calls,
  570.      and more (*note Expressions::.).
  571.  
  572.    * "Control statements" specify the control flow of `awk' programs.
  573.      The `awk' language gives you C--like constructs (`if', `for',
  574.      `while', and so on) as well as a few special ones (*note
  575.      Statements::.).
  576.  
  577.    * A "compound statement" is just one or more `awk' statements
  578.      enclosed in curly braces.  This way you can group several
  579.      statements to form the body of an `if' or similar statement.
  580.  
  581.    * You can define "user--defined functions" for use elsewhere in
  582.      the `awk' program (*note User-defined::.).
  583.  
  584.  
  585. 
  586. File: gawk-info,  Node: Expressions,  Next: Statements,  Prev: Actions,  Up: Top
  587.  
  588. Actions: Expressions
  589. ********************
  590.  
  591. Expressions are the basic building block of `awk' actions.  An
  592. expression evaluates to a value, which you can print, test, store in
  593. a variable or pass to a function.
  594.  
  595. But, beyond that, an expression can assign a new value to a variable
  596. or a field, with an assignment operator.
  597.  
  598. An expression can serve as a statement on its own.  Most other action
  599. statements are made up of various combinations of expressions.  As in
  600. other languages, expressions in `awk' include variables, array
  601. references, constants, and function calls, as well as combinations of
  602. these with various operators.
  603.  
  604. * Menu:
  605.  
  606. * Constants::       String and numeric constants.
  607. * Variables::       Variables give names to values for future use.
  608. * Fields::          Field references such as `$1' are also expressions.
  609. * Arrays::          Array element references are expressions.
  610.  
  611. * Arithmetic Ops::  Arithmetic operations (`+', `-', etc.)
  612. * Concatenation::   Concatenating strings.
  613. * Comparison Ops::  Comparison of numbers and strings with `<', etc.
  614. * Boolean Ops::     Combining comparison expressions using boolean operators
  615.                      `||' (``or''), `&&' (``and'') and `!' (``not'').
  616.  
  617. * Assignment Ops::  Changing the value of a variable or a field.
  618. * Increment Ops::   Incrementing the numeric value of a variable.
  619.  
  620. * Conversion::      The conversion of strings to numbers and vice versa.
  621. * Conditional Exp:: Conditional expressions select between two subexpressions
  622.                      under control of a third subexpression.
  623. * Function Calls::  A function call is an expression.
  624.  
  625.  
  626. 
  627. File: gawk-info,  Node: Constants,  Next: Variables,  Up: Expressions
  628.  
  629. Constant Expressions
  630. ====================
  631.  
  632. There are two types of constants: numeric constants and string
  633. constants.
  634.  
  635. The "numeric constant" is a number.  This number can be an integer, a
  636. decimal fraction, or a number in scientific (exponential) notation. 
  637. Note that all numeric values are represented within `awk' in
  638. double--precision floating point.  Here are some examples of numeric
  639. constants, which all have the same value:
  640.  
  641.      105
  642.      1.05e+2
  643.      1050e-1
  644.  
  645. A string constant consists of a sequence of characters enclosed in
  646. double--quote marks.  For example:
  647.  
  648.      "parrot"
  649.  
  650. represents the string constant `parrot'.  Strings in `gawk' can be of
  651. any length and they can contain all the possible 8--bit ASCII
  652. characters including ASCII NUL.  Other `awk' implementations may have
  653. difficulty with some character codes.
  654.  
  655. Some characters cannot be included literally in a string.  You
  656. represent them instead with "escape sequences", which are character
  657. sequences beginning with a backslash (`\').
  658.  
  659. One use of the backslash is to include double--quote characters in a
  660. string.  Since a plain double--quote would end the string, you must
  661. use `\"'.  Backslash itself is another character that can't be
  662. included normally; you write `\\' to put one backslash in the string.
  663.  
  664. Another use of backslash is to represent unprintable characters such
  665. as newline.  While there is nothing to stop you from writing these
  666. characters directly in an `awk' program, they may look ugly.
  667.  
  668. `\b'
  669.      Represents a backspaced,  H'.
  670.  
  671. `\f'
  672.      Represents a formfeed,  L'.
  673.  
  674. `\n'
  675.      Represents a newline,  J'.
  676.  
  677. `\r'
  678.      Represents a carriage return,  M'.
  679.  
  680. `\t'
  681.      Represents a horizontal tab,  I'.
  682.  
  683. `\v'
  684.      Represents a vertical tab,  K'.
  685.  
  686. `\NNN'
  687.      Represents the octal value NNN, where NNN is one to three digits
  688.      between 0 and 7.  For example, the code for the ASCII ESC
  689.      (escape) character is `\033'.
  690.  
  691.  
  692. 
  693. File: gawk-info,  Node: Variables,  Next: Arithmetic Ops,  Prev: Constants,  Up: Expressions
  694.  
  695. Variables
  696. =========
  697.  
  698. Variables let you give names to values and refer to them later.  You
  699. have already seen variables in many of the examples.  The name of a
  700. variable must be a sequence of letters, digits and underscores, but
  701. it may not begin with a digit.  Case is significant in variable
  702. names; `a' and `A' are distinct variables.
  703.  
  704. A variable name is a valid expression by itself; it represents the
  705. variable's current value.  Variables are given new values with
  706. "assignment operators" and "increment operators".  *Note Assignment
  707. Ops::.
  708.  
  709. A few variables have special built--in meanings, such as `FS', the
  710. field separator, and `NF', the number of fields in the current input
  711. record.  *Note Special::, for a list of them.  Special variables can
  712. be used and assigned just like all other variables, but their values
  713. are also used or changed automatically by `awk'.  Each special
  714. variable's name is made entirely of upper case letters.
  715.  
  716. Variables in `awk' can be assigned either numeric values or string
  717. values.  By default, variables are initialized to the null string,
  718. which has the numeric value zero.  So there is no need to
  719. ``initialize'' each variable explicitly in `awk', the way you would
  720. need to do in C or most other traditional programming languages.
  721.  
  722.  
  723. 
  724. File: gawk-info,  Node: Arithmetic Ops,  Next: Concatenation,  Prev: Variables,  Up: Expressions
  725.  
  726. Arithmetic Operators
  727. ====================
  728.  
  729. The `awk' language uses the common arithmetic operators when
  730. evaluating expressions.  All of these arithmetic operators follow
  731. normal precedence rules, and work as you would expect them to.  This
  732. example divides field 3 by field 4, adds field 2, stores the result
  733. into field 1, and prints the results:
  734.  
  735.      awk '{ $1 = $2 + $3 / $4; print }' inventory-shipped
  736.  
  737. The arithmetic operators in `awk' are:
  738.  
  739. `X + Y'
  740.      Addition.
  741.  
  742. `X - Y'
  743.      Subtraction.
  744.  
  745. `- X'
  746.      Negation.
  747.  
  748. `X / Y'
  749.      Division.  Since all numbers in `awk' are double--precision
  750.      floating point, the result is not rounded to an integer: `3 / 4'
  751.      has the value 0.75.
  752.  
  753. `X * Y'
  754.      Multiplication.
  755.  
  756. `X % Y'
  757.      Remainder.  The quotient is rounded toward zero to an integer,
  758.      multiplied by Y and this result is subtracted from X.  This
  759.      operation is sometimes known as ``trunc--mod''.  The following
  760.      relation always holds:
  761.  
  762.           `b * int(a / b) + (a % b) == a'
  763.  
  764.      One undesirable effect of this definition of remainder is that X
  765.      % Y is negative if X is negative.  Thus,
  766.  
  767.           -17 % 8 = -1
  768.  
  769. `X ^ Y'
  770. `X ** Y'
  771.      Exponentiation: X raised to the Y power.  `2 ^ 3' has the value
  772.      8.  The character sequence `**' is equivalent to `^'.
  773.  
  774.  
  775. 
  776. File: gawk-info,  Node: Concatenation,  Next: Comparison Ops,  Prev: Arithmetic Ops,  Up: Expressions
  777.  
  778. String Concatenation
  779. ====================
  780.  
  781. There is only one string operation: concatenation.  It does not have
  782. a specific operator to represent it.  Instead, concatenation is
  783. performed by writing expressions next to one another, with no
  784. operator.  For example:
  785.  
  786.      awk '{ print "Field number one: " $1 }' BBS-list
  787.  
  788. produces, for the first record in `BBS-list':
  789.  
  790.      Field number one: aardvark
  791.  
  792. If you hadn't put the space after the `:', the line would have run
  793. together.  For example:
  794.  
  795.      awk '{ print "Field number one:" $1 }' BBS-list
  796.  
  797. produces, for the first record in `BBS-list':
  798.  
  799.      Field number one:aardvark
  800.  
  801.  
  802. 
  803. File: gawk-info,  Node: Comparison Ops,  Next: Boolean Ops,  Prev: Concatenation,  Up: Expressions
  804.  
  805. Comparison Expressions
  806. ======================
  807.  
  808. "Comparison expressions" use "relational operators" to compare
  809. strings or numbers.  The relational operators are the same as in C. 
  810. Here is a table of them:
  811.  
  812. `X < Y'
  813.      True if X is less than Y.
  814.  
  815. `X <= Y'
  816.      True if X is less than or equal to Y.
  817.  
  818. `X > Y'
  819.      True if X is greater than Y.
  820.  
  821. `X >= Y'
  822.      True if X is greater than or equal to Y.
  823.  
  824. `X == Y'
  825.      True if X is equal to Y.
  826.  
  827. `X != Y'
  828.      True if X is not equal to Y.
  829.  
  830. `X ~ REGEXP'
  831.      True if regexp REGEXP matches the string X.
  832.  
  833. `X !~ REGEXP'
  834.      True if regexp REGEXP does not match the string X.
  835.  
  836. `SUBSCRIPT in ARRAY'
  837.      True if array ARRAY has an element with the subscript SUBSCRIPT.
  838.  
  839. Comparison expressions have the value 1 if true and 0 if false.
  840.  
  841. The operands of a relational operator are compared as numbers if they
  842. are both numbers.  Otherwise they are converted to, and compared as,
  843. strings (*note Conversion::.).  Strings are compared by comparing the
  844. first character of each, then the second character of each, and so on.
  845. Thus, `"10"' is less than `"9"'.
  846.  
  847. For example,
  848.  
  849.      $1 == "foo"
  850.  
  851. has the value of 1, or is true, if the first field of the current
  852. input record is precisely `foo'.  By contrast,
  853.  
  854.      $1 ~ /foo/
  855.  
  856. has the value 1 if the first field contains `foo'.
  857.  
  858.  
  859. 
  860. File: gawk-info,  Node: Boolean Ops,  Next: Assignment Ops,  Prev: Comparison Ops,  Up: Expressions
  861.  
  862. Boolean Operators
  863. =================
  864.  
  865. A boolean expression is combination of comparison expressions or
  866. matching expressions, using the boolean operators ``or'' (`||'),
  867. ``and'' (`&&'), and ``not'' (`!'), along with parentheses to control
  868. nesting.  The truth of the boolean expression is computed by
  869. combining the truth values of the component expressions.
  870.  
  871. Boolean expressions can be used wherever comparison and matching
  872. expressions can be used.  They can be used in `if' and `while'
  873. statements.  They have numeric values (1 if true, 0 if false).
  874.  
  875. In addition, every boolean expression is also a valid boolean
  876. pattern, so you can use it as a pattern to control the execution of
  877. rules.
  878.  
  879. Here are descriptions of the three boolean operators, with an example
  880. of each.  It may be instructive to compare these examples with the
  881. analogous examples of boolean patterns (*note Boolean::.), which use
  882. the same boolean operators in patterns instead of expressions.
  883.  
  884. `BOOLEAN1 && BOOLEAN2'
  885.      True if both BOOLEAN1 and BOOLEAN2 are true.  For example, the
  886.      following statement prints the current input record if it
  887.      contains both `2400' and `foo'.
  888.  
  889.           if ($0 ~ /2400/ && $0 ~ /foo/) print
  890.  
  891.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is
  892.      true.  This can make a difference when BOOLEAN2 contains
  893.      expressions that have side effects: in the case of `$0 ~ /foo/
  894.      && ($2 == bar++)', the variable `bar' is not incremented if
  895.      there is no `foo' in the record.
  896.  
  897. `BOOLEAN1 || BOOLEAN2'
  898.      True if at least one of BOOLEAN1 and BOOLEAN2 is true.  For
  899.      example, the following command prints all records in the input
  900.      file `BBS-list' that contain *either* `2400' or `foo', or both.
  901.  
  902.           awk '{ if ($0 ~ /2400/ || $0 ~ /foo/) print }' BBS-list
  903.  
  904.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is
  905.      true.  This can make a difference when BOOLEAN2 contains
  906.      expressions that have side effects.
  907.  
  908. `!BOOLEAN'
  909.      True if BOOLEAN is false.  For example, the following program
  910.      prints all records in the input file `BBS-list' that do *not*
  911.      contain the string `foo'.
  912.  
  913.           awk '{ if (! ($0 ~ /foo/)) print }' BBS-list
  914.  
  915.  
  916. 
  917. File: gawk-info,  Node: Assignment Ops,  Next: Increment Ops,  Prev: Boolean Ops,  Up: Expressions
  918.  
  919. Assignment Operators
  920. ====================
  921.  
  922. An "assignment" is an expression that stores a new value into a
  923. variable.  For example, let's assign the value 1 to the variable `z':
  924.  
  925.      z = 1
  926.  
  927. After this expression is executed, the variable `z' has the value 1. 
  928. Whatever old value `z' had before the assignment is forgotten.
  929.  
  930. The `=' sign is called an "assignment operator".  It is the simplest
  931. assignment operator because the value of the right--hand operand is
  932. stored unchanged.
  933.  
  934. The left--hand operand of an assignment can be a variable (*note
  935. Variables::.), a field (*note Changing Fields::.) or an array element
  936. (*note Arrays::.).  These are all called "lvalues", which means they
  937. can appear on the left side of an assignment operator.  The
  938. right--hand operand may be any expression; it produces the new value
  939. which the assignment stores in the specified variable, field or array
  940. element.
  941.  
  942. Assignments can store string values also.  For example, this would
  943. store the value `"this food is good"' in the variable `message':
  944.  
  945.      thing = "food"
  946.      predicate = "good"
  947.      message = "this " thing " is " predicate
  948.  
  949. (This also illustrates concatenation of strings.)
  950.  
  951. It is important to note that variables do *not* have permanent types.
  952. The type of a variable is simply the type of whatever value it
  953. happens to hold at the moment.  In the following program fragment,
  954. the variable `foo' has a numeric value at first, and a string value
  955. later on:
  956.  
  957.      foo = 1
  958.      print foo
  959.      foo = "bar"
  960.      print foo
  961.  
  962. When the second assignment gives `foo' a string value, the fact that
  963. it previously had a numeric value is forgotten.
  964.  
  965. An assignment is an expression, so it has a value: the same value
  966. that is assigned.  Thus, `z = 1' as an expression has the value 1. 
  967. One consequence of this is that you can write multiple assignments
  968. together:
  969.  
  970.      x = y = z = 0
  971.  
  972. stores the value 0 in all three variables.  It does this because the
  973. value of `z = 0', which is 0, is stored into `y', and then the value
  974. of `y = z = 0', which is 0, is stored into `x'.
  975.  
  976. You can use an assignment anywhere an expression is called for.  For
  977. example, it is valid to write `x != (y = 1)' to set `y' to 1 and then
  978. test whether `x' equals 1.  But this style tends to make programs
  979. hard to read; except in a one--shot program, you should rewrite it to
  980. get rid of such nesting of assignments.  This is never very hard.
  981.  
  982. Aside from `=', there are several other assignment operators that do
  983. arithmetic with the old value of the variable.  For example, the
  984. operator `+=' computes a new value by adding the right--hand value to
  985. the old value of the variable.  Thus, the following assignment adds 5
  986. to the value of `foo':
  987.  
  988.      foo += 5
  989.  
  990. This is precisely equivalent to the following:
  991.  
  992.      foo = foo + 5
  993.  
  994. Use whichever one makes the meaning of your program clearer.
  995.  
  996. Here is a table of the arithmetic assignment operators.  In each
  997. case, the right--hand operand is an expression whose value is
  998. converted to a number.
  999.  
  1000. `LVALUE += INCREMENT'
  1001.      Adds INCREMENT to the value of LVALUE to make the new value of
  1002.      LVALUE.
  1003.  
  1004. `LVALUE -= DECREMENT'
  1005.      Subtracts DECREMENT from the value of LVALUE.
  1006.  
  1007. `LVALUE *= COEFFICIENT'
  1008.      Multiplies the value of LVALUE by COEFFICIENT.
  1009.  
  1010. `LVALUE /= QUOTIENT'
  1011.      Divides the value of LVALUE by QUOTIENT.
  1012.  
  1013. `LVALUE %= MODULUS'
  1014.      Sets LVALUE to its remainder by MODULUS.
  1015.  
  1016. `LVALUE ^= POWER'
  1017. `LVALUE **= POWER'
  1018.      Raises LVALUE to the power POWER.
  1019.  
  1020.  
  1021. 
  1022. File: gawk-info,  Node: Increment Ops,  Next: Conversion,  Prev: Assignment Ops,  Up: Expressions
  1023.  
  1024. Increment Operators
  1025. ===================
  1026.  
  1027. "Increment operators" increase or decrease the value of a variable by
  1028. 1.  You could do the same thing with an assignment operator, so the
  1029. increment operators add no power to the `awk' language; but they are
  1030. convenient abbreviations for something very common.
  1031.  
  1032. The operator to add 1 is written `++'.  There are two ways to use
  1033. this operator: pre--incrementation and post--incrementation.
  1034.  
  1035. To pre--increment a variable V, write `++V'.  This adds 1 to the
  1036. value of V and that new value is also the value of this expression. 
  1037. The assignment expression `V += 1' is completely equivalent.
  1038.  
  1039. Writing the `++' after the variable specifies post--increment.  This
  1040. increments the variable value just the same; the difference is that
  1041. the value of the increment expression itself is the variable's *old*
  1042. value.  Thus, if `foo' has value 4, then the expression `foo++' has
  1043. the value 4, but it changes the value of `foo' to 5.
  1044.  
  1045. The post--increment `foo++' is nearly equivalent to writing `(foo +=
  1046. 1) - 1'.  It is not perfectly equivalent because all numbers in `awk'
  1047. are floating point: in floating point, `foo + 1 - 1' does not
  1048. necessarily equal `foo'.  But the difference will be minute as long
  1049. as you stick to numbers that are fairly small (less than a trillion).
  1050.  
  1051. Any lvalue can be incremented.  Fields and array elements are
  1052. incremented just like variables.
  1053.  
  1054. The decrement operator `--' works just like `++' except that it
  1055. subtracts 1 instead of adding.  Like `++', it can be used before the
  1056. lvalue to pre--decrement or after it to post--decrement.
  1057.  
  1058. Here is a summary of increment and decrement expressions.
  1059.  
  1060. `++LVALUE'
  1061.      This expression increments LVALUE and the new value becomes the
  1062.      value of this expression.
  1063.  
  1064. `LVALUE++'
  1065.      This expression causes the contents of LVALUE to be incremented.
  1066.      The value of the expression is the *old* value of LVALUE.
  1067.  
  1068. `--LVALUE'
  1069.      Like `++LVALUE', but instead of adding, it subtracts.  It
  1070.      decrements LVALUE and delivers the value that results.
  1071.  
  1072. `LVALUE--'
  1073.      Like `LVALUE++', but instead of adding, it subtracts.  It
  1074.      decrements LVALUE. The value of the expression is the *old*
  1075.      value of LVALUE.
  1076.  
  1077.  
  1078. 
  1079. File: gawk-info,  Node: Conversion,  Next: Conditional Exp,  Prev: Increment Ops,  Up: Expressions
  1080.  
  1081. Conversion of Strings and Numbers
  1082. =================================
  1083.  
  1084. Strings are converted to numbers, and numbers to strings, if the
  1085. context of your `awk' statement demands it.  For example, if the
  1086. values of `foo' or `bar' in the expression `foo + bar' happen to be
  1087. strings, they are converted to numbers before the addition is
  1088. performed.  If numeric values appear in string concatenation, they
  1089. are converted to strings.  Consider this:
  1090.  
  1091.      two = 2; three = 3
  1092.      print (two three) + 4
  1093.  
  1094. This eventually prints the (numeric) value `27'.  The numeric
  1095. variables `two' and `three' are converted to strings and concatenated
  1096. together, and the resulting string is converted back to a number
  1097. before adding `4'.  The resulting numeric value `27' is printed.
  1098.  
  1099. If, for some reason, you need to force a number to be converted to a
  1100. string, concatenate the null string with that number.  To force a
  1101. string to be converted to a number, add zero to that string.  Strings
  1102. that can't be interpreted as valid numbers are given the numeric
  1103. value zero.
  1104.  
  1105. The exact manner in which numbers are converted into strings is
  1106. controlled by the `awk' special variable `OFMT' (*note Special::.). 
  1107. Numbers are converted using a special version of the `sprintf'
  1108. function (*note Built-in::.) with `OFMT' as the format specifier.
  1109.  
  1110. `OFMT''s default value is `"%.6g"', which prints a value with at
  1111. least six significant digits.  You might want to change it to specify
  1112. more precision, if your version of `awk' uses double precision
  1113. arithmetic.  Double precision on most modern machines gives you 16 or
  1114. 17 decimal digits of precision.
  1115.  
  1116. Strange results can happen if you set `OFMT' to a string that doesn't
  1117. tell `sprintf' how to format floating point numbers in a useful way. 
  1118. For example, if you forget the `%' in the format, all numbers will be
  1119. converted to the same constant string.
  1120.  
  1121.  
  1122. 
  1123. File: gawk-info,  Node: Conditional Exp,  Next: Function Calls,  Prev: Conversion,  Up: Expressions
  1124.  
  1125. Conditional Expressions
  1126. =======================
  1127.  
  1128. A "conditional expression" is a special kind of expression with three
  1129. operands.  It allows you to use one expression's value to select one
  1130. of two other expressions.
  1131.  
  1132. The conditional expression looks the same as in the C language:
  1133.  
  1134.      SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP
  1135.  
  1136. There are three subexpressions.  The first, SELECTOR, is always
  1137. computed first.  If it is ``true'' (not zero) then IF-TRUE-EXP is
  1138. computed next and its value becomes the value of the whole expression.
  1139. Otherwise, IF-FALSE-EXP is computed next and its value becomes the
  1140. value of the whole expression.
  1141.  
  1142. For example, this expression produces the absolute value of `x':
  1143.  
  1144.      x > 0 ? x : -x
  1145.  
  1146. Each time the conditional expression is computed, exactly one of
  1147. IF-TRUE-EXP and IF-FALSE-EXP is computed; the other is ignored.  This
  1148. is important when the expressions contain side effects.  For example,
  1149. this conditional expression examines element `i' of either array `a'
  1150. or array `b', and increments `i'.
  1151.  
  1152.      x == y ? a[i++] : b[i++]
  1153.  
  1154. This is guaranteed to increment `i' exactly once, because each time
  1155. one or the other of the two increment expressions will be executed
  1156. and the other will not be.
  1157.  
  1158.  
  1159. 
  1160. File: gawk-info,  Node: Function Calls,  Prev: Conditional Exp,  Up: Expressions
  1161.  
  1162. Function Calls
  1163. ==============
  1164.  
  1165. A "function" is a name for a particular calculation.  Because it has
  1166. a name, you can ask for it by name at any point in the program.  For
  1167. example, the function `sqrt' computes the square root of a number.
  1168.  
  1169. A fixed set of functions are "built in", which means they are
  1170. available in every `awk' program.  The `sqrt' function is one of
  1171. these.  *Note Built-in::, for a list of built--in functions and their
  1172. descriptions.  In addition, you can define your own functions in the
  1173. program for use elsewhere in the same program.  *Note User-defined::,
  1174. for how to do this.
  1175.  
  1176. The way to use a function is with a "function call" expression, which
  1177. consists of the function name followed by a list of "arguments" in
  1178. parentheses.  The arguments are expressions which give the raw
  1179. materials for the calculation that the function will do.  When there
  1180. is more than one argument, they are separated by commas.  If there
  1181. are no arguments, write just `()' after the function name.
  1182.  
  1183. *Do not put any space between the function name and the
  1184. open--parenthesis!*  A user--defined function name looks just like
  1185. the name of a variable, and space would make the expression look like
  1186. concatenation of a variable with an expression inside parentheses. 
  1187. Space before the parenthesis is harmless with built--in functions,
  1188. but it is best not to get into the habit of using space, lest you do
  1189. likewise for a user--defined function one day by mistake.
  1190.  
  1191. Each function needs a particular number of arguments.  For example,
  1192. the `sqrt' function must be called with a single argument, like this:
  1193.  
  1194.      sqrt(ARGUMENT)
  1195.  
  1196. The argument is the number to take the square root of.
  1197.  
  1198. Some of the built--in functions allow you to omit the final argument.
  1199. If you do so, they will use a reasonable default.  *Note Built-in::,
  1200. for full details.  If arguments are omitted in calls to user--defined
  1201. functions, then those arguments are treated as local variables,
  1202. initialized to the null string (*note User-defined::.).
  1203.  
  1204. Like every other expression, the function call has a value, which is
  1205. computed by the function based on the arguments you give it.  In this
  1206. example, the value of `sqrt(ARGUMENT)' is the square root of the
  1207. argument.  A function can also have side effects, such as assigning
  1208. the values of certain variables or doing I/O.
  1209.  
  1210. Here is a command to read numbers, one number per line, and print the
  1211. square root of each one:
  1212.  
  1213.      awk '{ print "The square root of", $1, "is", sqrt($1) }'
  1214.  
  1215.  
  1216. 
  1217. File: gawk-info,  Node: Statements,  Next: Arrays,  Prev: Expressions,  Up: Top
  1218.  
  1219. Actions: Statements
  1220. *******************
  1221.  
  1222. "Control statements" such as `if', `while', and so on control the
  1223. flow of execution in `awk' programs.  Most of the control statements
  1224. in `awk' are patterned on similar statements in C.
  1225.  
  1226. The simplest kind of statement is an expression.  The other kinds of
  1227. statements start with special keywords such as `if' and `while', to
  1228. distinguish them from simple expressions.
  1229.  
  1230. In all the examples in this chapter, BODY can be either a single
  1231. statement or a group of statements.  Groups of statements are
  1232. enclosed in braces, and separated by newlines or semicolons.
  1233.  
  1234. * Menu:
  1235.  
  1236. * Expressions:: One kind of statement simply computes an expression.
  1237.  
  1238. * If::         Conditionally execute some `awk' statements.
  1239.  
  1240. * While::      Loop until some condition is satisfied.
  1241.  
  1242. * Do::         Do specified action while looping until some
  1243.                condition is satisfied.
  1244.  
  1245. * For::        Another looping statement, that provides
  1246.                initialization and increment clauses.
  1247.  
  1248. * Break::      Immediately exit the innermost enclosing loop.
  1249.  
  1250. * Continue::   Skip to the end of the innermost enclosing loop.
  1251.  
  1252. * Next::       Stop processing the current input record.
  1253.  
  1254. * Exit::       Stop execution of `awk'.
  1255.  
  1256.  
  1257. 
  1258. File: gawk-info,  Node: If,  Next: While,  Up: Statements
  1259.  
  1260. The `if' Statement
  1261. ==================
  1262.  
  1263. The `if'-`else' statement is `awk''s decision--making statement.  The
  1264. `else' part of the statement is optional.
  1265.  
  1266.      `if (CONDITION) BODY1 else BODY2'
  1267.  
  1268. Here CONDITION is an expression that controls what the rest of the
  1269. statement will do.  If CONDITION is true, BODY1 is executed;
  1270. otherwise, BODY2 is executed (assuming that the `else' clause is
  1271. present).  The condition is considered true if it is nonzero or
  1272. nonnull.
  1273.  
  1274. Here is an example:
  1275.  
  1276.      awk '{ if (x % 2 == 0)
  1277.                 print "x is even"
  1278.             else
  1279.                 print "x is odd" }'
  1280.  
  1281. In this example, if the statement containing `x' is found to be true
  1282. (that is, x is divisible by 2), then the first `print' statement is
  1283. executed, otherwise the second `print' statement is performed.
  1284.  
  1285. If the `else' appears on the same line as BODY1, and BODY1 is a
  1286. single statement, then a semicolon must separate BODY1 from `else'. 
  1287. To illustrate this, let's rewrite the previous example:
  1288.  
  1289.      awk '{ if (x % 2 == 0) print "x is even"; else
  1290.              print "x is odd" }'
  1291.  
  1292. If you forget the `;', `awk' won't be able to parse it, and you will
  1293. get a syntax error.
  1294.  
  1295. We would not actually write this example this way, because a human
  1296. reader might fail to see the `else' if it were not the first thing on
  1297. its line.
  1298.  
  1299.  
  1300. 
  1301. File: gawk-info,  Node: While,  Next: Do,  Prev: If,  Up: Statements
  1302.  
  1303. The `while' Statement
  1304. =====================
  1305.  
  1306. In programming, a loop means a part of a program that is (or at least
  1307. can be) executed two or more times in succession.
  1308.  
  1309. The `while' statement is the simplest looping statement in `awk'.  It
  1310. repeatedly executes a statement as long as a condition is true.  It
  1311. looks like this:
  1312.  
  1313.      while (CONDITION)
  1314.        BODY
  1315.  
  1316. Here BODY is a statement that we call the "body" of the loop, and
  1317. CONDITION is an expression that controls how long the loop keeps
  1318. running.
  1319.  
  1320. The first thing the `while' statement does is test CONDITION.  If
  1321. CONDITION is true, it executes the statement BODY.  After BODY has
  1322. been executed, CONDITION is tested again and this process is repeated
  1323. until CONDITION is no longer true.  If CONDITION is initially false,
  1324. the body of the loop is never executed.
  1325.  
  1326.      awk '{ i = 1
  1327.             while (i <= 3) {
  1328.                 print $i
  1329.                 i++
  1330.             }
  1331.      }'
  1332.  
  1333. This example prints the first three input fields, one per line.
  1334.  
  1335. The loop works like this: first, the value of `i' is set to 1.  Then,
  1336. the `while' tests whether `i' is less than or equal to three.  This
  1337. is the case when `i' equals one, so the `i'-th field is printed. 
  1338. Then the `i++' increments the value of `i' and the loop repeats.
  1339.  
  1340. When `i' reaches 4, the loop exits.  Here BODY is a compound
  1341. statement enclosed in braces.  As you can see, a newline is not
  1342. required between the condition and the body; but using one makes the
  1343. program clearer unless the body is a compound statement or is very
  1344. simple.
  1345.  
  1346.  
  1347. 
  1348. File: gawk-info,  Node: Do,  Next: For,  Prev: While,  Up: Statements
  1349.  
  1350. The `do'--`while' Statement
  1351. ===========================
  1352.  
  1353. The `do' loop is a variation of the `while' looping statement.  The
  1354. `do' loop executes the BODY once, then repeats BODY as long as
  1355. CONDITION is true.  It looks like this:
  1356.  
  1357.      do
  1358.        BODY
  1359.      while (CONDITION)
  1360.  
  1361. Even if CONDITION is false at the start, BODY is executed at least
  1362. once (and only once, unless executing BODY makes CONDITION true). 
  1363. Contrast this with the corresponding `while' statement:
  1364.  
  1365.      while (CONDITION)
  1366.        BODY
  1367.  
  1368. This statement will not execute BODY even once if CONDITION is false
  1369. to begin with.
  1370.  
  1371. Here is an example of a `do' statement:
  1372.  
  1373.      awk '{ i = 1
  1374.             do {
  1375.                print $0
  1376.                i++
  1377.             } while (i <= 10)
  1378.      }'
  1379.  
  1380. prints each input record ten times.  It isn't a very realistic
  1381. example, since in this case an ordinary `while' would do just as
  1382. well.  But this is normal; there is only occasionally a real use for
  1383. a `do' statement.
  1384.  
  1385.  
  1386.