home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 11 / AUCD11B.iso / LANGUAGES / WraithSet / AwkStuff / MawkSrc / man / mawk
Text File  |  1999-11-05  |  42KB  |  1,255 lines

  1.  
  2.  
  3.  
  4. MAWK(1)                   USER COMMANDS                   MAWK(1)
  5.  
  6.  
  7.  
  8. NAME
  9.      mawk - pattern scanning and text processing language
  10.  
  11. SYNOPSIS
  12.      mawk [-W option] [-F value]  [-v  var=value]  [--]  'program
  13.      text' [file ...]
  14.      mawk [-W option] [-F value] [-v var=value] [-f program-file]
  15.      [--] [file ...]
  16.  
  17. DESCRIPTION
  18.      mawk is an interpreter for  the  AWK  Programming  Language.
  19.      The  AWK  language is useful for manipulation of data files,
  20.      text retrieval  and  processing,  and  for  prototyping  and
  21.      experimenting with algorithms.  mawk is a new awk meaning it
  22.      implements the AWK language as defined in Aho, Kernighan and
  23.      Weinberger,  The  AWK  Programming  Language, Addison-Wesley
  24.      Publishing, 1988.  (Hereafter referred to as the AWK  book.)
  25.      mawk conforms to the Posix 1003.2 (draft 11.3) definition of
  26.      the AWK language which contains a few features not described
  27.      in the AWK book,  and mawk provides a small number of exten-
  28.      sions.
  29.  
  30.      An AWK program is a sequence of pattern {action}  pairs  and
  31.      function  definitions.   Short  programs  are entered on the
  32.      command  line  usually  enclosed  in  '  '  to  avoid  shell
  33.      interpretation.   Longer programs can be read in from a file
  34.      with the -f option.  Data  input is read from  the  list  of
  35.      files  on  the  command line or from standard input when the
  36.      list is empty.  The input is broken into records  as  deter-
  37.      mined by the record separator variable, RS.  Initially, RS =
  38.      "\n" and records are synonymous with lines.  Each record  is
  39.      compared against each pattern and if it matches, the program
  40.      text for {action} is executed.
  41.  
  42. OPTIONS
  43.      -F value       sets the field separator, FS, to value.
  44.  
  45.      -f file        Program text is read  from  file  instead  of
  46.                     from  the  command line.  Multiple -f options
  47.                     are allowed.
  48.  
  49.      -v var=value   assigns value to program variable var.
  50.  
  51.      --             indicates the unambiguous end of options.
  52.  
  53.      The above options will be available with any Posix  compati-
  54.      ble  implementation  of  AWK,  and  implementation  specific
  55.      options are prefaced with -W.  mawk provides six:
  56.  
  57.      -W version     mawk writes  its  version  and  copyright  to
  58.                     stdout  and  compiled  limits  to  stderr and
  59.                     exits 0.
  60.  
  61.  
  62.  
  63. Version 1.2         Last change: Dec 22 1994                    1
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. MAWK(1)                   USER COMMANDS                   MAWK(1)
  71.  
  72.  
  73.  
  74.      -W dump        writes  an  assembler  like  listing  of  the
  75.                     internal  representation  of  the  program to
  76.                     stdout and exits 0  (on  successful  compila-
  77.                     tion).
  78.  
  79.      -W interactive sets unbuffered writes  to  stdout  and  line
  80.                     buffered  reads  from  stdin.   Records  from
  81.                     stdin are lines regardless of  the  value  of
  82.                     RS.
  83.  
  84.      -W exec file   Program text is read from file  and  this  is
  85.                     the  last option. Useful on systems that sup-
  86.                     port the #!  "magic  number"  convention  for
  87.                     executable scripts.
  88.  
  89.      -W sprintf=num adjusts the size of mawk's  internal  sprintf
  90.                     buffer  to  num bytes.  More than rare use of
  91.                     this option indicates mawk should  be  recom-
  92.                     piled.
  93.  
  94.      -W posix_space forces mawk not to consider '\n' to be space.
  95.  
  96.      The short forms -W[vdiesp] are recognized and on  some  sys-
  97.      tems  -We  is mandatory to avoid command line length limita-
  98.      tions.
  99.  
  100. THE AWK LANGUAGE
  101.   1. Program structure
  102.      An AWK program is a sequence of pattern {action}  pairs  and
  103.      user function definitions.
  104.  
  105.      A pattern can be:
  106.           BEGIN
  107.           END
  108.           expression
  109.           expression , expression
  110.  
  111.      One, but not both, of pattern {action} can be omitted.    If
  112.      {action}  is omitted it is implicitly { print }.  If pattern
  113.      is omitted, then it is implicitly matched.   BEGIN  and  END
  114.      patterns require an action.
  115.  
  116.      Statements are terminated by newlines, semi-colons or  both.
  117.      Groups  of  statements  such  as  actions or loop bodies are
  118.      blocked via { ... } as in C.  The last statement in a  block
  119.      doesn't  need a terminator.  Blank lines have no meaning; an
  120.      empty statement is terminated with a semi-colon. Long state-
  121.      ments can be continued with a backslash, \.  A statement can
  122.      be broken without a backslash after a comma, left brace, &&,
  123.      ||,  do,  else, the right parenthesis of an if, while or for
  124.      statement, and the right parenthesis of a  function  defini-
  125.      tion.   A comment starts with # and extends to, but does not
  126.  
  127.  
  128.  
  129. Version 1.2         Last change: Dec 22 1994                    2
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. MAWK(1)                   USER COMMANDS                   MAWK(1)
  137.  
  138.  
  139.  
  140.      include the end of line.
  141.  
  142.      The following statements control program flow inside blocks.
  143.  
  144.           if ( expr ) statement
  145.  
  146.           if ( expr ) statement else statement
  147.  
  148.           while ( expr ) statement
  149.  
  150.           do statement while ( expr )
  151.  
  152.           for ( opt_expr ; opt_expr ; opt_expr ) statement
  153.  
  154.           for ( var in array ) statement
  155.  
  156.           continue
  157.  
  158.           break
  159.  
  160.   2. Data types, conversion and comparison
  161.      There are two basic data types, numeric and string.  Numeric
  162.      constants  can  be integer like -2, decimal like 1.08, or in
  163.      scientific notation like -1.1e4 or .28E-3.  All numbers  are
  164.      represented  internally  and  all  computations  are done in
  165.      floating point arithmetic.  So for example,  the  expression
  166.      0.2e2 == 20 is true and true is represented as 1.0.
  167.  
  168.      String constants are enclosed in double quotes.
  169.  
  170.            "This is a string with a newline at the end.\n"
  171.  
  172.      Strings can be continued across a line by escaping  (\)  the
  173.      newline.  The following escape sequences are recognized.
  174.  
  175.           \\        \
  176.           \"        "
  177.           \a        alert, ascii 7
  178.           \b        backspace, ascii 8
  179.           \t        tab, ascii 9
  180.           \n        newline, ascii 10
  181.           \v        vertical tab, ascii 11
  182.           \f        formfeed, ascii 12
  183.           \r        carriage return, ascii 13
  184.           \ddd      1, 2 or 3 octal digits for ascii ddd
  185.           \xhh      1 or 2 hex digits for ascii  hh
  186.  
  187.      If you escape any other character \c, you get \c, i.e., mawk
  188.      ignores the escape.
  189.  
  190.      There are really three basic data types; the third is number
  191.      and string which has both a numeric value and a string value
  192.  
  193.  
  194.  
  195. Version 1.2         Last change: Dec 22 1994                    3
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. MAWK(1)                   USER COMMANDS                   MAWK(1)
  203.  
  204.  
  205.  
  206.      at  the  same  time.   User  defined  variables  come   into
  207.      existence when first referenced and are initialized to null,
  208.      a number and string value which  has  numeric  value  0  and
  209.      string  value  "".  Non-trivial number and string typed data
  210.      come from input and are typically stored  in  fields.   (See
  211.      section 4).
  212.  
  213.      The type of an expression is determined by its  context  and
  214.      automatic type conversion occurs if needed.  For example, to
  215.      evaluate the statements
  216.  
  217.           y = x + 2  ;  z = x  "hello"
  218.  
  219.      The value stored in variable y will be typed numeric.  If  x
  220.      is  not  numeric,  the  value  read  from  x is converted to
  221.      numeric before it is added to 2 and stored in y.  The  value
  222.      stored  in variable z will be typed string, and the value of
  223.      x will be converted to string if necessary and  concatenated
  224.      with "hello".  (Of course, the value and type stored in x is
  225.      not changed by any conversions.) A string expression is con-
  226.      verted  to  numeric using its longest numeric prefix as with
  227.      atof(3).  A numeric expression is  converted  to  string  by
  228.      replacing  expr with sprintf(CONVFMT, expr), unless expr can
  229.      be represented on the host machine as an exact integer  then
  230.      it is converted to sprintf("%d", expr).  Sprintf() is an AWK
  231.      built-in that duplicates the  functionality  of  sprintf(3),
  232.      and CONVFMT is a built-in variable used for internal conver-
  233.      sion from  number  to  string  and  initialized  to  "%.6g".
  234.      Explicit  type  conversions can be forced, expr "" is string
  235.      and expr+0 is numeric.
  236.  
  237.      To evaluate,  expr1  rel-op  expr2,  if  both  operands  are
  238.      numeric or number and string then the comparison is numeric;
  239.      if both operands are string the comparison is string; if one
  240.      operand  is  string, the non-string operand is converted and
  241.      the comparison is string.  The result is numeric, 1 or 0.
  242.  
  243.      In boolean contexts such as, if ( expr ) statement, a string
  244.      expression evaluates true if and only if it is not the empty
  245.      string ""; numeric values if and  only  if  not  numerically
  246.      zero.
  247.  
  248.   3. Regular expressions
  249.      In the AWK language, records, fields and strings  are  often
  250.      tested  for  matching a regular expression.  Regular expres-
  251.      sions are enclosed in slashes, and
  252.  
  253.           expr ~ /r/
  254.  
  255.      is an AWK expression that evaluates to 1 if  expr  "matches"
  256.      r,  which means a substring of expr is in the set of strings
  257.      defined by r.  With no match the expression evaluates to  0;
  258.  
  259.  
  260.  
  261. Version 1.2         Last change: Dec 22 1994                    4
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. MAWK(1)                   USER COMMANDS                   MAWK(1)
  269.  
  270.  
  271.  
  272.      replacing ~ with the "not match" operator, !~ , reverses the
  273.      meaning.  As  pattern-action pairs,
  274.  
  275.           /r/ { action }   and   $0 ~ /r/ { action }
  276.  
  277.      are the same, and for each  input  record  that  matches  r,
  278.      action  is executed.  In fact, /r/ is an AWK expression that
  279.      is equivalent to ($0 ~ /r/)  anywhere  except  when  on  the
  280.      right side of a match operator or passed as an argument to a
  281.      built-in function that expects a  regular  expression  argu-
  282.      ment.
  283.  
  284.      AWK uses extended regular expressions as with egrep(1).  The
  285.      regular  expression metacharacters, i.e., those with special
  286.      meaning in regular expressions are
  287.  
  288.            ^ $ . [ ] | ( ) * + ?
  289.  
  290.      Regular expressions are built up from characters as follows:
  291.  
  292.           c            matches any non-metacharacter c.
  293.  
  294.           \c           matches a character defined  by  the  same
  295.                        escape  sequences used in string constants
  296.                        or the literal character c if \c is not an
  297.                        escape sequence.
  298.  
  299.           .            matches any character (including newline).
  300.  
  301.           ^            matches the front of a string.
  302.  
  303.           $            matches the back of a string.
  304.  
  305.           [c1c2c3...]  matches  any  character   in   the   class
  306.                        c1c2c3...  .  An interval of characters is
  307.                        denoted c1-c2 inside a class [...].
  308.  
  309.           [^c1c2c3...] matches any character  not  in  the  class
  310.                        c1c2c3...
  311.  
  312.      Regular expressions are built up from other regular  expres-
  313.      sions as follows:
  314.  
  315.           r1r2         matches  r1  followed  immediately  by  r2
  316.                        (concatenation).
  317.  
  318.           r1 | r2      matches r1 or r2 (alternation).
  319.  
  320.           r*           matches r repeated zero or more times.
  321.  
  322.           r+           matches r repeated one or more times.
  323.  
  324.  
  325.  
  326.  
  327. Version 1.2         Last change: Dec 22 1994                    5
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. MAWK(1)                   USER COMMANDS                   MAWK(1)
  335.  
  336.  
  337.  
  338.           r?           matches r zero or once.
  339.  
  340.           (r)          matches r, providing grouping.
  341.  
  342.      The increasing precedence of operators is alternation,  con-
  343.      catenation and unary (*, + or ?).
  344.  
  345.      For example,
  346.  
  347.           /^[_a-zA-Z][_a-zA-Z0-9]*$/  and
  348.           /^[-+]?([0-9]+\.?|\.[0-9])[0-9]*([eE][-+]?[0-9]+)?$/
  349.  
  350.      are matched by AWK identifiers  and  AWK  numeric  constants
  351.      respectively.   Note  that  . has to be escaped to be recog-
  352.      nized as a decimal point, and that  metacharacters  are  not
  353.      special inside character classes.
  354.  
  355.      Any expression can be used on the right hand side of  the  ~
  356.      or !~ operators or passed to a built-in that expects a regu-
  357.      lar expression.  If needed, it is converted to  string,  and
  358.      then interpreted as a regular expression.  For example,
  359.  
  360.           BEGIN { identifier = "[_a-zA-Z][_a-zA-Z0-9]*" }
  361.  
  362.           $0 ~ "^" identifier
  363.  
  364.      prints all lines that start with an AWK identifier.
  365.  
  366.      mawk recognizes the  empty  regular  expression,  //,  which
  367.      matches  the empty string and hence is matched by any string
  368.      at the front, back and between every character.   For  exam-
  369.      ple,
  370.  
  371.           echo  abc | mawk { gsub(//, "X") ; print }
  372.           XaXbXcX
  373.  
  374.  
  375.   4. Records and fields
  376.      Records are read in one at a time, and stored in  the  field
  377.      variable  $0.   The  record  is  split into fields which are
  378.      stored in $1, $2, ..., $NF.  The built-in variable NF is set
  379.      to  the  number of fields, and NR and FNR are incremented by
  380.      1.  Fields above $NF are set to "".
  381.  
  382.      Assignment to $0 causes the fields and NF to be  recomputed.
  383.      Assignment to NF or to a field causes $0 to be reconstructed
  384.      by concatenating the $i's separated by OFS.  Assignment to a
  385.      field with index greater than NF, increases NF and causes $0
  386.      to be reconstructed.
  387.  
  388.      Data input stored in fields is  string,  unless  the  entire
  389.      field  has  numeric  form  and  then  the type is number and
  390.  
  391.  
  392.  
  393. Version 1.2         Last change: Dec 22 1994                    6
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. MAWK(1)                   USER COMMANDS                   MAWK(1)
  401.  
  402.  
  403.  
  404.      string.  For example,
  405.  
  406.           echo 24 24E |
  407.           mawk '{ print($1>100, $1>"100", $2>100, $2>"100") }'
  408.           0 1 1 1
  409.  
  410.      $0 and $2 are string and $1 is number and string.  The first
  411.      comparison  is  numeric,  the second is string, the third is
  412.      string (100 is converted to "100"), and the last is string.
  413.  
  414.   5. Expressions and operators
  415.      The expression syntax is similar to C.  Primary  expressions
  416.      are  numeric constants, string constants, variables, fields,
  417.      arrays and function calls. The identifier  for  a  variable,
  418.      array  or  function can be a sequence of letters, digits and
  419.      underscores, that does not start with  a  digit.   Variables
  420.      are  not  declared; they exist when first referenced and are
  421.      initialized to null.
  422.  
  423.      New expressions are composed with the following operators in
  424.      order of increasing precedence.
  425.  
  426.           assignment          =  +=  -=  *=  /=  %=  ^=
  427.           conditional         ?  :
  428.           logical or          ||
  429.           logical and         &&
  430.           array membership    in
  431.           matching       ~   !~
  432.           relational          <  >   <=  >=  ==  !=
  433.           concatenation       (no explicit operator)
  434.           add ops             +  -
  435.           mul ops             *  /  %
  436.           unary               +  -
  437.           logical not         !
  438.           exponentiation      ^
  439.           inc and dec         ++ -- (both post and pre)
  440.           field               $
  441.  
  442.      Assignment, conditional and exponentiation  associate  right
  443.      to  left;  the other operators associate left to right.  Any
  444.      expression can be parenthesized.
  445.  
  446.   6. Arrays
  447.      Awk provides one-dimensional  arrays.   Array  elements  are
  448.      expressed  as  array[expr].  Expr is internally converted to
  449.      string type, so, for example, A[1] and A["1"] are  the  same
  450.      element  and  the  actual  index  is "1".  Arrays indexed by
  451.      strings are called associative arrays.  Initially  an  array
  452.      is  empty;  elements  exist when first accessed.  An expres-
  453.      sion, expr in array evaluates to 1  if  array[expr]  exists,
  454.      else to 0.
  455.  
  456.  
  457.  
  458.  
  459. Version 1.2         Last change: Dec 22 1994                    7
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. MAWK(1)                   USER COMMANDS                   MAWK(1)
  467.  
  468.  
  469.  
  470.      There is a form of the for statement that  loops  over  each
  471.      index of an array.
  472.  
  473.           for ( var in array ) statement
  474.  
  475.      sets var to each index of array and executes statement.  The
  476.      order  that  var  transverses  the  indices  of array is not
  477.      defined.
  478.  
  479.      The statement, delete array[expr], causes array[expr] not to
  480.      exist.   mawk  supports  an  extension,  delete array, which
  481.      deletes all elements of array.
  482.  
  483.      Multidimensional arrays are synthesized  with  concatenation
  484.      using  the  built-in variable SUBSEP.  array[expr1,expr2] is
  485.      equivalent to array[expr1 SUBSEP expr2].  Testing for a mul-
  486.      tidimensional element uses a parenthesized index, such as
  487.  
  488.           if ( (i, j) in A )  print A[i, j]
  489.  
  490.  
  491.   7. Builtin-variables
  492.      The following variables are built-in and initialized  before
  493.      program execution.
  494.  
  495.           ARGC      number of command line arguments.
  496.  
  497.           ARGV      array of command line arguments, 0..ARGC-1.
  498.  
  499.           CONVFMT   format for internal conversion of numbers  to
  500.                     string, initially = "%.6g".
  501.  
  502.           ENVIRON   array indexed by environment  variables.   An
  503.                     environment  string,  var=value  is stored as
  504.                     ENVIRON[var] = value.
  505.  
  506.           FILENAME  name of the current input file.
  507.  
  508.           FNR       current record number in FILENAME.
  509.  
  510.           FS        splits  records  into  fields  as  a  regular
  511.                     expression.
  512.  
  513.           NF        number of fields in the current record.
  514.  
  515.           NR        current record  number  in  the  total  input
  516.                     stream.
  517.  
  518.           OFMT      format  for  printing  numbers;  initially  =
  519.                     "%.6g".
  520.  
  521.           OFS       inserted between fields on output,  initially
  522.  
  523.  
  524.  
  525. Version 1.2         Last change: Dec 22 1994                    8
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. MAWK(1)                   USER COMMANDS                   MAWK(1)
  533.  
  534.  
  535.  
  536.                     = " ".
  537.  
  538.           ORS       terminates each record on output, initially =
  539.                     "\n".
  540.  
  541.           RLENGTH   length set by the last call to  the  built-in
  542.                     function, match().
  543.  
  544.           RS        input record separator, initially = "\n".
  545.  
  546.           RSTART    index set by the last call to match().
  547.  
  548.           SUBSEP    used to build multiple array subscripts, ini-
  549.                     tially = "\034".
  550.  
  551.   8. Built-in functions
  552.      String functions
  553.  
  554.           gsub(r,s,t)  gsub(r,s)
  555.                Global  substitution,  every  match   of   regular
  556.                expression  r  in variable t is replaced by string
  557.                s.  The number of replacements is returned.  If  t
  558.                is  omitted,  $0 is used.  An & in the replacement
  559.                string s is replaced by the matched  substring  of
  560.                t.   \& and \\ put  literal & and \, respectively,
  561.                in the replacement string.
  562.  
  563.           index(s,t)
  564.                If t is a substring of s, then the position  where
  565.                t  starts  is  returned,  else 0 is returned.  The
  566.                first character of s is in position 1.
  567.  
  568.           length(s)
  569.                Returns the length of string s.
  570.  
  571.           match(s,r)
  572.                Returns the index of the first  longest  match  of
  573.                regular expression r in string s.  Returns 0 if no
  574.                match.  As a side effect, RSTART  is  set  to  the
  575.                return value.  RLENGTH is set to the length of the
  576.                match or -1 if no match.  If the empty  string  is
  577.                matched, RLENGTH is set to 0, and 1 is returned if
  578.                the match is at  the  front,  and  length(s)+1  is
  579.                returned if the match is at the back.
  580.  
  581.           split(s,A,r)  split(s,A)
  582.                String s is split into fields by  regular  expres-
  583.                sion  r  and  the  fields are loaded into array A.
  584.                The number of fields is returned.  See section  11
  585.                below  for  more  detail.   If r is omitted, FS is
  586.                used.
  587.  
  588.  
  589.  
  590.  
  591. Version 1.2         Last change: Dec 22 1994                    9
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. MAWK(1)                   USER COMMANDS                   MAWK(1)
  599.  
  600.  
  601.  
  602.           sprintf(format,expr-list)
  603.                Returns  a  string  constructed   from   expr-list
  604.                according  to  format.   See  the  description  of
  605.                printf() below.
  606.  
  607.           sub(r,s,t)  sub(r,s)
  608.                Single substitution, same as gsub() except at most
  609.                one substitution.
  610.  
  611.           substr(s,i,n)  substr(s,i)
  612.                Returns the substring of  string  s,  starting  at
  613.                index i, of length n.  If n is omitted, the suffix
  614.                of s, starting at i is returned.
  615.  
  616.           tolower(s)
  617.                Returns a copy of s with all upper case characters
  618.                converted to lower case.
  619.  
  620.           toupper(s)
  621.                Returns a copy of s with all lower case characters
  622.                converted to upper case.
  623.  
  624.      Arithmetic functions
  625.  
  626.           atan2(y,x)     Arctan of y/x between -pi and pi.
  627.  
  628.           cos(x)         Cosine function, x in radians.
  629.  
  630.           exp(x)         Exponential function.
  631.  
  632.           int(x)         Returns x truncated towards zero.
  633.  
  634.           log(x)         Natural logarithm.
  635.  
  636.           rand()         Returns a random number between zero and one.
  637.  
  638.           sin(x)         Sine function, x in radians.
  639.  
  640.           sqrt(x)        Returns square root of x.
  641.  
  642.           srand(expr)  srand()
  643.                Seeds the random number generator, using the clock
  644.                if  expr  is omitted, and returns the value of the
  645.                previous seed.  mawk seeds the random number  gen-
  646.                erator  from  the  clock at startup so there is no
  647.                real need to call srand().  Srand(expr) is  useful
  648.                for repeating pseudo random sequences.
  649.  
  650.   9. Input and output
  651.      There are two output statements, print and printf.
  652.  
  653.           print
  654.  
  655.  
  656.  
  657. Version 1.2         Last change: Dec 22 1994                   10
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. MAWK(1)                   USER COMMANDS                   MAWK(1)
  665.  
  666.  
  667.  
  668.                writes $0  ORS to standard output.
  669.  
  670.           print expr1, expr2, ..., exprn
  671.                writes expr1 OFS expr2 OFS ... exprn ORS to  stan-
  672.                dard output.  Numeric expressions are converted to
  673.                string with OFMT.
  674.  
  675.           printf format, expr-list
  676.                duplicates the printf C library  function  writing
  677.                to  standard  output.   The complete ANSI C format
  678.                specifications are recognized with conversions %c,
  679.                %d, %e, %E, %f, %g, %G, %i, %o, %s, %u, %x, %X and
  680.                %%, and conversion qualifiers h and l.
  681.  
  682.      The argument list to  print  or  printf  can  optionally  be
  683.      enclosed  in  parentheses.  Print formats numbers using OFMT
  684.      or "%d" for exact integers.  "%c" with  a  numeric  argument
  685.      prints  the  corresponding  8  bit  character, with a string
  686.      argument it prints the first character of the  string.   The
  687.      output  of  print  and printf can be redirected to a file or
  688.      command by appending > file, >> file or | command to the end
  689.      of  the  print statement.  Redirection opens file or command
  690.      only once, subsequent redirections  append  to  the  already
  691.      open  stream.   By  convention, mawk associates the filename
  692.      "/dev/stderr" with stderr which allows print and  printf  to
  693.      be  redirected  to  stderr.   mawk  also  associates "-" and
  694.      "/dev/stdout" with  stdin  and  stdout  which  allows  these
  695.      streams to be passed to functions.
  696.  
  697.      The input function getline has the following variations.
  698.  
  699.           getline
  700.                reads into $0, updates the fields, NF, NR and FNR.
  701.  
  702.           getline < file
  703.                reads into $0 from file, updates  the  fields  and
  704.                NF.
  705.  
  706.           getline var
  707.                reads the next record into  var,  updates  NR  and
  708.                FNR.
  709.  
  710.           getline var < file
  711.                reads the next record of file into var.
  712.  
  713.            command | getline
  714.                pipes a record from command into  $0  and  updates
  715.                the fields and NF.
  716.  
  717.            command | getline var
  718.                pipes a record from command into var.
  719.  
  720.  
  721.  
  722.  
  723. Version 1.2         Last change: Dec 22 1994                   11
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. MAWK(1)                   USER COMMANDS                   MAWK(1)
  731.  
  732.  
  733.  
  734.      Getline returns 0 on end-of-file, -1 on error, otherwise 1.
  735.  
  736.      Commands on the end of pipes are executed by /bin/sh.
  737.  
  738.      The function close(expr) closes the file or pipe  associated
  739.      with  expr.   Close  returns  0 if expr is an open file, the
  740.      exit status if expr is a piped command,  and  -1  otherwise.
  741.      Close  is  used  to  reread a file or command, make sure the
  742.      other end of an output pipe is  finished  or  conserve  file
  743.      resources.
  744.  
  745.      The function fflush(expr) flushes the output  file  or  pipe
  746.      associated  with  expr.  Fflush returns 0 if expr is an open
  747.      output stream else -1.  Fflush without an  argument  flushes
  748.      stdout.  Fflush with an empty argument ("") flushes all open
  749.      output.
  750.  
  751.      The function system(expr) uses /bin/sh to execute  expr  and
  752.      returns  the  exit status of the command expr.  Changes made
  753.      to the ENVIRON array are not  passed  to  commands  executed
  754.      with system or pipes.
  755.  
  756.   10. User defined functions
  757.      The syntax for a user defined function is
  758.  
  759.           function name( args ) { statements }
  760.  
  761.      The function body can contain a return statement
  762.  
  763.           return opt_expr
  764.  
  765.      A return statement is not required. Function  calls  may  be
  766.      nested  or  recursive.   Functions are passed expressions by
  767.      value and arrays by reference.   Extra  arguments  serve  as
  768.      local  variables  and are initialized to null.  For example,
  769.      csplit(s,A) puts each  character  of  s  into  array  A  and
  770.      returns the length of s.
  771.  
  772.           function csplit(s, A,    n, i)
  773.           {
  774.             n = length(s)
  775.             for( i = 1 ; i <= n ; i++ ) A[i] = substr(s, i, 1)
  776.             return n
  777.           }
  778.  
  779.      Putting extra space between passed arguments and local vari-
  780.      ables  is  conventional.  Functions can be referenced before
  781.      they are defined, but the function name and the '('  of  the
  782.      arguments must touch to avoid confusion with concatenation.
  783.  
  784.   11. Splitting strings, records and files
  785.      Awk programs use the same algorithm to  split  strings  into
  786.  
  787.  
  788.  
  789. Version 1.2         Last change: Dec 22 1994                   12
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. MAWK(1)                   USER COMMANDS                   MAWK(1)
  797.  
  798.  
  799.  
  800.      arrays  with  split(),  and records into fields on FS.  mawk
  801.      uses essentially the same  algorithm  to  split  files  into
  802.      records on RS.
  803.  
  804.      Split(expr,A,sep) works as follows:
  805.  
  806.           (1)  If sep is omitted, it is replaced by FS.  Sep  can
  807.                be  an expression or regular expression.  If it is
  808.                an expression of non-string type, it is  converted
  809.                to string.
  810.  
  811.           (2)  If sep = " " (a single  space),  then  <SPACE>  is
  812.                trimmed  from  the front and back of expr, and sep
  813.                becomes <SPACE>.  mawk defines <SPACE> as the reg-
  814.                ular   expression  /[ \t\n]+/.  Otherwise  sep  is
  815.                treated  as  a  regular  expression,  except  that
  816.                meta-characters are ignored for a string of length
  817.                1, e.g., split(x, A, "*") and  split(x,  A,  /\*/)
  818.                are the same.
  819.  
  820.           (3)  If expr is not string, it is converted to  string.
  821.                If  expr  is  then  the  empty  string "", split()
  822.                returns 0 and A  is  set  empty.   Otherwise,  all
  823.                non-overlapping,  non-null  and longest matches of
  824.                sep in expr, separate expr into fields  which  are
  825.                loaded  into  A.   The  fields are placed in A[1],
  826.                A[2], ..., A[n] and split() returns n, the  number
  827.                of fields which is the number of matches plus one.
  828.                Data placed in  A  that  looks  numeric  is  typed
  829.                number and string.
  830.  
  831.      Splitting records into fields  works  the  same  except  the
  832.      pieces  are loaded into $1, $2,..., $NF.  If $0 is empty, NF
  833.      is set to 0 and all $i to "".
  834.  
  835.      mawk splits files into records by the  same  algorithm,  but
  836.      with  the  slight  difference that RS is really a terminator
  837.      instead of a separator. (ORS is really a terminator too).
  838.  
  839.           E.g., if FS = ":+" and $0 = "a::b:" , then NF =  3  and
  840.           $1  =  "a", $2 = "b" and $3 = "", but if "a::b:" is the
  841.           contents of an input file and RS = ":+", then there are
  842.           two records "a" and "b".
  843.  
  844.      RS = " " is not special.
  845.  
  846.      If FS = "", then mawk  breaks  the  record  into  individual
  847.      characters, and, similarly, split(s,A,"") places the indivi-
  848.      dual characters of s into A.
  849.  
  850.   12. Multi-line records
  851.      Since mawk interprets RS as a regular expression, multi-line
  852.  
  853.  
  854.  
  855. Version 1.2         Last change: Dec 22 1994                   13
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. MAWK(1)                   USER COMMANDS                   MAWK(1)
  863.  
  864.  
  865.  
  866.      records  are  easy.  Setting RS = "\n\n+", makes one or more
  867.      blank lines separate records.  If FS = "  "  (the  default),
  868.      then single newlines, by the rules for <SPACE> above, become
  869.      space and single newlines are field separators.
  870.  
  871.           For example, if a file is "a b\nc\n\n",  RS  =  "\n\n+"
  872.           and  FS  =  " ", then there is one record "a b\nc" with
  873.           three fields "a", "b" and "c".   Changing  FS  =  "\n",
  874.           gives two fields "a b" and "c"; changing FS = "", gives
  875.           one field identical to the record.
  876.  
  877.      If you want lines with  spaces  or  tabs  to  be  considered
  878.      blank,  set  RS  =  "\n([ \t]*\n)+".  For compatibility with
  879.      other awks, setting RS = "" has the same effect as if  blank
  880.      lines are stripped from the front and back of files and then
  881.      records are determined as if RS = "\n\n+".   Posix  requires
  882.      that  "\n"  always separates records when RS = "" regardless
  883.      of the value of FS.  mawk does not support this  convention,
  884.      because defining "\n" as <SPACE> makes it unnecessary.
  885.  
  886.      Most of the time when you change RS for multi-line  records,
  887.      you  will  also  want  to change ORS to "\n\n" so the record
  888.      spacing is preserved on output.
  889.  
  890.   13. Program execution
  891.      This section  describes  the  order  of  program  execution.
  892.      First  ARGC is set to the total number of command line argu-
  893.      ments passed to the execution phase of the program.  ARGV[0]
  894.      is  set  the  name  of  the  AWK interpreter and ARGV[1] ...
  895.      ARGV[ARGC-1] holds  the  remaining  command  line  arguments
  896.      exclusive of options and program source.  For example with
  897.  
  898.           mawk  -f  prog  v=1  A  t=hello  B
  899.  
  900.      ARGC = 5 with ARGV[0] = "mawk", ARGV[1] = "v=1",  ARGV[2]  =
  901.      "A", ARGV[3] = "t=hello" and ARGV[4] = "B".
  902.  
  903.      Next, each BEGIN block is executed in order.  If the program
  904.      consists  entirely  of  BEGIN  blocks,  then  execution ter-
  905.      minates, else an input stream is opened and  execution  con-
  906.      tinues.  If ARGC equals 1, the input stream is set to stdin,
  907.      else  the command line arguments  ARGV[1]  ...  ARGV[ARGC-1]
  908.      are examined for a file argument.
  909.  
  910.      The command line arguments  divide  into  three  sets:  file
  911.      arguments,  assignment  arguments  and empty strings "".  An
  912.      assignment has the form  var=string.   When  an  ARGV[i]  is
  913.      examined  as  a possible file argument, if it is empty it is
  914.      skipped; if it is an assignment argument, the assignment  to
  915.      var  takes  place  and  i  skips  to the next argument; else
  916.      ARGV[i] is opened for input.  If it fails to open, execution
  917.      terminates with exit code 2.  If no command line argument is
  918.  
  919.  
  920.  
  921. Version 1.2         Last change: Dec 22 1994                   14
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. MAWK(1)                   USER COMMANDS                   MAWK(1)
  929.  
  930.  
  931.  
  932.      a file argument, then input comes from stdin.  Getline in  a
  933.      BEGIN  action  opens  input.  "-" as a file argument denotes
  934.      stdin.
  935.  
  936.      Once an input stream is open, each input  record  is  tested
  937.      against  each  pattern,  and  if  it matches, the associated
  938.      action is executed.  An expression pattern matches if it  is
  939.      boolean  true  (see  the end of section 2).  A BEGIN pattern
  940.      matches before any input has been read, and an  END  pattern
  941.      matches  after  all  input  has been read.  A range pattern,
  942.      expr1,expr2 , matches every  record  between  the  match  of
  943.      expr1 and the match expr2 inclusively.
  944.  
  945.      When end of file occurs on the input stream,  the  remaining
  946.      command line arguments are examined for a file argument, and
  947.      if there is one it is opened, else the END pattern  is  con-
  948.      sidered matched and all END actions are executed.
  949.  
  950.      In the example, the assignment v=1  takes  place  after  the
  951.      BEGIN  actions  are  executed,  and  the data placed in v is
  952.      typed number and string.  Input is then read  from  file  A.
  953.      On  end  of file A, t is set to the string "hello", and B is
  954.      opened for input.  On end of file B,  the  END  actions  are
  955.      executed.
  956.  
  957.      Program flow at the pattern {action} level  can  be  changed
  958.      with the
  959.  
  960.           next
  961.           exit  opt_expr
  962.  
  963.      statements.  A next statement causes the next  input  record
  964.      to  be  read  and  pattern testing to restart with the first
  965.      pattern {action} pair in the  program.   An  exit  statement
  966.      causes  immediate  execution  of  the END actions or program
  967.      termination if there are none or if the exit  occurs  in  an
  968.      END action.  The opt_expr sets the exit value of the program
  969.      unless overridden by a later exit or subsequent error.
  970.  
  971. EXAMPLES
  972.      1. emulate cat.
  973.  
  974.           { print }
  975.  
  976.      2. emulate wc.
  977.  
  978.           { chars += length($0) + 1  # add one for the \n
  979.             words += NF
  980.           }
  981.  
  982.           END{ print NR, words, chars }
  983.  
  984.  
  985.  
  986.  
  987. Version 1.2         Last change: Dec 22 1994                   15
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. MAWK(1)                   USER COMMANDS                   MAWK(1)
  995.  
  996.  
  997.  
  998.      3. count the number of unique "real words".
  999.  
  1000.           BEGIN { FS = "[^A-Za-z]+" }
  1001.  
  1002.           { for(i = 1 ; i <= NF ; i++)  word[$i] = "" }
  1003.  
  1004.           END { delete word[""]
  1005.                 for ( i in word )  cnt++
  1006.                 print cnt
  1007.           }
  1008.  
  1009.      4. sum the second field of every record based on  the  first
  1010.      field.
  1011.  
  1012.           $1 ~ /credit|gain/ { sum += $2 }
  1013.           $1 ~ /debit|loss/  { sum -= $2 }
  1014.  
  1015.           END { print sum }
  1016.  
  1017.      5. sort a file, comparing as string
  1018.  
  1019.           { line[NR] = $0 "" }  # make sure of comparison type
  1020.                           # in case some lines look numeric
  1021.  
  1022.           END {  isort(line, NR)
  1023.             for(i = 1 ; i <= NR ; i++) print line[i]
  1024.           }
  1025.  
  1026.           #insertion sort of A[1..n]
  1027.           function isort( A, n,    i, j, hold)
  1028.           {
  1029.             for( i = 2 ; i <= n ; i++)
  1030.             {
  1031.               hold = A[j = i]
  1032.               while ( A[j-1] > hold )
  1033.               { j-- ; A[j+1] = A[j] }
  1034.               A[j] = hold
  1035.             }
  1036.             # sentinel A[0] = "" will be created if needed
  1037.           }
  1038.  
  1039.  
  1040. COMPATIBILITY ISSUES
  1041.      The Posix 1003.2(draft 11.3) definition of the AWK  language
  1042.      is  AWK  as  described in the AWK book with a few extensions
  1043.      that appeared in SystemVR4 nawk. The extensions are:
  1044.  
  1045.           New functions: toupper() and tolower().
  1046.  
  1047.           New variables: ENVIRON[] and CONVFMT.
  1048.  
  1049.           ANSI  C  conversion  specifications  for  printf()  and
  1050.  
  1051.  
  1052.  
  1053. Version 1.2         Last change: Dec 22 1994                   16
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. MAWK(1)                   USER COMMANDS                   MAWK(1)
  1061.  
  1062.  
  1063.  
  1064.           sprintf().
  1065.  
  1066.           New command options:  -v var=value, multiple -f options
  1067.           and implementation options as arguments to -W.
  1068.  
  1069.  
  1070.      Posix AWK is oriented to operate on files a line at a  time.
  1071.      RS can be changed from "\n" to another single character, but
  1072.      it is hard to find any use for this - there are no  examples
  1073.      in  the AWK book.  By convention, RS = "", makes one or more
  1074.      blank lines separate records, allowing  multi-line  records.
  1075.      When RS = "", "\n" is always a field separator regardless of
  1076.      the value in FS.
  1077.  
  1078.      mawk, on the other hand, allows RS to be a  regular  expres-
  1079.      sion.  When "\n" appears in records, it is treated as space,
  1080.      and FS always determines fields.
  1081.  
  1082.      Removing the line at a time paradigm can make some  programs
  1083.      simpler  and  can  often  improve performance.  For example,
  1084.      redoing example 3 from above,
  1085.  
  1086.           BEGIN { RS = "[^A-Za-z]+" }
  1087.  
  1088.           { word[ $0 ] = "" }
  1089.  
  1090.           END { delete  word[ "" ]
  1091.             for( i in word )  cnt++
  1092.             print cnt
  1093.           }
  1094.  
  1095.      counts the number of unique words  by  making  each  word  a
  1096.      record.   On  moderate  size  files,  mawk executes twice as
  1097.      fast, because of the simplified inner loop.
  1098.  
  1099.      The following program replaces  each  comment  by  a  single
  1100.      space in a C program file,
  1101.  
  1102.           BEGIN {
  1103.             RS = "/\*([^*]|\*+[^/*])*\*+/"
  1104.                # comment is record separator
  1105.             ORS = " "
  1106.             getline  hold
  1107.             }
  1108.  
  1109.             { print hold ; hold = $0 }
  1110.  
  1111.             END { printf "%s" , hold }
  1112.  
  1113.      Buffering one record is needed to avoid terminating the last
  1114.      record with a space.
  1115.  
  1116.  
  1117.  
  1118.  
  1119. Version 1.2         Last change: Dec 22 1994                   17
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. MAWK(1)                   USER COMMANDS                   MAWK(1)
  1127.  
  1128.  
  1129.  
  1130.      With mawk, the following are all equivalent,
  1131.  
  1132.           x ~ /a\+b/    x ~ "a\+b"     x ~ "a\\+b"
  1133.  
  1134.      The strings get scanned twice, once as string  and  once  as
  1135.      regular  expression.   On  the string scan, mawk ignores the
  1136.      escape on non-escape characters while the AWK book advocates
  1137.      \c be recognized as c which necessitates the double escaping
  1138.      of meta-characters in strings. Posix explicitly declines  to
  1139.      define  the  behavior  which  passively forces programs that
  1140.      must run under a variety of awks to use  the  more  portable
  1141.      but less readable, double escape.
  1142.  
  1143.      Posix AWK does not recognize "/dev/std{out,err}" or  \x  hex
  1144.      escape sequences in strings.  Unlike ANSI C, mawk limits the
  1145.      number of digits that follows  \x  to  two  as  the  current
  1146.      implementation only supports 8 bit characters.  The built-in
  1147.      fflush first appeared in a recent (1993) AT&T  awk  released
  1148.      to netlib, and is not part of the posix standard.  Aggregate
  1149.      deletion with delete array is not part of  the  posix  stan-
  1150.      dard.
  1151.  
  1152.      Posix explicitly leaves the behavior of FS =  ""  undefined,
  1153.      and  mentions splitting the record into characters as a pos-
  1154.      sible interpretation, but currently this use is not portable
  1155.      across implementations.
  1156.  
  1157.      Finally, here is how mawk handles exceptional cases not dis-
  1158.      cussed  in the AWK book or the Posix draft.  It is unsafe to
  1159.      assume consistency across awks and safe to skip to the  next
  1160.      section.
  1161.  
  1162.           substr(s, i, n) returns the  characters  of  s  in  the
  1163.           intersection  of the closed interval [1, length(s)] and
  1164.           the half-open interval [i, i+n).  When  this  intersec-
  1165.           tion  is  empty,  the  empty  string  is  returned;  so
  1166.           substr("ABC", 1, 0) = "" and  substr("ABC",  -4,  6)  =
  1167.           "A".
  1168.  
  1169.           Every string, including the empty string,  matches  the
  1170.           empty  string  at  the front so, s ~ // and s ~ "", are
  1171.           always 1 as is match(s, //) and match(s, "").  The last
  1172.           two set RLENGTH to 0.
  1173.  
  1174.           index(s, t) is always the same as match(s, t1) where t1
  1175.           is  the  same  as t with metacharacters escaped.  Hence
  1176.           consistency  with  match  requires  that  index(s,  "")
  1177.           always  returns 1.  Also the condition, index(s,t) != 0
  1178.           if  and  only  t  is  a  substring   of   s,   requires
  1179.           index("","") = 1.
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185. Version 1.2         Last change: Dec 22 1994                   18
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. MAWK(1)                   USER COMMANDS                   MAWK(1)
  1193.  
  1194.  
  1195.  
  1196.           If getline encounters end of file, getline var,  leaves
  1197.           var unchanged.  Similarly, on entry to the END actions,
  1198.           $0, the fields and NF have their value  unaltered  from
  1199.           the last record.
  1200.  
  1201. SEE ALSO
  1202.      egrep(1)
  1203.  
  1204.      Aho, Kernighan and Weinberger, The AWK Programming Language,
  1205.      Addison-Wesley Publishing, 1988, (the AWK book), defines the
  1206.      language, opening with a  tutorial  and  advancing  to  many
  1207.      interesting  programs  that  delve  into  issues of software
  1208.      design and analysis relevant to programming in any language.
  1209.  
  1210.      The GAWK Manual, The Free Software Foundation,  1991,  is  a
  1211.      tutorial  and  language  reference that does not attempt the
  1212.      depth of the AWK book and assumes the reader may be a novice
  1213.      programmer. The section on AWK arrays is excellent.  It also
  1214.      discusses Posix requirements for AWK.
  1215.  
  1216. BUGS
  1217.      mawk cannot handle ascii NUL \0 in the source or data files.
  1218.      You can output NUL using printf with %c, and any other 8 bit
  1219.      character is acceptable input.
  1220.  
  1221.      mawk implements printf() and sprintf() using the  C  library
  1222.      functions,  printf  and  sprintf, so full ANSI compatibility
  1223.      requires an ANSI C library.  In practice this  means  the  h
  1224.      conversion qualifier may not be available.  Also mawk inher-
  1225.      its any bugs or limitations of the library functions.
  1226.  
  1227.      Implementors of the AWK language  have  shown  a  consistent
  1228.      lack of imagination when naming their programs.
  1229.  
  1230. AUTHOR
  1231.      Mike Brennan (brennan@whidbey.com).
  1232.  
  1233.  
  1234.  
  1235.  
  1236.  
  1237.  
  1238.  
  1239.  
  1240.  
  1241.  
  1242.  
  1243.  
  1244.  
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251. Version 1.2         Last change: Dec 22 1994                   19
  1252.  
  1253.  
  1254.  
  1255.