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

  1. This is Info file gawk.info, produced by Makeinfo-1.55 from the input
  2. file /gnu-src/gawk-2.15.6/gawk.texi.
  3.    This file documents `awk', a program that you can use to select
  4. particular records in a file and perform operations upon them.
  5.    This is Edition 0.15 of `The GAWK Manual',
  6. for the 2.15 version of the GNU implementation
  7. of AWK.
  8.    Copyright (C) 1989, 1991, 1992, 1993 Free Software Foundation, Inc.
  9.    Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: gawk.info,  Node: Actions,  Next: Expressions,  Prev: Patterns,  Up: Top
  21. Overview of Actions
  22. *******************
  23.    An `awk' program or script consists of a series of rules and
  24. function definitions, interspersed.  (Functions are described later.
  25. *Note User-defined Functions: User-defined.)
  26.    A rule contains a pattern and an action, either of which may be
  27. omitted.  The purpose of the "action" is to tell `awk' what to do once
  28. a match for the pattern is found.  Thus, the entire program looks
  29. somewhat like this:
  30.      [PATTERN] [{ ACTION }]
  31.      [PATTERN] [{ ACTION }]
  32.      ...
  33.      function NAME (ARGS) { ... }
  34.      ...
  35.    An action consists of one or more `awk' "statements", enclosed in
  36. curly braces (`{' and `}').  Each statement specifies one thing to be
  37. done.  The statements are separated by newlines or semicolons.
  38.    The curly braces around an action must be used even if the action
  39. contains only one statement, or even if it contains no statements at
  40. all.  However, if you omit the action entirely, omit the curly braces as
  41. well.  (An omitted action is equivalent to `{ print $0 }'.)
  42.    Here are the kinds of statements supported in `awk':
  43.    * Expressions, which can call functions or assign values to variables
  44.      (*note Expressions as Action Statements: Expressions.).  Executing
  45.      this kind of statement simply computes the value of the expression
  46.      and then ignores it.  This is useful when the expression has side
  47.      effects (*note Assignment Expressions: Assignment Ops.).
  48.    * Control statements, which specify the control flow of `awk'
  49.      programs.  The `awk' language gives you C-like constructs (`if',
  50.      `for', `while', and so on) as well as a few special ones (*note
  51.      Control Statements in Actions: Statements.).
  52.    * Compound statements, which consist of one or more statements
  53.      enclosed in curly braces.  A compound statement is used in order
  54.      to put several statements together in the body of an `if',
  55.      `while', `do' or `for' statement.
  56.    * Input control, using the `getline' command (*note Explicit Input
  57.      with `getline': Getline.), and the `next' statement (*note The
  58.      `next' Statement: Next Statement.).
  59.    * Output statements, `print' and `printf'.  *Note Printing Output:
  60.      Printing.
  61.    * Deletion statements, for deleting array elements.  *Note The
  62.      `delete' Statement: Delete.
  63. File: gawk.info,  Node: Expressions,  Next: Statements,  Prev: Actions,  Up: Top
  64. Expressions as Action Statements
  65. ********************************
  66.    Expressions are the basic building block of `awk' actions.  An
  67. expression evaluates to a value, which you can print, test, store in a
  68. variable or pass to a function.  But beyond that, an expression can
  69. assign a new value to a variable or a field, with an assignment
  70. operator.
  71.    An expression can serve as a statement on its own.  Most other kinds
  72. of statements contain one or more expressions which specify data to be
  73. operated on.  As in other languages, expressions in `awk' include
  74. variables, array references, constants, and function calls, as well as
  75. combinations of these with various operators.
  76. * Menu:
  77. * Constants::                   String, numeric, and regexp constants.
  78. * Variables::                   Variables give names to values for later use.
  79. * Arithmetic Ops::              Arithmetic operations (`+', `-', etc.)
  80. * Concatenation::               Concatenating strings.
  81. * Comparison Ops::              Comparison of numbers and strings
  82.                                 with `<', etc.
  83. * Boolean Ops::                 Combining comparison expressions
  84.                                 using boolean operators
  85.                                 `||' ("or"), `&&' ("and") and `!' ("not").
  86. * Assignment Ops::              Changing the value of a variable or a field.
  87. * Increment Ops::               Incrementing the numeric value of a variable.
  88. * Conversion::                  The conversion of strings to numbers
  89.                                 and vice versa.
  90. * Values::                      The whole truth about numbers and strings.
  91. * Conditional Exp::             Conditional expressions select
  92.                                 between two subexpressions under control
  93.                                 of a third subexpression.
  94. * Function Calls::              A function call is an expression.
  95. * Precedence::                  How various operators nest.
  96. File: gawk.info,  Node: Constants,  Next: Variables,  Prev: Expressions,  Up: Expressions
  97. Constant Expressions
  98. ====================
  99.    The simplest type of expression is the "constant", which always has
  100. the same value.  There are three types of constants: numeric constants,
  101. string constants, and regular expression constants.
  102.    A "numeric constant" stands for a number.  This number can be an
  103. integer, a decimal fraction, or a number in scientific (exponential)
  104. notation.  Note that all numeric values are represented within `awk' in
  105. double-precision floating point.  Here are some examples of numeric
  106. constants, which all have the same value:
  107.      105
  108.      1.05e+2
  109.      1050e-1
  110.    A string constant consists of a sequence of characters enclosed in
  111. double-quote marks.  For example:
  112.      "parrot"
  113. represents the string whose contents are `parrot'.  Strings in `gawk'
  114. can be of any length and they can contain all the possible 8-bit ASCII
  115. characters including ASCII NUL.  Other `awk' implementations may have
  116. difficulty with some character codes.
  117.    Some characters cannot be included literally in a string constant.
  118. You represent them instead with "escape sequences", which are character
  119. sequences beginning with a backslash (`\').
  120.    One use of an escape sequence is to include a double-quote character
  121. in a string constant.  Since a plain double-quote would end the string,
  122. you must use `\"' to represent a single double-quote character as a
  123. part of the string.  The backslash character itself is another
  124. character that cannot be included normally; you write `\\' to put one
  125. backslash in the string.  Thus, the string whose contents are the two
  126. characters `"\' must be written `"\"\\"'.
  127.    Another use of backslash is to represent unprintable characters such
  128. as newline.  While there is nothing to stop you from writing most of
  129. these characters directly in a string constant, they may look ugly.
  130.    Here is a table of all the escape sequences used in `awk':
  131.      Represents a literal backslash, `\'.
  132.      Represents the "alert" character, control-g, ASCII code 7.
  133.      Represents a backspace, control-h, ASCII code 8.
  134.      Represents a formfeed, control-l, ASCII code 12.
  135.      Represents a newline, control-j, ASCII code 10.
  136.      Represents a carriage return, control-m, ASCII code 13.
  137.      Represents a horizontal tab, control-i, ASCII code 9.
  138.      Represents a vertical tab, control-k, ASCII code 11.
  139. `\NNN'
  140.      Represents the octal value NNN, where NNN are one to three digits
  141.      between 0 and 7.  For example, the code for the ASCII ESC (escape)
  142.      character is `\033'.
  143. `\xHH...'
  144.      Represents the hexadecimal value HH, where HH are hexadecimal
  145.      digits (`0' through `9' and either `A' through `F' or `a' through
  146.      `f').  Like the same construct in ANSI C, the escape sequence
  147.      continues until the first non-hexadecimal digit is seen.  However,
  148.      using more than two hexadecimal digits produces undefined results.
  149.      (The `\x' escape sequence is not allowed in POSIX `awk'.)
  150.    A "constant regexp" is a regular expression description enclosed in
  151. slashes, such as `/^beginning and end$/'.  Most regexps used in `awk'
  152. programs are constant, but the `~' and `!~' operators can also match
  153. computed or "dynamic" regexps (*note How to Use Regular Expressions:
  154. Regexp Usage.).
  155.    Constant regexps may be used like simple expressions.  When a
  156. constant regexp is not on the right hand side of the `~' or `!~'
  157. operators, it has the same meaning as if it appeared in a pattern, i.e.
  158. `($0 ~ /foo/)' (*note Expressions as Patterns: Expression Patterns.).
  159. This means that the two code segments,
  160.      if ($0 ~ /barfly/ || $0 ~ /camelot/)
  161.          print "found"
  162.      if (/barfly/ || /camelot/)
  163.          print "found"
  164. are exactly equivalent.  One rather bizarre consequence of this rule is
  165. that the following boolean expression is legal, but does not do what
  166. the user intended:
  167.      if (/foo/ ~ $1) print "found foo"
  168.    This code is "obviously" testing `$1' for a match against the regexp
  169. `/foo/'.  But in fact, the expression `(/foo/ ~ $1)' actually means
  170. `(($0 ~ /foo/) ~ $1)'.  In other words, first match the input record
  171. against the regexp `/foo/'.  The result will be either a 0 or a 1,
  172. depending upon the success or failure of the match.  Then match that
  173. result against the first field in the record.
  174.    Since it is unlikely that you would ever really wish to make this
  175. kind of test, `gawk' will issue a warning when it sees this construct in
  176. a program.
  177.    Another consequence of this rule is that the assignment statement
  178.      matches = /foo/
  179. will assign either 0 or 1 to the variable `matches', depending upon the
  180. contents of the current input record.
  181.    Constant regular expressions are also used as the first argument for
  182. the `sub' and `gsub' functions (*note Built-in Functions for String
  183. Manipulation: String Functions.).
  184.    This feature of the language was never well documented until the
  185. POSIX specification.
  186.    You may be wondering, when is
  187.      $1 ~ /foo/ { ... }
  188. preferable to
  189.      $1 ~ "foo" { ... }
  190.    Since the right-hand sides of both `~' operators are constants, it
  191. is more efficient to use the `/foo/' form: `awk' can note that you have
  192. supplied a regexp and store it internally in a form that makes pattern
  193. matching more efficient.  In the second form, `awk' must first convert
  194. the string into this internal form, and then perform the pattern
  195. matching.  The first form is also better style; it shows clearly that
  196. you intend a regexp match.
  197. File: gawk.info,  Node: Variables,  Next: Arithmetic Ops,  Prev: Constants,  Up: Expressions
  198. Variables
  199. =========
  200.    Variables let you give names to values and refer to them later.  You
  201. have already seen variables in many of the examples.  The name of a
  202. variable must be a sequence of letters, digits and underscores, but it
  203. may not begin with a digit.  Case is significant in variable names; `a'
  204. and `A' are distinct variables.
  205.    A variable name is a valid expression by itself; it represents the
  206. variable's current value.  Variables are given new values with
  207. "assignment operators" and "increment operators".  *Note Assignment
  208. Expressions: Assignment Ops.
  209.    A few variables have special built-in meanings, such as `FS', the
  210. field separator, and `NF', the number of fields in the current input
  211. record.  *Note Built-in Variables::, for a list of them.  These
  212. built-in variables can be used and assigned just like all other
  213. variables, but their values are also used or changed automatically by
  214. `awk'.  Each built-in variable's name is made entirely of upper case
  215. letters.
  216.    Variables in `awk' can be assigned either numeric or string values.
  217. By default, variables are initialized to the null string, which is
  218. effectively zero if converted to a number.  There is no need to
  219. "initialize" each variable explicitly in `awk', the way you would in C
  220. or most other traditional languages.
  221. * Menu:
  222. * Assignment Options::          Setting variables on the command line
  223.                                 and a summary of command line syntax.
  224.                                 This is an advanced method of input.
  225. File: gawk.info,  Node: Assignment Options,  Prev: Variables,  Up: Variables
  226. Assigning Variables on the Command Line
  227. ---------------------------------------
  228.    You can set any `awk' variable by including a "variable assignment"
  229. among the arguments on the command line when you invoke `awk' (*note
  230. Invoking `awk': Command Line.).  Such an assignment has this form:
  231.      VARIABLE=TEXT
  232. With it, you can set a variable either at the beginning of the `awk'
  233. run or in between input files.
  234.    If you precede the assignment with the `-v' option, like this:
  235.      -v VARIABLE=TEXT
  236. then the variable is set at the very beginning, before even the `BEGIN'
  237. rules are run.  The `-v' option and its assignment must precede all the
  238. file name arguments, as well as the program text.
  239.    Otherwise, the variable assignment is performed at a time determined
  240. by its position among the input file arguments: after the processing of
  241. the preceding input file argument.  For example:
  242.      awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
  243. prints the value of field number `n' for all input records.  Before the
  244. first file is read, the command line sets the variable `n' equal to 4.
  245. This causes the fourth field to be printed in lines from the file
  246. `inventory-shipped'.  After the first file has finished, but before the
  247. second file is started, `n' is set to 2, so that the second field is
  248. printed in lines from `BBS-list'.
  249.    Command line arguments are made available for explicit examination by
  250. the `awk' program in an array named `ARGV' (*note Built-in
  251. Variables::.).
  252.    `awk' processes the values of command line assignments for escape
  253. sequences (*note Constant Expressions: Constants.).
  254. File: gawk.info,  Node: Arithmetic Ops,  Next: Concatenation,  Prev: Variables,  Up: Expressions
  255. Arithmetic Operators
  256. ====================
  257.    The `awk' language uses the common arithmetic operators when
  258. evaluating expressions.  All of these arithmetic operators follow normal
  259. precedence rules, and work as you would expect them to.  This example
  260. divides field three by field four, adds field two, stores the result
  261. into field one, and prints the resulting altered input record:
  262.      awk '{ $1 = $2 + $3 / $4; print }' inventory-shipped
  263.    The arithmetic operators in `awk' are:
  264. `X + Y'
  265.      Addition.
  266. `X - Y'
  267.      Subtraction.
  268. `- X'
  269.      Negation.
  270. `+ X'
  271.      Unary plus.  No real effect on the expression.
  272. `X * Y'
  273.      Multiplication.
  274. `X / Y'
  275.      Division.  Since all numbers in `awk' are double-precision
  276.      floating point, the result is not rounded to an integer: `3 / 4'
  277.      has the value 0.75.
  278. `X % Y'
  279.      Remainder.  The quotient is rounded toward zero to an integer,
  280.      multiplied by Y and this result is subtracted from X.  This
  281.      operation is sometimes known as "trunc-mod."  The following
  282.      relation always holds:
  283.           b * int(a / b) + (a % b) == a
  284.      One possibly undesirable effect of this definition of remainder is
  285.      that `X % Y' is negative if X is negative.  Thus,
  286.           -17 % 8 = -1
  287.      In other `awk' implementations, the signedness of the remainder
  288.      may be machine dependent.
  289. `X ^ Y'
  290. `X ** Y'
  291.      Exponentiation: X raised to the Y power.  `2 ^ 3' has the value 8.
  292.      The character sequence `**' is equivalent to `^'.  (The POSIX
  293.      standard only specifies the use of `^' for exponentiation.)
  294. File: gawk.info,  Node: Concatenation,  Next: Comparison Ops,  Prev: Arithmetic Ops,  Up: Expressions
  295. String Concatenation
  296. ====================
  297.    There is only one string operation: concatenation.  It does not have
  298. a specific operator to represent it.  Instead, concatenation is
  299. performed by writing expressions next to one another, with no operator.
  300. For example:
  301.      awk '{ print "Field number one: " $1 }' BBS-list
  302. produces, for the first record in `BBS-list':
  303.      Field number one: aardvark
  304.    Without the space in the string constant after the `:', the line
  305. would run together.  For example:
  306.      awk '{ print "Field number one:" $1 }' BBS-list
  307. produces, for the first record in `BBS-list':
  308.      Field number one:aardvark
  309.    Since string concatenation does not have an explicit operator, it is
  310. often necessary to insure that it happens where you want it to by
  311. enclosing the items to be concatenated in parentheses.  For example, the
  312. following code fragment does not concatenate `file' and `name' as you
  313. might expect:
  314.      file = "file"
  315.      name = "name"
  316.      print "something meaningful" > file name
  317. It is necessary to use the following:
  318.      print "something meaningful" > (file name)
  319.    We recommend you use parentheses around concatenation in all but the
  320. most common contexts (such as in the right-hand operand of `=').
  321. File: gawk.info,  Node: Comparison Ops,  Next: Boolean Ops,  Prev: Concatenation,  Up: Expressions
  322. Comparison Expressions
  323. ======================
  324.    "Comparison expressions" compare strings or numbers for
  325. relationships such as equality.  They are written using "relational
  326. operators", which are a superset of those in C.  Here is a table of
  327. them:
  328. `X < Y'
  329.      True if X is less than Y.
  330. `X <= Y'
  331.      True if X is less than or equal to Y.
  332. `X > Y'
  333.      True if X is greater than Y.
  334. `X >= Y'
  335.      True if X is greater than or equal to Y.
  336. `X == Y'
  337.      True if X is equal to Y.
  338. `X != Y'
  339.      True if X is not equal to Y.
  340. `X ~ Y'
  341.      True if the string X matches the regexp denoted by Y.
  342. `X !~ Y'
  343.      True if the string X does not match the regexp denoted by Y.
  344. `SUBSCRIPT in ARRAY'
  345.      True if array ARRAY has an element with the subscript SUBSCRIPT.
  346.    Comparison expressions have the value 1 if true and 0 if false.
  347.    The rules `gawk' uses for performing comparisons are based on those
  348. in draft 11.2 of the POSIX standard.  The POSIX standard introduced the
  349. concept of a "numeric string", which is simply a string that looks like
  350. a number, for example, `" +2"'.
  351.    When performing a relational operation, `gawk' considers the type of
  352. an operand to be the type it received on its last *assignment*, rather
  353. than the type of its last *use* (*note Numeric and String Values:
  354. Values.).  This type is *unknown* when the operand is from an
  355. "external" source: field variables, command line arguments, array
  356. elements resulting from a `split' operation, and the value of an
  357. `ENVIRON' element.  In this case only, if the operand is a numeric
  358. string, then it is considered to be of both string type and numeric
  359. type.  If at least one operand of a comparison is of string type only,
  360. then a string comparison is performed.  Any numeric operand will be
  361. converted to a string using the value of `CONVFMT' (*note Conversion of
  362. Strings and Numbers: Conversion.).  If one operand of a comparison is
  363. numeric, and the other operand is either numeric or both numeric and
  364. string, then `gawk' does a numeric comparison.  If both operands have
  365. both types, then the comparison is numeric.  Strings are compared by
  366. comparing the first character of each, then the second character of
  367. each, and so on.  Thus `"10"' is less than `"9"'.  If there are two
  368. strings where one is a prefix of the other, the shorter string is less
  369. than the longer one.  Thus `"abc"' is less than `"abcd"'.
  370.    Here are some sample expressions, how `gawk' compares them, and what
  371. the result of the comparison is.
  372. `1.5 <= 2.0'
  373.      numeric comparison (true)
  374. `"abc" >= "xyz"'
  375.      string comparison (false)
  376. `1.5 != " +2"'
  377.      string comparison (true)
  378. `"1e2" < "3"'
  379.      string comparison (true)
  380. `a = 2; b = "2"'
  381. `a == b'
  382.      string comparison (true)
  383.      echo 1e2 3 | awk '{ print ($1 < $2) ? "true" : "false" }'
  384. prints `false' since both `$1' and `$2' are numeric strings and thus
  385. have both string and numeric types, thus dictating a numeric comparison.
  386.    The purpose of the comparison rules and the use of numeric strings is
  387. to attempt to produce the behavior that is "least surprising," while
  388. still "doing the right thing."
  389.    String comparisons and regular expression comparisons are very
  390. different.  For example,
  391.      $1 == "foo"
  392. has the value of 1, or is true, if the first field of the current input
  393. record is precisely `foo'.  By contrast,
  394.      $1 ~ /foo/
  395. has the value 1 if the first field contains `foo', such as `foobar'.
  396.    The right hand operand of the `~' and `!~' operators may be either a
  397. constant regexp (`/.../'), or it may be an ordinary expression, in
  398. which case the value of the expression as a string is a dynamic regexp
  399. (*note How to Use Regular Expressions: Regexp Usage.).
  400.    In very recent implementations of `awk', a constant regular
  401. expression in slashes by itself is also an expression.  The regexp
  402. `/REGEXP/' is an abbreviation for this comparison expression:
  403.      $0 ~ /REGEXP/
  404.    In some contexts it may be necessary to write parentheses around the
  405. regexp to avoid confusing the `gawk' parser.  For example, `(/x/ - /y/)
  406. > threshold' is not allowed, but `((/x/) - (/y/)) > threshold' parses
  407. properly.
  408.    One special place where `/foo/' is *not* an abbreviation for `$0 ~
  409. /foo/' is when it is the right-hand operand of `~' or `!~'! *Note
  410. Constant Expressions: Constants, where this is discussed in more detail.
  411. File: gawk.info,  Node: Boolean Ops,  Next: Assignment Ops,  Prev: Comparison Ops,  Up: Expressions
  412. Boolean Expressions
  413. ===================
  414.    A "boolean expression" is a combination of comparison expressions or
  415. matching expressions, using the boolean operators "or" (`||'), "and"
  416. (`&&'), and "not" (`!'), along with parentheses to control nesting.
  417. The truth of the boolean expression is computed by combining the truth
  418. values of the component expressions.
  419.    Boolean expressions can be used wherever comparison and matching
  420. expressions can be used.  They can be used in `if', `while' `do' and
  421. `for' statements.  They have numeric values (1 if true, 0 if false),
  422. which come into play if the result of the boolean expression is stored
  423. in a variable, or used in arithmetic.
  424.    In addition, every boolean expression is also a valid boolean
  425. pattern, so you can use it as a pattern to control the execution of
  426. rules.
  427.    Here are descriptions of the three boolean operators, with an
  428. example of each.  It may be instructive to compare these examples with
  429. the analogous examples of boolean patterns (*note Boolean Operators and
  430. Patterns: Boolean Patterns.), which use the same boolean operators in
  431. patterns instead of expressions.
  432. `BOOLEAN1 && BOOLEAN2'
  433.      True if both BOOLEAN1 and BOOLEAN2 are true.  For example, the
  434.      following statement prints the current input record if it contains
  435.      both `2400' and `foo'.
  436.           if ($0 ~ /2400/ && $0 ~ /foo/) print
  437.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is true.
  438.      This can make a difference when BOOLEAN2 contains expressions that
  439.      have side effects: in the case of `$0 ~ /foo/ && ($2 == bar++)',
  440.      the variable `bar' is not incremented if there is no `foo' in the
  441.      record.
  442. `BOOLEAN1 || BOOLEAN2'
  443.      True if at least one of BOOLEAN1 or BOOLEAN2 is true.  For
  444.      example, the following command prints all records in the input
  445.      file `BBS-list' that contain *either* `2400' or `foo', or both.
  446.           awk '{ if ($0 ~ /2400/ || $0 ~ /foo/) print }' BBS-list
  447.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is false.
  448.      This can make a difference when BOOLEAN2 contains expressions
  449.      that have side effects.
  450. `!BOOLEAN'
  451.      True if BOOLEAN is false.  For example, the following program
  452.      prints all records in the input file `BBS-list' that do *not*
  453.      contain the string `foo'.
  454.           awk '{ if (! ($0 ~ /foo/)) print }' BBS-list
  455. File: gawk.info,  Node: Assignment Ops,  Next: Increment Ops,  Prev: Boolean Ops,  Up: Expressions
  456. Assignment Expressions
  457. ======================
  458.    An "assignment" is an expression that stores a new value into a
  459. variable.  For example, let's assign the value 1 to the variable `z':
  460.      z = 1
  461.    After this expression is executed, the variable `z' has the value 1.
  462. Whatever old value `z' had before the assignment is forgotten.
  463.    Assignments can store string values also.  For example, this would
  464. store the value `"this food is good"' in the variable `message':
  465.      thing = "food"
  466.      predicate = "good"
  467.      message = "this " thing " is " predicate
  468. (This also illustrates concatenation of strings.)
  469.    The `=' sign is called an "assignment operator".  It is the simplest
  470. assignment operator because the value of the right-hand operand is
  471. stored unchanged.
  472.    Most operators (addition, concatenation, and so on) have no effect
  473. except to compute a value.  If you ignore the value, you might as well
  474. not use the operator.  An assignment operator is different; it does
  475. produce a value, but even if you ignore the value, the assignment still
  476. makes itself felt through the alteration of the variable.  We call this
  477. a "side effect".
  478.    The left-hand operand of an assignment need not be a variable (*note
  479. Variables::.); it can also be a field (*note Changing the Contents of a
  480. Field: Changing Fields.) or an array element (*note Arrays in `awk':
  481. Arrays.).  These are all called "lvalues", which means they can appear
  482. on the left-hand side of an assignment operator.  The right-hand
  483. operand may be any expression; it produces the new value which the
  484. assignment stores in the specified variable, field or array element.
  485.    It is important to note that variables do *not* have permanent types.
  486. The type of a variable is simply the type of whatever value it happens
  487. to hold at the moment.  In the following program fragment, the variable
  488. `foo' has a numeric value at first, and a string value later on:
  489.      foo = 1
  490.      print foo
  491.      foo = "bar"
  492.      print foo
  493. When the second assignment gives `foo' a string value, the fact that it
  494. previously had a numeric value is forgotten.
  495.    An assignment is an expression, so it has a value: the same value
  496. that is assigned.  Thus, `z = 1' as an expression has the value 1.  One
  497. consequence of this is that you can write multiple assignments together:
  498.      x = y = z = 0
  499. stores the value 0 in all three variables.  It does this because the
  500. value of `z = 0', which is 0, is stored into `y', and then the value of
  501. `y = z = 0', which is 0, is stored into `x'.
  502.    You can use an assignment anywhere an expression is called for.  For
  503. example, it is valid to write `x != (y = 1)' to set `y' to 1 and then
  504. test whether `x' equals 1.  But this style tends to make programs hard
  505. to read; except in a one-shot program, you should rewrite it to get rid
  506. of such nesting of assignments.  This is never very hard.
  507.    Aside from `=', there are several other assignment operators that do
  508. arithmetic with the old value of the variable.  For example, the
  509. operator `+=' computes a new value by adding the right-hand value to
  510. the old value of the variable.  Thus, the following assignment adds 5
  511. to the value of `foo':
  512.      foo += 5
  513. This is precisely equivalent to the following:
  514.      foo = foo + 5
  515. Use whichever one makes the meaning of your program clearer.
  516.    Here is a table of the arithmetic assignment operators.  In each
  517. case, the right-hand operand is an expression whose value is converted
  518. to a number.
  519. `LVALUE += INCREMENT'
  520.      Adds INCREMENT to the value of LVALUE to make the new value of
  521.      LVALUE.
  522. `LVALUE -= DECREMENT'
  523.      Subtracts DECREMENT from the value of LVALUE.
  524. `LVALUE *= COEFFICIENT'
  525.      Multiplies the value of LVALUE by COEFFICIENT.
  526. `LVALUE /= QUOTIENT'
  527.      Divides the value of LVALUE by QUOTIENT.
  528. `LVALUE %= MODULUS'
  529.      Sets LVALUE to its remainder by MODULUS.
  530. `LVALUE ^= POWER'
  531. `LVALUE **= POWER'
  532.      Raises LVALUE to the power POWER.  (Only the `^=' operator is
  533.      specified by POSIX.)
  534. File: gawk.info,  Node: Increment Ops,  Next: Conversion,  Prev: Assignment Ops,  Up: Expressions
  535. Increment Operators
  536. ===================
  537.    "Increment operators" increase or decrease the value of a variable
  538. by 1.  You could do the same thing with an assignment operator, so the
  539. increment operators add no power to the `awk' language; but they are
  540. convenient abbreviations for something very common.
  541.    The operator to add 1 is written `++'.  It can be used to increment
  542. a variable either before or after taking its value.
  543.    To pre-increment a variable V, write `++V'.  This adds 1 to the
  544. value of V and that new value is also the value of this expression.
  545. The assignment expression `V += 1' is completely equivalent.
  546.    Writing the `++' after the variable specifies post-increment.  This
  547. increments the variable value just the same; the difference is that the
  548. value of the increment expression itself is the variable's *old* value.
  549. Thus, if `foo' has the value 4, then the expression `foo++' has the
  550. value 4, but it changes the value of `foo' to 5.
  551.    The post-increment `foo++' is nearly equivalent to writing `(foo +=
  552. 1) - 1'.  It is not perfectly equivalent because all numbers in `awk'
  553. are floating point: in floating point, `foo + 1 - 1' does not
  554. necessarily equal `foo'.  But the difference is minute as long as you
  555. stick to numbers that are fairly small (less than a trillion).
  556.    Any lvalue can be incremented.  Fields and array elements are
  557. incremented just like variables.  (Use `$(i++)' when you wish to do a
  558. field reference and a variable increment at the same time.  The
  559. parentheses are necessary because of the precedence of the field
  560. reference operator, `$'.)
  561.    The decrement operator `--' works just like `++' except that it
  562. subtracts 1 instead of adding.  Like `++', it can be used before the
  563. lvalue to pre-decrement or after it to post-decrement.
  564.    Here is a summary of increment and decrement expressions.
  565. `++LVALUE'
  566.      This expression increments LVALUE and the new value becomes the
  567.      value of this expression.
  568. `LVALUE++'
  569.      This expression causes the contents of LVALUE to be incremented.
  570.      The value of the expression is the *old* value of LVALUE.
  571. `--LVALUE'
  572.      Like `++LVALUE', but instead of adding, it subtracts.  It
  573.      decrements LVALUE and delivers the value that results.
  574. `LVALUE--'
  575.      Like `LVALUE++', but instead of adding, it subtracts.  It
  576.      decrements LVALUE.  The value of the expression is the *old* value
  577.      of LVALUE.
  578. File: gawk.info,  Node: Conversion,  Next: Values,  Prev: Increment Ops,  Up: Expressions
  579. Conversion of Strings and Numbers
  580. =================================
  581.    Strings are converted to numbers, and numbers to strings, if the
  582. context of the `awk' program demands it.  For example, if the value of
  583. either `foo' or `bar' in the expression `foo + bar' happens to be a
  584. string, it is converted to a number before the addition is performed.
  585. If numeric values appear in string concatenation, they are converted to
  586. strings.  Consider this:
  587.      two = 2; three = 3
  588.      print (two three) + 4
  589. This eventually prints the (numeric) value 27.  The numeric values of
  590. the variables `two' and `three' are converted to strings and
  591. concatenated together, and the resulting string is converted back to the
  592. number 23, to which 4 is then added.
  593.    If, for some reason, you need to force a number to be converted to a
  594. string, concatenate the null string with that number.  To force a string
  595. to be converted to a number, add zero to that string.
  596.    A string is converted to a number by interpreting a numeric prefix
  597. of the string as numerals: `"2.5"' converts to 2.5, `"1e3"' converts to
  598. 1000, and `"25fix"' has a numeric value of 25.  Strings that can't be
  599. interpreted as valid numbers are converted to zero.
  600.    The exact manner in which numbers are converted into strings is
  601. controlled by the `awk' built-in variable `CONVFMT' (*note Built-in
  602. Variables::.).  Numbers are converted using a special version of the
  603. `sprintf' function (*note Built-in Functions: Built-in.) with `CONVFMT'
  604. as the format specifier.
  605.    `CONVFMT''s default value is `"%.6g"', which prints a value with at
  606. least six significant digits.  For some applications you will want to
  607. change it to specify more precision.  Double precision on most modern
  608. machines gives you 16 or 17 decimal digits of precision.
  609.    Strange results can happen if you set `CONVFMT' to a string that
  610. doesn't tell `sprintf' how to format floating point numbers in a useful
  611. way.  For example, if you forget the `%' in the format, all numbers
  612. will be converted to the same constant string.
  613.    As a special case, if a number is an integer, then the result of
  614. converting it to a string is *always* an integer, no matter what the
  615. value of `CONVFMT' may be.  Given the following code fragment:
  616.      CONVFMT = "%2.2f"
  617.      a = 12
  618.      b = a ""
  619. `b' has the value `"12"', not `"12.00"'.
  620.    Prior to the POSIX standard, `awk' specified that the value of
  621. `OFMT' was used for converting numbers to strings.  `OFMT' specifies
  622. the output format to use when printing numbers with `print'.  `CONVFMT'
  623. was introduced in order to separate the semantics of conversions from
  624. the semantics of printing.  Both `CONVFMT' and `OFMT' have the same
  625. default value: `"%.6g"'.  In the vast majority of cases, old `awk'
  626. programs will not change their behavior.  However, this use of `OFMT'
  627. is something to keep in mind if you must port your program to other
  628. implementations of `awk'; we recommend that instead of changing your
  629. programs, you just port `gawk' itself!
  630. File: gawk.info,  Node: Values,  Next: Conditional Exp,  Prev: Conversion,  Up: Expressions
  631. Numeric and String Values
  632. =========================
  633.    Through most of this manual, we present `awk' values (such as
  634. constants, fields, or variables) as *either* numbers *or* strings.
  635. This is a convenient way to think about them, since typically they are
  636. used in only one way, or the other.
  637.    In truth though, `awk' values can be *both* string and numeric, at
  638. the same time.  Internally, `awk' represents values with a string, a
  639. (floating point) number, and an indication that one, the other, or both
  640. representations of the value are valid.
  641.    Keeping track of both kinds of values is important for execution
  642. efficiency:  a variable can acquire a string value the first time it is
  643. used as a string, and then that string value can be used until the
  644. variable is assigned a new value.  Thus, if a variable with only a
  645. numeric value is used in several concatenations in a row, it only has
  646. to be given a string representation once.  The numeric value remains
  647. valid, so that no conversion back to a number is necessary if the
  648. variable is later used in an arithmetic expression.
  649.    Tracking both kinds of values is also important for precise numerical
  650. calculations.  Consider the following:
  651.      a = 123.321
  652.      CONVFMT = "%3.1f"
  653.      b = a " is a number"
  654.      c = a + 1.654
  655. The variable `a' receives a string value in the concatenation and
  656. assignment to `b'.  The string value of `a' is `"123.3"'.  If the
  657. numeric value was lost when it was converted to a string, then the
  658. numeric use of `a' in the last statement would lose information.  `c'
  659. would be assigned the value 124.954 instead of 124.975.  Such errors
  660. accumulate rapidly, and very adversely affect numeric computations.
  661.    Once a numeric value acquires a corresponding string value, it stays
  662. valid until a new assignment is made.  If `CONVFMT' (*note Conversion
  663. of Strings and Numbers: Conversion.) changes in the meantime, the old
  664. string value will still be used.  For example:
  665.      BEGIN {
  666.          CONVFMT = "%2.2f"
  667.          a = 123.456
  668.          b = a ""                # force `a' to have string value too
  669.          printf "a = %s\n", a
  670.          CONVFMT = "%.6g"
  671.          printf "a = %s\n", a
  672.          a += 0                  # make `a' numeric only again
  673.          printf "a = %s\n", a    # use `a' as string
  674.      }
  675. This program prints `a = 123.46' twice, and then prints `a = 123.456'.
  676.    *Note Conversion of Strings and Numbers: Conversion, for the rules
  677. that specify how string values are made from numeric values.
  678. File: gawk.info,  Node: Conditional Exp,  Next: Function Calls,  Prev: Values,  Up: Expressions
  679. Conditional Expressions
  680. =======================
  681.    A "conditional expression" is a special kind of expression with
  682. three operands.  It allows you to use one expression's value to select
  683. one of two other expressions.
  684.    The conditional expression looks the same as in the C language:
  685.      SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP
  686. There are three subexpressions.  The first, SELECTOR, is always
  687. computed first.  If it is "true" (not zero and not null) then
  688. IF-TRUE-EXP is computed next and its value becomes the value of the
  689. whole expression.  Otherwise, IF-FALSE-EXP is computed next and its
  690. value becomes the value of the whole expression.
  691.    For example, this expression produces the absolute value of `x':
  692.      x > 0 ? x : -x
  693.    Each time the conditional expression is computed, exactly one of
  694. IF-TRUE-EXP and IF-FALSE-EXP is computed; the other is ignored.  This
  695. is important when the expressions contain side effects.  For example,
  696. this conditional expression examines element `i' of either array `a' or
  697. array `b', and increments `i'.
  698.      x == y ? a[i++] : b[i++]
  699. This is guaranteed to increment `i' exactly once, because each time one
  700. or the other of the two increment expressions is executed, and the
  701. other is not.
  702. File: gawk.info,  Node: Function Calls,  Next: Precedence,  Prev: Conditional Exp,  Up: Expressions
  703. Function Calls
  704. ==============
  705.    A "function" is a name for a particular calculation.  Because it has
  706. a name, you can ask for it by name at any point in the program.  For
  707. example, the function `sqrt' computes the square root of a number.
  708.    A fixed set of functions are "built-in", which means they are
  709. available in every `awk' program.  The `sqrt' function is one of these.
  710. *Note Built-in Functions: Built-in, for a list of built-in functions
  711. and their descriptions.  In addition, you can define your own functions
  712. in the program for use elsewhere in the same program.  *Note
  713. User-defined Functions: User-defined, for how to do this.
  714.    The way to use a function is with a "function call" expression,
  715. which consists of the function name followed by a list of "arguments"
  716. in parentheses.  The arguments are expressions which give the raw
  717. materials for the calculation that the function will do.  When there is
  718. more than one argument, they are separated by commas.  If there are no
  719. arguments, write just `()' after the function name.  Here are some
  720. examples:
  721.      sqrt(x^2 + y^2)      # One argument
  722.      atan2(y, x)          # Two arguments
  723.      rand()               # No arguments
  724.    *Do not put any space between the function name and the
  725. open-parenthesis!*  A user-defined function name looks just like the
  726. name of a variable, and space would make the expression look like
  727. concatenation of a variable with an expression inside parentheses.
  728. Space before the parenthesis is harmless with built-in functions, but
  729. it is best not to get into the habit of using space to avoid mistakes
  730. with user-defined functions.
  731.    Each function expects a particular number of arguments.  For
  732. example, the `sqrt' function must be called with a single argument, the
  733. number to take the square root of:
  734.      sqrt(ARGUMENT)
  735.    Some of the built-in functions allow you to omit the final argument.
  736. If you do so, they use a reasonable default.  *Note Built-in Functions:
  737. Built-in, for full details.  If arguments are omitted in calls to
  738. user-defined functions, then those arguments are treated as local
  739. variables, initialized to the null string (*note User-defined
  740. Functions: User-defined.).
  741.    Like every other expression, the function call has a value, which is
  742. computed by the function based on the arguments you give it.  In this
  743. example, the value of `sqrt(ARGUMENT)' is the square root of the
  744. argument.  A function can also have side effects, such as assigning the
  745. values of certain variables or doing I/O.
  746.    Here is a command to read numbers, one number per line, and print the
  747. square root of each one:
  748.      awk '{ print "The square root of", $1, "is", sqrt($1) }'
  749. File: gawk.info,  Node: Precedence,  Prev: Function Calls,  Up: Expressions
  750. Operator Precedence (How Operators Nest)
  751. ========================================
  752.    "Operator precedence" determines how operators are grouped, when
  753. different operators appear close by in one expression.  For example,
  754. `*' has higher precedence than `+'; thus, `a + b * c' means to multiply
  755. `b' and `c', and then add `a' to the product (i.e., `a + (b * c)').
  756.    You can overrule the precedence of the operators by using
  757. parentheses.  You can think of the precedence rules as saying where the
  758. parentheses are assumed if you do not write parentheses yourself.  In
  759. fact, it is wise to always use parentheses whenever you have an unusual
  760. combination of operators, because other people who read the program may
  761. not remember what the precedence is in this case.  You might forget,
  762. too; then you could make a mistake.  Explicit parentheses will help
  763. prevent any such mistake.
  764.    When operators of equal precedence are used together, the leftmost
  765. operator groups first, except for the assignment, conditional and
  766. exponentiation operators, which group in the opposite order.  Thus, `a
  767. - b + c' groups as `(a - b) + c'; `a = b = c' groups as `a = (b = c)'.
  768.    The precedence of prefix unary operators does not matter as long as
  769. only unary operators are involved, because there is only one way to
  770. parse them--innermost first.  Thus, `$++i' means `$(++i)' and `++$x'
  771. means `++($x)'.  However, when another operator follows the operand,
  772. then the precedence of the unary operators can matter.  Thus, `$x^2'
  773. means `($x)^2', but `-x^2' means `-(x^2)', because `-' has lower
  774. precedence than `^' while `$' has higher precedence.
  775.    Here is a table of the operators of `awk', in order of increasing
  776. precedence:
  777. assignment
  778.      `=', `+=', `-=', `*=', `/=', `%=', `^=', `**='.  These operators
  779.      group right-to-left.  (The `**=' operator is not specified by
  780.      POSIX.)
  781. conditional
  782.      `?:'.  This operator groups right-to-left.
  783. logical "or".
  784.      `||'.
  785. logical "and".
  786.      `&&'.
  787. array membership
  788.      `in'.
  789. matching
  790.      `~', `!~'.
  791. relational, and redirection
  792.      The relational operators and the redirections have the same
  793.      precedence level.  Characters such as `>' serve both as
  794.      relationals and as redirections; the context distinguishes between
  795.      the two meanings.
  796.      The relational operators are `<', `<=', `==', `!=', `>=' and `>'.
  797.      The I/O redirection operators are `<', `>', `>>' and `|'.
  798.      Note that I/O redirection operators in `print' and `printf'
  799.      statements belong to the statement level, not to expressions.  The
  800.      redirection does not produce an expression which could be the
  801.      operand of another operator.  As a result, it does not make sense
  802.      to use a redirection operator near another operator of lower
  803.      precedence, without parentheses.  Such combinations, for example
  804.      `print foo > a ? b : c', result in syntax errors.
  805. concatenation
  806.      No special token is used to indicate concatenation.  The operands
  807.      are simply written side by side.
  808. add, subtract
  809.      `+', `-'.
  810. multiply, divide, mod
  811.      `*', `/', `%'.
  812. unary plus, minus, "not"
  813.      `+', `-', `!'.
  814. exponentiation
  815.      `^', `**'.  These operators group right-to-left.  (The `**'
  816.      operator is not specified by POSIX.)
  817. increment, decrement
  818.      `++', `--'.
  819. field
  820.      `$'.
  821. File: gawk.info,  Node: Statements,  Next: Arrays,  Prev: Expressions,  Up: Top
  822. Control Statements in Actions
  823. *****************************
  824.    "Control statements" such as `if', `while', and so on control the
  825. flow of execution in `awk' programs.  Most of the control statements in
  826. `awk' are patterned on similar statements in C.
  827.    All the control statements start with special keywords such as `if'
  828. and `while', to distinguish them from simple expressions.
  829.    Many control statements contain other statements; for example, the
  830. `if' statement contains another statement which may or may not be
  831. executed.  The contained statement is called the "body".  If you want
  832. to include more than one statement in the body, group them into a
  833. single compound statement with curly braces, separating them with
  834. newlines or semicolons.
  835. * Menu:
  836. * If Statement::                Conditionally execute
  837.                                 some `awk' statements.
  838. * While Statement::             Loop until some condition is satisfied.
  839. * Do Statement::                Do specified action while looping until some
  840.                                 condition is satisfied.
  841. * For Statement::               Another looping statement, that provides
  842.                                 initialization and increment clauses.
  843. * Break Statement::             Immediately exit the innermost enclosing loop.
  844. * Continue Statement::          Skip to the end of the innermost
  845.                                 enclosing loop.
  846. * Next Statement::              Stop processing the current input record.
  847. * Next File Statement::         Stop processing the current file.
  848. * Exit Statement::              Stop execution of `awk'.
  849. File: gawk.info,  Node: If Statement,  Next: While Statement,  Prev: Statements,  Up: Statements
  850. The `if' Statement
  851. ==================
  852.    The `if'-`else' statement is `awk''s decision-making statement.  It
  853. looks like this:
  854.      if (CONDITION) THEN-BODY [else ELSE-BODY]
  855. CONDITION is an expression that controls what the rest of the statement
  856. will do.  If CONDITION is true, THEN-BODY is executed; otherwise,
  857. ELSE-BODY is executed (assuming that the `else' clause is present).
  858. The `else' part of the statement is optional.  The condition is
  859. considered false if its value is zero or the null string, and true
  860. otherwise.
  861.    Here is an example:
  862.      if (x % 2 == 0)
  863.          print "x is even"
  864.      else
  865.          print "x is odd"
  866.    In this example, if the expression `x % 2 == 0' is true (that is,
  867. the value of `x' is divisible by 2), then the first `print' statement
  868. is executed, otherwise the second `print' statement is performed.
  869.    If the `else' appears on the same line as THEN-BODY, and THEN-BODY
  870. is not a compound statement (i.e., not surrounded by curly braces),
  871. then a semicolon must separate THEN-BODY from `else'.  To illustrate
  872. this, let's rewrite the previous example:
  873.      awk '{ if (x % 2 == 0) print "x is even"; else
  874.              print "x is odd" }'
  875. If you forget the `;', `awk' won't be able to parse the statement, and
  876. you will get a syntax error.
  877.    We would not actually write this example this way, because a human
  878. reader might fail to see the `else' if it were not the first thing on
  879. its line.
  880. File: gawk.info,  Node: While Statement,  Next: Do Statement,  Prev: If Statement,  Up: Statements
  881. The `while' Statement
  882. =====================
  883.    In programming, a "loop" means a part of a program that is (or at
  884. least can be) executed two or more times in succession.
  885.    The `while' statement is the simplest looping statement in `awk'.
  886. It repeatedly executes a statement as long as a condition is true.  It
  887. looks like this:
  888.      while (CONDITION)
  889.        BODY
  890. Here BODY is a statement that we call the "body" of the loop, and
  891. CONDITION is an expression that controls how long the loop keeps
  892. running.
  893.    The first thing the `while' statement does is test CONDITION.  If
  894. CONDITION is true, it executes the statement BODY.  (CONDITION is true
  895. when the value is not zero and not a null string.)  After BODY has been
  896. executed, CONDITION is tested again, and if it is still true, BODY is
  897. executed again.  This process repeats until CONDITION is no longer
  898. true.  If CONDITION is initially false, the body of the loop is never
  899. executed.
  900.    This example prints the first three fields of each record, one per
  901. line.
  902.      awk '{ i = 1
  903.             while (i <= 3) {
  904.                 print $i
  905.                 i++
  906.             }
  907.      }'
  908. Here the body of the loop is a compound statement enclosed in braces,
  909. containing two statements.
  910.    The loop works like this: first, the value of `i' is set to 1.
  911. Then, the `while' tests whether `i' is less than or equal to three.
  912. This is the case when `i' equals one, so the `i'-th field is printed.
  913. Then the `i++' increments the value of `i' and the loop repeats.  The
  914. loop terminates when `i' reaches 4.
  915.    As you can see, a newline is not required between the condition and
  916. the body; but using one makes the program clearer unless the body is a
  917. compound statement or is very simple.  The newline after the open-brace
  918. that begins the compound statement is not required either, but the
  919. program would be hard to read without it.
  920. File: gawk.info,  Node: Do Statement,  Next: For Statement,  Prev: While Statement,  Up: Statements
  921. The `do'-`while' Statement
  922. ==========================
  923.    The `do' loop is a variation of the `while' looping statement.  The
  924. `do' loop executes the BODY once, then repeats BODY as long as
  925. CONDITION is true.  It looks like this:
  926.      do
  927.        BODY
  928.      while (CONDITION)
  929.    Even if CONDITION is false at the start, BODY is executed at least
  930. once (and only once, unless executing BODY makes CONDITION true).
  931. Contrast this with the corresponding `while' statement:
  932.      while (CONDITION)
  933.        BODY
  934. This statement does not execute BODY even once if CONDITION is false to
  935. begin with.
  936.    Here is an example of a `do' statement:
  937.      awk '{ i = 1
  938.             do {
  939.                print $0
  940.                i++
  941.             } while (i <= 10)
  942.      }'
  943. prints each input record ten times.  It isn't a very realistic example,
  944. since in this case an ordinary `while' would do just as well.  But this
  945. reflects actual experience; there is only occasionally a real use for a
  946. `do' statement.
  947.