man entry for awk

mawk - pattern scanning and text processing language

SYNOPSIS
       mawk [-W  option]  [-F value] [-v var=value] [--] 'program text' [file ...]
       mawk [-W option] [-F value] [-v var=value] [-f program-file] [--] [file ...]

DESCRIPTION
       mawk is an interpreter for the AWK Programming Language.  The AWK lan-
       guage is useful for manipulation of data files, text retrieval and pro-
       cessing,  and  for prototyping and experimenting with algorithms.  mawk
       is a new awk meaning it implements the AWK language as defined in  Aho,
       Kernighan  and Weinberger, The AWK Programming Language, Addison-Wesley
       Publishing, 1988.  (Hereafter referred to as the AWK book.)  mawk  con-
       forms  to  the Posix 1003.2 (draft 11.3) definition of the AWK language
       which contains a few features not described in the AWK book,  and  mawk
       provides a small number of extensions.

       An  AWK  program  is  a sequence of pattern {action} pairs and function
       definitions.  Short programs are entered on the  command  line  usually
       enclosed  in ' ' to avoid shell interpretation.  Longer programs can be
       read in from a file with the -f option.  Data  input is read  from  the
       list  of files on the command line or from standard input when the list
       is empty.  The input is broken into records as determined by the record
       separator  variable,  RS.  Initially, RS = "\n" and records are synony-
       mous with lines.  Each record is compared against each pattern  and  if
       it matches, the program text for {action} is executed.

OPTIONS
       -F value       sets the field separator, FS, to value.

       -f file        Program  text is read from file instead of from the com-
                      mand line.  Multiple -f options are allowed.

       -v var=value   assigns value to program variable var.

       --             indicates the unambiguous end of options.

       The above options will be available with any Posix compatible implemen-
       tation  of  AWK,  and implementation specific options are prefaced with
       -W.  mawk provides six:

       -W version     mawk writes its version and copyright to stdout and com-
                      piled limits to stderr and exits 0.

       -W dump        writes  an assembler like listing of the internal repre-
                      sentation of the program to stdout and exits 0 (on  suc-
                      cessful compilation).

       -W interactive sets unbuffered writes to stdout and line buffered reads
                      from stdin.  Records from stdin are lines regardless  of
                      the value of RS.

       -W exec file   Program  text  is  read  from  file and this is the last
                      option. Useful on systems that support  the  #!   "magic
                      number" convention for executable scripts.

       -W sprintf=num adjusts  the  size  of mawk's internal sprintf buffer to
                      num bytes.  More than rare use of this option  indicates
                      mawk should be recompiled.

       -W posix_space forces mawk not to consider '\n' to be space.

       The  short  forms  -W[vdiesp] are recognized and on some systems -We is
       mandatory to avoid command line length limitations.

THE AWK LANGUAGE
   1. Program structure
       An AWK program is a sequence of pattern {action} pairs and  user  func-
       tion definitions.

       A pattern can be:
              BEGIN
              END
              expression
              expression , expression

       One, but not both, of pattern {action} can be omitted.   If {action} is
       omitted it is implicitly { print }.  If pattern is omitted, then it  is
       implicitly matched.  BEGIN and END patterns require an action.

       Statements  are terminated by newlines, semi-colons or both.  Groups of
       statements such as actions or loop bodies are blocked via { ... } as in
       C.   The  last  statement  in a block doesn't need a terminator.  Blank
       lines have no meaning; an empty statement is terminated  with  a  semi-
       colon.  Long statements can be continued with a backslash, \.  A state-
       ment can be broken without a backslash after a comma, left  brace,  &&,
       ||,  do,  else, the right parenthesis of an if, while or for statement,
       and the right parenthesis of a function definition.  A  comment  starts
       with # and extends to, but does not include the end of line.

       The following statements control program flow inside blocks.

              if ( expr ) statement

              if ( expr ) statement else statement

              while ( expr ) statement

              do statement while ( expr )

              for ( opt_expr ; opt_expr ; opt_expr ) statement

              for ( var in array ) statement

              continue

              break

   2. Data types, conversion and comparison
       There  are two basic data types, numeric and string.  Numeric constants
       can be integer like -2, decimal like 1.08, or  in  scientific  notation
       like  -1.1e4 or .28E-3.  All numbers are represented internally and all
       computations are done in floating point arithmetic.   So  for  example,
       the expression 0.2e2 == 20 is true and true is represented as 1.0.

       String constants are enclosed in double quotes.

                   "This is a string with a newline at the end.\n"

       Strings  can  be  continued  across a line by escaping (\) the newline.
       The following escape sequences are recognized.

            \\        \
            \"        "
            \a        alert, ascii 7
            \b        backspace, ascii 8
            \t        tab, ascii 9
            \n        newline, ascii 10
            \v        vertical tab, ascii 11
            \f        formfeed, ascii 12
            \r        carriage return, ascii 13
            \ddd      1, 2 or 3 octal digits for ascii ddd
            \xhh      1 or 2 hex digits for ascii  hh

       If you escape any other character \c, you get \c,  i.e.,  mawk  ignores
       the escape.

       There are really three basic data types; the third is number and string
       which has both a numeric value and a string value  at  the  same  time.
       User  defined  variables  come into existence when first referenced and
       are initialized to null, a number and string value  which  has  numeric
       value  0 and string value "".  Non-trivial number and string typed data
       come from input and are typically stored in fields.  (See section 4).

       The type of an expression is determined by its  context  and  automatic
       type  conversion occurs if needed.  For example, to evaluate the state-
       ments

            y = x + 2  ;  z = x  "hello"

       The value stored in variable y will be typed  numeric.   If  x  is  not
       numeric,  the  value  read  from x is converted to numeric before it is
       added to 2 and stored in y.  The value stored in  variable  z  will  be
       typed  string, and the value of x will be converted to string if neces-
       sary and concatenated with "hello".  (Of course,  the  value  and  type
       stored in x is not changed by any conversions.)  A string expression is
       converted to numeric using its longest numeric prefix as with  atof(3).
       A  numeric  expression  is  converted  to string by replacing expr with
       sprintf(CONVFMT, expr), unless expr can  be  represented  on  the  host
       machine  as  an  exact  integer  then  it is converted to sprintf("%d",
       expr).  Sprintf() is an AWK built-in that duplicates the  functionality
       of  sprintf(3),  and  CONVFMT  is a built-in variable used for internal
       conversion from number to string and initialized to  "%.6g".   Explicit
       type  conversions  can  be  forced,  expr  ""  is  string and expr+0 is
       numeric.

       To evaluate, expr1 rel-op expr2, if both operands are numeric or number
       and  string then the comparison is numeric; if both operands are string
       the comparison is string; if one  operand  is  string,  the  non-string
       operand  is  converted  and  the  comparison  is string.  The result is
       numeric, 1 or 0.

       In boolean contexts such as, if ( expr ) statement, a string expression
       evaluates  true  if  and only if it is not the empty string ""; numeric
       values if and only if not numerically zero.

   3. Regular expressions
       In the AWK language, records, fields and strings are often  tested  for
       matching  a  regular  expression.   Regular expressions are enclosed in
       slashes, and

            expr ~ /r/

       is an AWK expression that evaluates to 1 if  expr  "matches"  r,  which
       means  a substring of expr is in the set of strings defined by r.  With
       no match the expression evaluates to  0;  replacing  ~  with  the  "not
       match" operator, !~ , reverses the meaning.  As  pattern-action pairs,

            /r/ { action }   and   $0 ~ /r/ { action }

       are  the  same,  and  for  each  input record that matches r, action is
       executed.  In fact, /r/ is an AWK expression that is equivalent to  ($0
       ~  /r/)  anywhere  except when on the right side of a match operator or
       passed as an argument to a built-in function  that  expects  a  regular
       expression argument.

       AWK  uses  extended  regular expressions as with egrep(1).  The regular
       expression metacharacters, i.e., those with special meaning in  regular
       expressions are

             ^ $ . [ ] | ( ) * + ?

       Regular expressions are built up from characters as follows:

              c            matches any non-metacharacter c.

              \c           matches  a  character  defined  by  the same escape
                           sequences used in string constants or  the  literal
                           character c if \c is not an escape sequence.

              .            matches any character (including newline).

              ^            matches the front of a string.

              $            matches the back of a string.

              [c1c2c3...]  matches  any character in the class c1c2c3... .  An
                           interval of characters is denoted  c1-c2  inside  a
                           class [...].

              [^c1c2c3...] matches any character not in the class c1c2c3...

       Regular expressions are built up from other regular expressions as fol-
       lows:

              r1r2         matches r1 followed immediately by  r2  (concatena-
                           tion).

              r1 | r2      matches r1 or r2 (alternation).

              r*           matches r repeated zero or more times.

              r+           matches r repeated one or more times.

              r?           matches r zero or once.

              (r)          matches r, providing grouping.

       The  increasing  precedence  of operators is alternation, concatenation
       and unary (*, + or ?).

       For example,

            /^[_a-zA-Z][_a-zA-Z0-9]*$/  and
            /^[-+]?([0-9]+\.?|\.[0-9])[0-9]*([eE][-+]?[0-9]+)?$/

       are matched by AWK identifiers and AWK numeric constants  respectively.
       Note  that . has to be escaped to be recognized as a decimal point, and
       that metacharacters are not special inside character classes.

       Any expression can be used on the right hand side of the ~ or !~ opera-
       tors  or  passed  to  a built-in that expects a regular expression.  If
       needed, it is converted to string, and then interpreted  as  a  regular
       expression.  For example,

            BEGIN { identifier = "[_a-zA-Z][_a-zA-Z0-9]*" }

            $0 ~ "^" identifier

       prints all lines that start with an AWK identifier.

       mawk  recognizes  the  empty  regular expression, //, which matches the
       empty string and hence is matched by any string at the front, back  and
       between every character.  For example,

            echo  abc | mawk { gsub(//, "X") ; print }
            XaXbXcX


   4. Records and fields
       Records are read in one at a time, and stored in the field variable $0.
       The record is split into fields which are stored in $1, $2,  ...,  $NF.
       The built-in variable NF is set to the number of fields, and NR and FNR
       are incremented by 1.  Fields above $NF are set to "".

       Assignment to $0 causes the fields and NF to be recomputed.  Assignment
       to  NF or to a field causes $0 to be reconstructed by concatenating the
       $i's separated by OFS.  Assignment to a field with index  greater  than
       NF increases NF and causes $0 to be reconstructed.

       Data  input  stored  in  fields  is string, unless the entire field has
       numeric form and then the type is number and string.  For example,

            echo 24 24E |
            mawk '{ print($1>100, $1>"100", $2>100, $2>"100") }'
            0 1 1 1

       $0 and $2 are string and $1 is number and string.  The first comparison
       is numeric, the second is string, the third is string (100 is converted
       to "100"), and the last is string.

   5. Expressions and operators
       The expression syntax is similar to C.  Primary expressions are numeric
       constants,  string  constants,  variables,  fields, arrays and function
       calls.  The identifier for a variable,  array  or  function  can  be  a
       sequence of letters, digits and underscores, that does not start with a
       digit.  Variables are not declared; they exist  when  first  referenced
       and are initialized to null.

       New  expressions  are composed with the following operators in order of
       increasing precedence.

              assignment          =  +=  -=  *=  /=  %=  ^=
              conditional         ?  :
              logical or          ||
              logical and         &&
              array membership    iinn
              matching       ~   !~
              relational          <  >   <=  >=  ==  !=
              concatenation       (no explicit operator)
              add ops             +  -
              mul ops             *  /  %
              unary               +  -
              logical not         !
              exponentiation      ^
              inc and dec         ++ -- (both post and pre)
              field               $

       Assignment, conditional and exponentiation associate right to left; the
       other  operators associate left to right.  Any expression can be paren-
       thesized.

...

   9. Input and output
       There are two output statements, print and printf.

              print  writes $0  ORS to standard output.

              print expr1, expr2, ..., exprn
                     writes expr1 OFS expr2 OFS ... exprn ORS to standard out-
                     put.   Numeric  expressions  are converted to string with
                     OFMT.

              printf format, expr-list
                     duplicates the printf C library function writing to stan-
                     dard  output.   The complete ANSI C format specifications
                     are recognized with conversions %c, %d, %e, %E,  %f,  %g,
                     %G,  %i, %o, %s, %u, %x, %X and %%, and conversion quali-
                     fiers h and l.

       The argument list to print or printf  can  optionally  be  enclosed  in
       parentheses.   Print formats numbers using OFMT or "%d" for exact inte-
       gers.  "%c" with a numeric argument  prints  the  corresponding  8  bit
       character,  with a string argument it prints the first character of the
       string.  The output of print and printf can be redirected to a file  or
       command  by  appending  >  file, >> file or | command to the end of the
       print statement.  Redirection opens file or command only  once,  subse-
       quent  redirections  append to the already open stream.  By convention,
       mawk associates the filename "/dev/stderr"  with  stderr  which  allows
       print  and printf to be redirected to stderr.  mawk also associates "-"
       and "/dev/stdout" with stdin and stdout which allows these  streams  to
       be passed to functions.

       The input function getline has the following variations.

              getline
                     reads into $0, updates the fields NF, NR and FNR.

              getline < file
                     reads into $0 from file, updates the fields and NF.

              getline var
                     reads the next record into var, updates NR and FNR.

              getline var < file
                     reads the next record of file into var.

               command | getline
                     pipes  a  record  from  command  into  $0 and updates the
                     fields and NF.

               command | getline var
                     pipes a record from command into var.

       Getline returns 0 on end-of-file, -1 on error, otherwise 1.

       Commands on the end of pipes are executed by /bin/sh.

       The function close(expr) closes the file or pipe associated with  expr.
       Close  returns  0 if expr is an open file, the exit status if expr is a
       piped command, and -1 otherwise.  Close is used to  reread  a  file  or
       command,  make sure the other end of an output pipe is finished or con-
       serve file resources.

       The function fflush(expr) flushes the output file  or  pipe  associated
       with  expr.  Fflush returns 0 if expr is an open output stream else -1.
       Fflush without an argument flushes stdout.  Fflush with an empty  argu-
       ment ("") flushes all open output.

       The  function system(expr) uses /bin/sh to execute expr and returns the
       exit status of the command expr.  Changes made to the ENVIRON array are
       not passed to commands executed with system or pipes.

...

13. Program execution
       This section describes the order of program execution.  First  ARGC  is
       set  to the total number of command line arguments passed to the execu-
       tion phase of the program.  ARGV[0] is set the name of the  AWK  inter-
       preter  and  ARGV[1] ...  ARGV[ARGC-1] holds the remaining command line
       arguments exclusive of options and program source.  For example with

            mawk  -f  prog  v=1  A  t=hello  B

       ARGC = 5 with ARGV[0] = "mawk", ARGV[1] = "v=1", ARGV[2] = "A", ARGV[3]
       = "t=hello" and ARGV[4] = "B".

       Next,  each  BEGIN block is executed in order.  If the program consists
       entirely of BEGIN blocks, then  execution  terminates,  else  an  input
       stream  is opened and execution continues.  If ARGC equals 1, the input
       stream is set to stdin, else  the command line  arguments  ARGV[1]  ...
       ARGV[ARGC-1] are examined for a file argument.

       The  command  line  arguments  divide  into three sets: file arguments,
       assignment arguments and empty strings "".  An assignment has the  form
       var=string.   When  an ARGV[i] is examined as a possible file argument,
       if it is empty it is skipped; if it  is  an  assignment  argument,  the
       assignment  to  var  takes place and ii skips to the next argument; else
       ARGV[i] is opened for input.  If it fails to open, execution terminates
       with exit code 2.  If no command line argument is a file argument, then
       input comes from stdin.  Getline in a BEGIN action opens input.  "-" as
       a file argument denotes stdin.

       Once  an input stream is open, each input record is tested against each
       pattern, and if it matches, the  associated  action  is  executed.   An
       expression  pattern  matches if it is boolean true (see the end of sec-
       tion 2).  A BEGIN pattern matches before any input has been  read,  and
       an END pattern matches after all input has been read.  A range pattern,
       expr1,expr2 , matches every record between the match of expr1  and  the
       match expr2 inclusively.

       When end of file occurs on the input stream, the remaining command line
       arguments are examined for a file argument, and if there is one  it  is
       opened,  else the END pattern is considered matched and all END actions
       are executed.

       In the example, the assignment v=1 takes place after the BEGIN  actions
       are  executed,  and  the  data  placed in v is typed number and string.
       Input is then read from file A.  On end of file A,  t  is  set  to  the
       string  "hello",  and B is opened for input.  On end of file B, the END
       actions are executed.

       Program flow at the pattern {action} level can be changed with the

            next
            exit  opt_expr

       statements.  A next statement causes the next input record to  be  read
       and  pattern testing to restart with the first pattern {action} pair in
       the program.  An exit statement causes immediate execution of  the  END
       actions  or program termination if there are none or if the exit occurs
       in an END action.  The opt_expr sets the  exit  value  of  the  program
       unless overridden by a later exit or subsequent error.