• gawk和mawk的区别笔记221108


    发现Ubuntu22.04的桌面版和服务器版的awk是不同的实现
    Ubuntu22.04Server服务器版默认用的是gawk , 也带mawk
    Ubuntu22.04Desktop桌面版用的是mawk 不带gawk

    Server版既有gawk,又有mawk, 默认gawk

    root@us224-1:~# mawk
    Usage: mawk [Options] [Program] [file ...]
    
    Program:
        The -f option value is the name of a file containing program text.
        If no -f option is given, a "--" ends option processing; the following
        parameters are the program text.
    
    Options:
        -f program-file  Program  text is read from file instead of from the
                         command-line.  Multiple -f options are accepted.
        -F value         sets the field separator, FS, to value.
        -v var=value     assigns value to program variable var.
        --               unambiguous end of options.
    
        Implementation-specific options are prefixed with "-W".  They can be
        abbreviated:
    
        -W version       show version information and exit.
        -W dump          show assembler-like listing of program and exit.
        -W help          show this message and exit.
        -W interactive   set unbuffered output, line-buffered input.
        -W exec file     use file as program as well as last option.
        -W random=number set initial random seed.
        -W sprintf=number adjust size of sprintf buffer.
        -W posix_space   do not consider "\n" a space.
        -W usage         show this message and exit.
    root@us224-1:~# gawk
    Usage: gawk [POSIX or GNU style options] -f progfile [--] file ...
    Usage: gawk [POSIX or GNU style options] [--] 'program' file ...
    POSIX options:          GNU long options: (standard)
            -f progfile             --file=progfile
            -F fs                   --field-separator=fs
            -v var=val              --assign=var=val
    Short options:          GNU long options: (extensions)
            -b                      --characters-as-bytes
            -c                      --traditional
            -C                      --copyright
            -d[file]                --dump-variables[=file]
            -D[file]                --debug[=file]
            -e 'program-text'       --source='program-text'
            -E file                 --exec=file
            -g                      --gen-pot
            -h                      --help
            -i includefile          --include=includefile
            -l library              --load=library
            -L[fatal|invalid|no-ext]        --lint[=fatal|invalid|no-ext]
            -M                      --bignum
            -N                      --use-lc-numeric
            -n                      --non-decimal-data
            -o[file]                --pretty-print[=file]
            -O                      --optimize
            -p[file]                --profile[=file]
            -P                      --posix
            -r                      --re-interval
            -s                      --no-optimize
            -S                      --sandbox
            -t                      --lint-old
            -V                      --version
    
    To report bugs, see node `Bugs' in `gawk.info'
    which is section `Reporting Problems and Bugs' in the
    printed version.  This same information may be found at
    https://www.gnu.org/software/gawk/manual/html_node/Bugs.html.
    PLEASE do NOT try to report bugs by posting in comp.lang.awk,
    or by using a web forum such as Stack Overflow.
    
    gawk is a pattern scanning and processing language.
    By default it reads standard input and writes standard output.
    
    Examples:
            gawk '{ sum += $1 }; END { print sum }' file
            gawk -F: '{ print $1 }' /etc/passwd
    root@us224-1:~# 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    Desktop版只有mawk, 没有gawk

    root@ud224:/test# gawk
    Command 'gawk' not found, but can be installed with:
    apt install gawk
    root@ud224:/test# mawk
    Usage: mawk [Options] [Program] [file ...]
    
    Program:
        The -f option value is the name of a file containing program text.
        If no -f option is given, a "--" ends option processing; the following
        parameters are the program text.
    
    Options:
        -f program-file  Program  text is read from file instead of from the
                         command-line.  Multiple -f options are accepted.
        -F value         sets the field separator, FS, to value.
        -v var=value     assigns value to program variable var.
        --               unambiguous end of options.
    
        Implementation-specific options are prefixed with "-W".  They can be
        abbreviated:
    
        -W version       show version information and exit.
        -W dump          show assembler-like listing of program and exit.
        -W help          show this message and exit.
        -W interactive   set unbuffered output, line-buffered input.
        -W exec file     use file as program as well as last option.
        -W random=number set initial random seed.
        -W sprintf=number adjust size of sprintf buffer.
        -W posix_space   do not consider "\n" a space.
        -W usage         show this message and exit.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    22.10 Server版输入awk

    root@us2210-1:~# awk
    Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
    Usage: awk [POSIX or GNU style options] [--] 'program' file ...
    POSIX options:          GNU long options: (standard)
            -f progfile             --file=progfile
            -F fs                   --field-separator=fs
            -v var=val              --assign=var=val
    Short options:          GNU long options: (extensions)
            -b                      --characters-as-bytes
            -c                      --traditional
            -C                      --copyright
            -d[file]                --dump-variables[=file]
            -D[file]                --debug[=file]
            -e 'program-text'       --source='program-text'
            -E file                 --exec=file
            -g                      --gen-pot
            -h                      --help
            -i includefile          --include=includefile
            -l library              --load=library
            -L[fatal|invalid|no-ext]        --lint[=fatal|invalid|no-ext]
            -M                      --bignum
            -N                      --use-lc-numeric
            -n                      --non-decimal-data
            -o[file]                --pretty-print[=file]
            -O                      --optimize
            -p[file]                --profile[=file]
            -P                      --posix
            -r                      --re-interval
            -s                      --no-optimize
            -S                      --sandbox
            -t                      --lint-old
            -V                      --version
    
    To report bugs, see node `Bugs' in `gawk.info'
    which is section `Reporting Problems and Bugs' in the
    printed version.  This same information may be found at
    https://www.gnu.org/software/gawk/manual/html_node/Bugs.html.
    PLEASE do NOT try to report bugs by posting in comp.lang.awk,
    or by using a web forum such as Stack Overflow.
    
    gawk is a pattern scanning and processing language.
    By default it reads standard input and writes standard output.
    
    Examples:
            awk '{ sum += $1 }; END { print sum }' file
            awk -F: '{ print $1 }' /etc/passwd
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    22.04 Server版输入awk

    root@us224-1:~# awk
    Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
    Usage: awk [POSIX or GNU style options] [--] 'program' file ...
    POSIX options:          GNU long options: (standard)
            -f progfile             --file=progfile
            -F fs                   --field-separator=fs
            -v var=val              --assign=var=val
    Short options:          GNU long options: (extensions)
            -b                      --characters-as-bytes
            -c                      --traditional
            -C                      --copyright
            -d[file]                --dump-variables[=file]
            -D[file]                --debug[=file]
            -e 'program-text'       --source='program-text'
            -E file                 --exec=file
            -g                      --gen-pot
            -h                      --help
            -i includefile          --include=includefile
            -l library              --load=library
            -L[fatal|invalid|no-ext]        --lint[=fatal|invalid|no-ext]
            -M                      --bignum
            -N                      --use-lc-numeric
            -n                      --non-decimal-data
            -o[file]                --pretty-print[=file]
            -O                      --optimize
            -p[file]                --profile[=file]
            -P                      --posix
            -r                      --re-interval
            -s                      --no-optimize
            -S                      --sandbox
            -t                      --lint-old
            -V                      --version
    
    To report bugs, see node `Bugs' in `gawk.info'
    which is section `Reporting Problems and Bugs' in the
    printed version.  This same information may be found at
    https://www.gnu.org/software/gawk/manual/html_node/Bugs.html.
    PLEASE do NOT try to report bugs by posting in comp.lang.awk,
    or by using a web forum such as Stack Overflow.
    
    gawk is a pattern scanning and processing language.
    By default it reads standard input and writes standard output.
    
    Examples:
            awk '{ sum += $1 }; END { print sum }' file
            awk -F: '{ print $1 }' /etc/passwd
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    22.04 桌面版输入 awk

    root@ud224:/test# awk
    Usage: mawk [Options] [Program] [file ...]
    
    Program:
        The -f option value is the name of a file containing program text.
        If no -f option is given, a "--" ends option processing; the following
        parameters are the program text.
    
    Options:
        -f program-file  Program  text is read from file instead of from the
                         command-line.  Multiple -f options are accepted.
        -F value         sets the field separator, FS, to value.
        -v var=value     assigns value to program variable var.
        --               unambiguous end of options.
    
        Implementation-specific options are prefixed with "-W".  They can be
        abbreviated:
    
        -W version       show version information and exit.
        -W dump          show assembler-like listing of program and exit.
        -W help          show this message and exit.
        -W interactive   set unbuffered output, line-buffered input.
        -W exec file     use file as program as well as last option.
        -W random=number set initial random seed.
        -W sprintf=number adjust size of sprintf buffer.
        -W posix_space   do not consider "\n" a space.
        -W usage         show this message and exit.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    22.10 Server版产看版本用 awk -V

    root@us2210-1:~# awk -V
    GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.1.0, GNU MP 6.2.1)
    Copyright (C) 1989, 1991-2020 Free Software Foundation.
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program. If not, see http://www.gnu.org/licenses/.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    22.04 Server版产看版本用 awk -V

    root@us224-1:~# awk -V
    GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.1.0, GNU MP 6.2.1)
    Copyright (C) 1989, 1991-2020 Free Software Foundation.
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
    along with this program. If not, see http://www.gnu.org/licenses/.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    22.04 Desktop版查看版本用 awk -W version

    root@ud224:/test# awk -W version
    mawk 1.3.4 20200120
    Copyright 2008-2019,2020, Thomas E. Dickey
    Copyright 1991-1996,2014, Michael D. Brennan
    
    random-funcs:       srandom/random
    regex-funcs:        internal
    compiled limits:
    sprintf buffer      8192
    maximum-integer     2147483647
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    UbuntuServer2210 的 man gawk

    GAWK(1) Utility Commands GAWK(1)

    NAME
    gawk - pattern scanning and processing language

    SYNOPSIS
    gawk [ POSIX or GNU style options ] -f program-file [ – ] file …
    gawk [ POSIX or GNU style options ] [ – ] program-text file …

    DESCRIPTION
    Gawk is the GNU Project’s implementation of the AWK programming language. It conforms to the definition of the language in the
    POSIX 1003.1 standard. This version in turn is based on the description in The AWK Programming Language, by Aho, Kernighan,
    and Weinberger. Gawk provides the additional features found in the current version of Brian Kernighan’s awk and numerous GNU-
    specific extensions.

       The command line consists of options to gawk itself, the AWK program text (if not supplied via the -f  or  --include  options),
       and values to be made available in the ARGC and ARGV pre-defined AWK variables.
    
       When  gawk  is  invoked  with the --profile option, it starts gathering profiling statistics from the execution of the program.
       Gawk runs more slowly in this mode, and automatically produces an execution profile in the file awkprof.out when done.  See the
       --profile option, below.
    
       Gawk  also  has  an integrated debugger. An interactive debugging session can be started by supplying the --debug option to the
       command line. In this mode of execution, gawk loads the AWK source code and then prompts for debugging commands.  Gawk can only
       debug  AWK  program  source provided with the -f and --include options.  The debugger is documented in GAWK: Effective AWK Pro‐
       gramming.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    OPTION FORMAT
    Gawk options may be either traditional POSIX-style one letter options, or GNU-style long options. POSIX options start with a
    single “-”, while long options start with “–”. Long options are provided for both GNU-specific features and for POSIX-man‐
    dated features.

       Gawk-specific options are typically used in long-option form.  Arguments to long options are either joined with the  option  by
       an = sign, with no intervening spaces, or they may be provided in the next command line argument.  Long options may be abbrevi‐
       ated, as long as the abbreviation remains unique.
    
       Additionally, every long option has a corresponding short option, so that the option's functionality may be used from within #!
       executable scripts.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    OPTIONS
    Gawk accepts the following options. Standard options are listed first, followed by options for gawk extensions, listed alpha‐
    betically by short option.

       -f program-file
       --file program-file
              Read the AWK program source from the file program-file, instead of from the first command line  argument.   Multiple  -f
              (or  --file)  options  may  be  used.  Files read with -f are treated as if they begin with an implicit @namespace "awk"
              statement.
    
       -F fs
       --field-separator fs
              Use fs for the input field separator (the value of the FS predefined variable).
    
       -v var=val
       --assign var=val
              Assign the value val to the variable var, before execution of the program begins.  Such variable values are available to
              the BEGIN rule of an AWK program.
    
       -b
       --characters-as-bytes
              Treat  all  input data as single-byte characters. In other words, don't pay any attention to the locale information when
              attempting to process strings as multibyte characters.  The --posix option overrides this one.
    
       -c
       --traditional
              Run in compatibility mode.  In compatibility mode, gawk behaves identically to Brian Kernighan's awk; none of  the  GNU-
              specific extensions are recognized.  See GNU EXTENSIONS, below, for more information.
    
       -C
       --copyright
              Print the short version of the GNU copyright information message on the standard output and exit successfully.
    
       -d[file]
       --dump-variables[=file]
              Print a sorted list of global variables, their types and final values to file.  If no file is provided, gawk uses a file
              named awkvars.out in the current directory.
              Having a list of all the global variables is a good way to look for typographical errors in your  programs.   You  would
              also  use  this  option if you have a large program with a lot of functions, and you want to be sure that your functions
              don't inadvertently use global variables that you meant to be local.  (This is a particularly easy mistake to make  with
              simple variable names like i, j, and so on.)
    
       -D[file]
       --debug[=file]
              Enable debugging of AWK programs.  By default, the debugger reads commands interactively from the keyboard (standard in‐
              put).  The optional file argument specifies a file with a list of commands for  the  debugger  to  execute  non-interac‐
              tively.
    
       -e program-text
       --source program-text
              Use program-text as AWK program source code.  This option allows the easy intermixing of library functions (used via the
              -f and --include options) with source code entered on the command line.  It is intended primarily for  medium  to  large
              AWK  programs  used  in shell scripts.  Each argument supplied via -e is treated as if it begins with an implicit @name‐
              space "awk" statement.
    
       -E file
       --exec file
              Similar to -f, however, this is option is the last one processed.  This should be used with  #!   scripts,  particularly
              for  CGI  applications, to avoid passing in options or source code (!) on the command line from a URL.  This option dis‐
              ables command-line variable assignments.
    
       -g
       --gen-pot
              Scan and parse the AWK program, and generate a GNU .pot (Portable Object Template) format file on standard  output  with
              entries  for all localizable strings in the program.  The program itself is not executed.  See the GNU gettext distribu‐
              tion for more information on .pot files.
    
       -h
       --help Print a relatively short summary of the available options on the standard output.  (Per the GNU Coding Standards,  these
              options cause an immediate, successful exit.)
    
       -i include-file
       --include include-file
              Load  an  awk  source  library.   This  searches for the library using the AWKPATH environment variable.  If the initial
              search fails, another attempt will be made after appending the .awk suffix.  The file will be loaded  only  once  (i.e.,
              duplicates  are  eliminated),  and  the code does not constitute the main program source.  Files read with --include are
              treated as if they begin with an implicit @namespace "awk" statement.
    
       -l lib
       --load lib
              Load a gawk extension from the shared library lib.  This searches for the library using the AWKLIBPATH environment vari‐
              able.   If  the initial search fails, another attempt will be made after appending the default shared library suffix for
              the platform.  The library initialization routine is expected to be named dl_load().
    
       -L [value]
       --lint[=value]
              Provide warnings about constructs that are dubious or non-portable to other AWK implementations.  With an optional argu‐
              ment  of fatal, lint warnings become fatal errors.  This may be drastic, but its use will certainly encourage the devel‐
              opment of cleaner AWK programs.  With an optional argument of invalid, only warnings about things that are actually  in‐
              valid  are issued. (This is not fully implemented yet.)  With an optional argument of no-ext, warnings about gawk exten‐
              sions are disabled.
    
       -M
       --bignum
              Force arbitrary precision arithmetic on numbers. This option has no effect if gawk is not compiled to use the  GNU  MPFR
              and GMP libraries.  (In such a case, gawk issues a warning.)
    
       -n
       --non-decimal-data
              Recognize octal and hexadecimal values in input data.  Use this option with great caution!
    
       -N
       --use-lc-numeric
              Force  gawk  to  use the locale's decimal point character when parsing input data.  Although the POSIX standard requires
              this behavior, and gawk does so when --posix is in effect, the default is to follow traditional behavior and use  a  pe‐
              riod  as  the decimal point, even in locales where the period is not the decimal point character.  This option overrides
              the default behavior, without the full draconian strictness of the --posix option.
    
       -o[file]
       --pretty-print[=file]
              Output a pretty printed version of the program to file.  If no file is provided, gawk uses a file named  awkprof.out  in
              the current directory.  This option implies --no-optimize.
    
       -O
       --optimize
              Enable gawk's default optimizations upon the internal representation of the program.  Currently, this just includes sim‐
              ple constant folding.  This option is on by default.
    
       -p[prof-file]
       --profile[=prof-file]
              Start a profiling session, and send the profiling data to prof-file.  The default is awkprof.out.  The profile  contains
              execution  counts  of  each  statement  in the program in the left margin and function call counts for each user-defined
              function.  This option implies --no-optimize.
    
       -P
       --posix
              This turns on compatibility mode, with the following additional restrictions:
    
              • \x escape sequences are not recognized.
    
              • You cannot continue lines after ?  and :.
    
              • The synonym func for the keyword function is not recognized.
    
              • The operators ** and **= cannot be used in place of ^ and ^=.
    
       -r
       --re-interval
              Enable the use of interval expressions in regular expression matching (see Regular Expressions,  below).   Interval  ex‐
              pressions  were  not  traditionally available in the AWK language.  The POSIX standard added them, to make awk and egrep
              consistent with each other.  They are enabled by default, but this option remains for use together with --traditional.
    
       -s
       --no-optimize
              Disable gawk's default optimizations upon the internal representation of the program.
    
       -S
       --sandbox
              Run gawk in sandbox mode, disabling the system() function, input redirection with getline, output redirection with print
              and  printf,  and loading dynamic extensions.  Command execution (through pipelines) is also disabled.  This effectively
              blocks a script from accessing local resources, except for the files specified on the command line.
    
       -t
       --lint-old
              Provide warnings about constructs that are not portable to the original version of UNIX awk.
    
       -V
       --version
              Print version information for this particular copy of gawk on the standard output.  This is useful mainly for knowing if
              the  current  copy  of  gawk  on your system is up to date with respect to whatever the Free Software Foundation is dis‐
              tributing.  This is also useful when reporting bugs.  (Per the GNU Coding Standards, these options cause  an  immediate,
              successful exit.)
    
       --     Signal  the  end  of  options.  This is useful to allow further arguments to the AWK program itself to start with a “-”.
              This provides consistency with the argument parsing convention used by most other POSIX programs.
    
       In compatibility mode, any other options are flagged as invalid, but are otherwise ignored.  In normal operation,  as  long  as
       program  text  has  been  supplied, unknown options are passed on to the AWK program in the ARGV array for processing.  This is
       particularly useful for running AWK programs via the #!  executable interpreter mechanism.
    
       For POSIX compatibility, the -W option may be used, followed by the name of a long option.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167

    AWK PROGRAM EXECUTION
    An AWK program consists of a sequence of optional directives, pattern-action statements, and optional function definitions.

              @include "filename"
              @load "filename"
              @namespace "name"
              pattern   { action statements }
              function name(parameter list) { statements }
    
       Gawk first reads the program source from the program-file(s) if specified, from arguments to --source, or from the  first  non-
       option  argument  on the command line.  The -f and --source options may be used multiple times on the command line.  Gawk reads
       the program text as if all the program-files and command line source texts had been concatenated together.  This is useful  for
       building  libraries  of AWK functions, without having to include them in each new AWK program that uses them.  It also provides
       the ability to mix library functions with command line programs.
    
       In addition, lines beginning with @include may be used to include other source files into your program, making library use even
       easier.  This is equivalent to using the --include option.
    
       Lines  beginning  with @load may be used to load extension functions into your program.  This is equivalent to using the --load
       option.
    
       The environment variable AWKPATH specifies a search path to use when finding source files named with the -f and  --include  op‐
       tions.  If this variable does not exist, the default path is ".:/usr/local/share/awk".  (The actual directory may vary, depend‐
       ing upon how gawk was built and installed.)  If a file name given to the -f option contains a “/” character, no path search  is
       performed.
    
       The  environment variable AWKLIBPATH specifies a search path to use when finding source files named with the --load option.  If
       this variable does not exist, the default path is "/usr/local/lib/gawk".  (The actual directory may vary,  depending  upon  how
       gawk was built and installed.)
    
       Gawk  executes AWK programs in the following order.  First, all variable assignments specified via the -v option are performed.
       Next, gawk compiles the program into an internal form.  Then, gawk executes the code in the BEGIN rule(s) (if  any),  and  then
       proceeds to read each file named in the ARGV array (up to ARGV[ARGC-1]).  If there are no files named on the command line, gawk
       reads the standard input.
    
       If a filename on the command line has the form var=val it is treated as a variable assignment.  The variable var  will  be  as‐
       signed  the  value val.  (This happens after any BEGIN rule(s) have been run.)  Command line variable assignment is most useful
       for dynamically assigning values to the variables AWK uses to control how input is broken into fields and records.  It is  also
       useful for controlling state if multiple passes are needed over a single data file.
    
       If the value of a particular element of ARGV is empty (""), gawk skips over it.
    
       For  each input file, if a BEGINFILE rule exists, gawk executes the associated code before processing the contents of the file.
       Similarly, gawk executes the code associated with ENDFILE after processing the file.
    
       For each record in the input, gawk tests to see if it matches any pattern in the AWK program.  For each pattern that the record
       matches, gawk executes the associated action.  The patterns are tested in the order they occur in the program.
    
       Finally, after all the input is exhausted, gawk executes the code in the END rule(s) (if any).
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    Command Line Directories
    According to POSIX, files named on the awk command line must be text files. The behavior is ``undefined’’ if they are not.
    Most versions of awk treat a directory on the command line as a fatal error.

       Starting with version 4.0 of gawk, a directory on the command line produces a warning, but is otherwise skipped.  If either  of
       the --posix or --traditional options is given, then gawk reverts to treating directories on the command line as a fatal error.
    
    • 1
    • 2

    VARIABLES, RECORDS AND FIELDS
    AWK variables are dynamic; they come into existence when they are first used. Their values are either floating-point numbers
    or strings, or both, depending upon how they are used. Additionally, gawk allows variables to have regular-expression type.
    AWK also has one dimensional arrays; arrays with multiple dimensions may be simulated. Gawk provides true arrays of arrays;
    see Arrays, below. Several pre-defined variables are set as a program runs; these are described as needed and summarized be‐
    low.

    Records
    Normally, records are separated by newline characters. You can control how records are separated by assigning values to the
    built-in variable RS. If RS is any single character, that character separates records. Otherwise, RS is a regular expression.
    Text in the input that matches this regular expression separates the record. However, in compatibility mode, only the first
    character of its string value is used for separating records. If RS is set to the null string, then records are separated by
    empty lines. When RS is set to the null string, the newline character always acts as a field separator, in addition to what‐
    ever value FS may have.

    Fields
    As each input record is read, gawk splits the record into fields, using the value of the FS variable as the field separator.
    If FS is a single character, fields are separated by that character. If FS is the null string, then each individual character
    becomes a separate field. Otherwise, FS is expected to be a full regular expression. In the special case that FS is a single
    space, fields are separated by runs of spaces and/or tabs and/or newlines. NOTE: The value of IGNORECASE (see below) also af‐
    fects how fields are split when FS is a regular expression, and how records are separated when RS is a regular expression.

       If the FIELDWIDTHS variable is set to a space-separated list of numbers, each field is expected to have fixed width,  and  gawk
       splits up the record using the specified widths.  Each field width may optionally be preceded by a colon-separated value speci‐
       fying the number of characters to skip before the field starts.  The value of FS is ignored.  Assigning a new value  to  FS  or
       FPAT overrides the use of FIELDWIDTHS.
    
       Similarly,  if  the  FPAT  variable  is  set  to a string representing a regular expression, each field is made up of text that
       matches that regular expression. In this case, the regular expression describes the fields themselves, instead of the text that
       separates the fields.  Assigning a new value to FS or FIELDWIDTHS overrides the use of FPAT.
    
       Each field in the input record may be referenced by its position: $1, $2, and so on.  $0 is the whole record, including leading
       and trailing whitespace.  Fields need not be referenced by constants:
    
              n = 5
              print $n
    
       prints the fifth field in the input record.
    
       The variable NF is set to the total number of fields in the input record.
    
       References to non-existent fields (i.e., fields after $NF) produce the null string.  However, assigning to a non-existent field
       (e.g.,  $(NF+2) = 5) increases the value of NF, creates any intervening fields with the null string as their values, and causes
       the value of $0 to be recomputed, with the fields being separated by the value of OFS.  References to negative numbered  fields
       cause  a fatal error.  Decrementing NF causes the values of fields past the new value to be lost, and the value of $0 to be re‐
       computed, with the fields being separated by the value of OFS.
    
       Assigning a value to an existing field causes the whole record to be rebuilt when $0 is  referenced.   Similarly,  assigning  a
       value to $0 causes the record to be resplit, creating new values for the fields.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    Built-in Variables
    Gawk’s built-in variables are:

       ARGC        The number of command line arguments (does not include options to gawk, or the program source).
    
       ARGIND      The index in ARGV of the current file being processed.
    
       ARGV        Array  of  command  line arguments.  The array is indexed from 0 to ARGC - 1.  Dynamically changing the contents of
                   ARGV can control the files used for data.
    
       BINMODE     On non-POSIX systems, specifies use of “binary” mode for all file I/O.  Numeric values of 1, 2, or 3, specify  that
                   input files, output files, or all files, respectively, should use binary I/O.  String values of "r", or "w" specify
                   that input files, or output files, respectively, should use binary I/O.  String values of "rw" or "wr" specify that
                   all files should use binary I/O.  Any other string value is treated as "rw", but generates a warning message.
    
       CONVFMT     The conversion format for numbers, "%.6g", by default.
    
       ENVIRON     An array containing the values of the current environment.  The array is indexed by the environment variables, each
                   element being the value of that variable (e.g., ENVIRON["HOME"] might be "/home/arnold").
    
                   In POSIX mode, changing this array does not affect the environment seen by programs which gawk spawns via redirect‐
                   ion  or  the  system()  function.   Otherwise, gawk updates its real environment so that programs it spawns see the
                   changes.
    
       ERRNO       If a system error occurs either doing a redirection for getline, during a read for getline, or  during  a  close(),
                   then  ERRNO  is  set to a string describing the error.  The value is subject to translation in non-English locales.
                   If the string in ERRNO corresponds to a system error in the errno(3) variable, then the numeric value can be  found
                   in PROCINFO["errno"].  For non-system errors, PROCINFO["errno"] will be zero.
    
       FIELDWIDTHS A  whitespace-separated  list of field widths.  When set, gawk parses the input into fields of fixed width, instead
                   of using the value of the FS variable as the field separator.  Each field width may optionally  be  preceded  by  a
                   colon-separated value specifying the number of characters to skip before the field starts.  See Fields, above.
    
       FILENAME    The  name  of the current input file.  If no files are specified on the command line, the value of FILENAME is “-”.
                   However, FILENAME is undefined inside the BEGIN rule (unless set by getline).
    
       FNR         The input record number in the current input file.
    
       FPAT        A regular expression describing the contents of the fields in a record.  When  set,  gawk  parses  the  input  into
                   fields,  where  the  fields  match the regular expression, instead of using the value of FS as the field separator.
                   See Fields, above.
    
       FS          The input field separator, a space by default.  See Fields, above.
    
       FUNCTAB     An array whose indices and corresponding values are the names of all the user-defined or extension functions in the
                   program.  NOTE: You may not use the delete statement with the FUNCTAB array.
    
       IGNORECASE  Controls the case-sensitivity of all regular expression and string operations.  If IGNORECASE has a non-zero value,
                   then string comparisons and pattern matching in rules, field splitting with FS and FPAT, record separating with RS,
                   regular  expression  matching  with  ~ and !~, and the gensub(), gsub(), index(), match(), patsplit(), split(), and
                   sub() built-in functions all ignore case when doing regular expression operations.  NOTE: Array subscripting is not
                   affected.  However, the asort() and asorti() functions are affected.
                   Thus,  if IGNORECASE is not equal to zero, /aB/ matches all of the strings "ab", "aB", "Ab", and "AB".  As with all
                   AWK variables, the initial value of IGNORECASE is zero, so all regular expression and string  operations  are  nor‐
                   mally case-sensitive.
    
       LINT        Provides  dynamic  control  of the --lint option from within an AWK program.  When true, gawk prints lint warnings.
                   When false, it does not.  The values allowed for the --lint option may also be assigned to LINT, with the same  ef‐
                   fects.  Any other true value just prints warnings.
    
       NF          The number of fields in the current input record.
    
       NR          The total number of input records seen so far.
    
       OFMT        The output format for numbers, "%.6g", by default.
    
       OFS         The output field separator, a space by default.
    
       ORS         The output record separator, by default a newline.
    
       PREC        The working precision of arbitrary precision floating-point numbers, 53 by default.
    
       PROCINFO    The elements of this array provide access to information about the running AWK program.  On some systems, there may
                   be elements in the array, "group1" through "groupn" for some n, which is the number of  supplementary  groups  that
                   the  process  has.   Use  the  in operator to test for these elements.  The following elements are guaranteed to be
                   available:
    
                   PROCINFO["argv"]     The command line arguments as received by gawk at the C-language level.  The subscripts  start
                                        from zero.
    
                   PROCINFO["egid"]     The value of the getegid(2) system call.
    
                   PROCINFO["errno"]    The value of errno(3) when ERRNO is set to the associated error message.
    
                   PROCINFO["euid"]     The value of the geteuid(2) system call.
    
                   PROCINFO["FS"]       "FS"  if  field  splitting with FS is in effect, "FPAT" if field splitting with FPAT is in ef‐
                                        fect, "FIELDWIDTHS" if field splitting with FIELDWIDTHS is in effect, or "API"  if  API  input
                                        parser field splitting is in effect.
    
                   PROCINFO["gid"]      The value of the getgid(2) system call.
    
                   PROCINFO["identifiers"]
                                        A  subarray, indexed by the names of all identifiers used in the text of the AWK program.  The
                                        values indicate what gawk knows about the identifiers after it has finished parsing  the  pro‐
                                        gram; they are not updated while the program runs.  For each identifier, the value of the ele‐
                                        ment is one of the following:
    
                                        "array"     The identifier is an array.
    
                                        "builtin"   The identifier is a built-in function.
    
                                        "extension" The identifier is an extension function loaded via @load or --load.
    
                                        "scalar"    The identifier is a scalar.
    
                                        "untyped"   The identifier is untyped (could be used as a scalar or array, gawk  doesn't  know
                                                    yet).
    
                                        "user"      The identifier is a user-defined function.
    
                   PROCINFO["pgrpid"]   The value of the getpgrp(2) system call.
    
                   PROCINFO["pid"]      The value of the getpid(2) system call.
    
                   PROCINFO["platform"] A string indicating the platform for which gawk was compiled.  It is one of:
    
                                        "djgpp", "mingw"
                                               Microsoft Windows, using either DJGPP, or MinGW, respectively.
    
                                        "os2"  OS/2.
    
                                        "posix"
                                               GNU/Linux, Cygwin, Mac OS X, and legacy Unix systems.
    
                                        "vms"  OpenVMS or Vax/VMS.
    
                   PROCINFO["ppid"]     The value of the getppid(2) system call.
    
                   PROCINFO["strftime"] The default time format string for strftime().  Changing its value affects how strftime() for‐
                                        mats time values when called with no arguments.
    
                   PROCINFO["uid"]      The value of the getuid(2) system call.
    
                   PROCINFO["version"]  The version of gawk.
    
                   The following elements are present if loading dynamic extensions is available:
    
                   PROCINFO["api_major"]
                          The major version of the extension API.
    
                   PROCINFO["api_minor"]
                          The minor version of the extension API.
    
                   The following elements are available if MPFR support is compiled into gawk:
    
                   PROCINFO["gmp_version"]
                          The version of the GNU GMP library used for arbitrary precision number support in gawk.
    
                   PROCINFO["mpfr_version"]
                          The version of the GNU MPFR library used for arbitrary precision number support in gawk.
    
                   PROCINFO["prec_max"]
                          The maximum precision supported by the GNU MPFR library for arbitrary precision floating-point numbers.
    
                   PROCINFO["prec_min"]
                          The minimum precision allowed by the GNU MPFR library for arbitrary precision floating-point numbers.
    
                   The following elements may set by a program to change gawk's behavior:
    
                   PROCINFO["NONFATAL"]
                          If this exists, then I/O errors for all redirections become nonfatal.
    
                   PROCINFO["name", "NONFATAL"]
                          Make I/O errors for name be nonfatal.
    
                   PROCINFO["command", "pty"]
                          Use a pseudo-tty for two-way communication with command instead of setting up two one-way pipes.
    
                   PROCINFO["input", "READ_TIMEOUT"]
                          The timeout in milliseconds for reading data from input, where input is a redirection string or a  filename.
                          A value of zero or less than zero means no timeout.
    
                   PROCINFO["input", "RETRY"]
                          If  an  I/O error that may be retried occurs when reading data from input, and this array entry exists, then
                          getline returns -2 instead of following the default behavior of returning -1 and configuring input to return
                          no  further data.  An I/O error that may be retried is one where errno(3) has the value EAGAIN, EWOULDBLOCK,
                          EINTR, or ETIMEDOUT.  This may be useful in conjunction with PROCINFO["input", "READ_TIMEOUT"] or in  situa‐
                          tions where a file descriptor has been configured to behave in a non-blocking fashion.
    
                   PROCINFO["sorted_in"]
                          If  this element exists in PROCINFO, then its value controls the order in which array elements are traversed
                          in for  loops.   Supported  values  are  "@ind_str_asc",  "@ind_num_asc",  "@val_type_asc",  "@val_str_asc",
                          "@val_num_asc",  "@ind_str_desc",  "@ind_num_desc",  "@val_type_desc", "@val_str_desc", "@val_num_desc", and
                          "@unsorted".  The value can also be the name (as a string) of any comparison function defined as follows:
    
                               function cmp_func(i1, v1, i2, v2)
    
                          where i1 and i2 are the indices, and v1 and v2 are the corresponding values of the two elements  being  com‐
                          pared.   It  should return a number less than, equal to, or greater than 0, depending on how the elements of
                          the array are to be ordered.
    
       ROUNDMODE   The rounding mode to use for arbitrary precision arithmetic on numbers, by default  "N"  (IEEE-754  roundTiesToEven
                   mode).  The accepted values are:
    
                   "A" or "a"
                          for  rounding  away  from  zero.   These are only available if your version of the GNU MPFR library supports
                          rounding away from zero.
    
                   "D" or "d" for roundTowardNegative.
    
                   "N" or "n" for roundTiesToEven.
    
                   "U" or "u" for roundTowardPositive.
    
                   "Z" or "z" for roundTowardZero.
    
       RS          The input record separator, by default a newline.
    
       RT          The record terminator.  Gawk sets RT to the input text that matched the character or regular  expression  specified
                   by RS.
    
       RSTART      The  index of the first character matched by match(); 0 if no match.  (This implies that character indices start at
                   one.)
    
       RLENGTH     The length of the string matched by match(); -1 if no match.
    
       SUBSEP      The string used to separate multiple subscripts in array elements, by default "\034".
    
       SYMTAB      An array whose indices are the names of all currently defined global variables and arrays in the program.  The  ar‐
                   ray may be used for indirect access to read or write the value of a variable:
    
                        foo = 5
                        SYMTAB["foo"] = 4
                        print foo    # prints 4
    
                   The  typeof()  function may be used to test if an element in SYMTAB is an array.  You may not use the delete state‐
                   ment with the SYMTAB array, nor assign to elements with an index that is not a variable name.
    
       TEXTDOMAIN  The text domain of the AWK program; used to find the localized translations for the program's strings.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227

    Arrays
    Arrays are subscripted with an expression between square brackets ([ and ]). If the expression is an expression list (expr,
    expr …) then the array subscript is a string consisting of the concatenation of the (string) value of each expression, sepa‐
    rated by the value of the SUBSEP variable. This facility is used to simulate multiply dimensioned arrays. For example:

              i = "A"; j = "B"; k = "C"
              x[i, j, k] = "hello, world\n"
    
       assigns the string "hello, world\n" to the element of the array x which is indexed by the string "A\034B\034C".  All arrays  in
       AWK are associative, i.e., indexed by string values.
    
       The special operator in may be used to test if an array has an index consisting of a particular value:
    
              if (val in array)
                   print array[val]
    
       If the array has multiple subscripts, use (i, j) in array.
    
       The  in  construct  may  also be used in a for loop to iterate over all the elements of an array.  However, the (i, j) in array
       construct only works in tests, not in for loops.
    
       An element may be deleted from an array using the delete statement.  The delete statement may also be used to delete the entire
       contents of an array, just by specifying the array name without a subscript.
    
       gawk  supports true multidimensional arrays. It does not require that such arrays be ``rectangular'' as in C or C++.  For exam‐
       ple:
    
              a[1] = 5
              a[2][1] = 6
              a[2][2] = 7
    
       NOTE: You may need to tell gawk that an array element is really a subarray in order to use it where gawk expects an array (such
       as  in  the  second argument to split()).  You can do this by creating an element in the subarray and then deleting it with the
       delete statement.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    Namespaces
    Gawk provides a simple namespace facility to help work around the fact that all variables in AWK are global.

       A qualified name consists of a two simple identifiers joined by a double colon (::).  The left-hand identifier  represents  the
       namespace  and  the  right-hand identifier is the variable within it.  All simple (non-qualified) names are considered to be in
       the ``current'' namespace; the default namespace is awk.  However, simple identifiers consisting solely  of  uppercase  letters
       are forced into the awk namespace, even if the current namespace is different.
    
       You change the current namespace with an @namespace "name" directive.
    
       The  standard predefined builtin function names may not be used as namespace names.  The names of additional functions provided
       by gawk may be used as namespace names or as simple identifiers in other namespaces.  For more details, see GAWK: Effective AWK
       Programming.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Variable Typing And Conversion
    Variables and fields may be (floating point) numbers, or strings, or both. They may also be regular expressions. How the value
    of a variable is interpreted depends upon its context. If used in a numeric expression, it will be treated as a number; if
    used as a string it will be treated as a string.

       To  force  a variable to be treated as a number, add zero to it; to force it to be treated as a string, concatenate it with the
       null string.
    
       Uninitialized variables have the numeric value zero and the string value "" (the null, or empty, string).
    
       When a string must be converted to a number, the conversion is accomplished using strtod(3).  A number is converted to a string
       by  using the value of CONVFMT as a format string for sprintf(3), with the numeric value of the variable as the argument.  How‐
       ever, even though all numbers in AWK are floating-point, integral values are always converted as integers.  Thus, given
    
              CONVFMT = "%2.2f"
              a = 12
              b = a ""
    
       the variable b has a string value of "12" and not "12.00".
    
       NOTE: When operating in POSIX mode (such as with the --posix option), beware that locale settings may interfere  with  the  way
       decimal  numbers  are  treated:  the  decimal separator of the numbers you are feeding to gawk must conform to what your locale
       would expect, be it a comma (,) or a period (.).
    
       Gawk performs comparisons as follows: If two variables are numeric, they are compared numerically.  If one value is numeric and
       the  other  has  a string value that is a “numeric string,” then comparisons are also done numerically.  Otherwise, the numeric
       value is converted to a string and a string comparison is performed.  Two strings are compared, of course, as strings.
    
       Note that string constants, such as "57", are not numeric strings, they are string constants.  The  idea  of  “numeric  string”
       only  applies  to  fields,  getline  input,  FILENAME,  ARGV elements, ENVIRON elements and the elements of an array created by
       split() or patsplit() that are numeric strings.  The basic idea is that user input, and only user input,  that  looks  numeric,
       should be treated that way.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    Octal and Hexadecimal Constants
    You may use C-style octal and hexadecimal constants in your AWK program source code. For example, the octal value 011 is equal
    to decimal 9, and the hexadecimal value 0x11 is equal to decimal 17.

    String Constants
    String constants in AWK are sequences of characters enclosed between double quotes (like “value”). Within strings, certain es‐
    cape sequences are recognized, as in C. These are:

       \\   A literal backslash.
    
       \a   The “alert” character; usually the ASCII BEL character.
    
       \b   Backspace.
    
       \f   Form-feed.
    
       \n   Newline.
    
       \r   Carriage return.
    
       \t   Horizontal tab.
    
       \v   Vertical tab.
    
       \xhex digits
            The  character  represented  by the string of hexadecimal digits following the \x.  Up to two following hexadecimal digits
            are considered part of the escape sequence.  E.g., "\x1B" is the ASCII ESC (escape) character.
    
       \ddd The character represented by the 1-, 2-, or 3-digit sequence of octal digits.  E.g., "\033"  is  the  ASCII  ESC  (escape)
            character.
    
       \c   The literal character c.
    
       In  compatibility mode, the characters represented by octal and hexadecimal escape sequences are treated literally when used in
       regular expression constants.  Thus, /a\52b/ is equivalent to /a\*b/.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    Regexp Constants
    A regular expression constant is a sequence of characters enclosed between forward slashes (like /value/). Regular expression
    matching is described more fully below; see Regular Expressions.

       The  escape  sequences  described  earlier  may also be used inside constant regular expressions (e.g., /[ \t\f\n\r\v]/ matches
       whitespace characters).
    
       Gawk provides strongly typed regular expression constants. These are written with a leading @ symbol (like so: @/value/).  Such
       constants may be assigned to scalars (variables, array elements) and passed to user-defined functions. Variables that have been
       so assigned have regular expression type.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    PATTERNS AND ACTIONS
    AWK is a line-oriented language. The pattern comes first, and then the action. Action statements are enclosed in { and }.
    Either the pattern may be missing, or the action may be missing, but, of course, not both. If the pattern is missing, the ac‐
    tion executes for every single record of input. A missing action is equivalent to

              { print }
    
       which prints the entire record.
    
       Comments begin with the # character, and continue until the end of the line.  Empty lines may be used to  separate  statements.
       Normally,  a  statement  ends  with  a  newline, however, this is not the case for lines ending in a comma, {, ?, :, &&, or ||.
       Lines ending in do or else also have their statements automatically continued on the following line.  In other  cases,  a  line
       can be continued by ending it with a “\”, in which case the newline is ignored.  However, a “\” after a # is not special.
    
       Multiple  statements  may be put on one line by separating them with a “;”.  This applies to both the statements within the ac‐
       tion part of a pattern-action pair (the usual case), and to the pattern-action statements themselves.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    Patterns
    AWK patterns may be one of the following:

              BEGIN
              END
              BEGINFILE
              ENDFILE
              /regular expression/
              relational expression
              pattern && pattern
              pattern || pattern
              pattern ? pattern : pattern
              (pattern)
              ! pattern
              pattern1, pattern2
    
       BEGIN and END are two special kinds of patterns which are not tested against the input.  The action parts of all BEGIN patterns
       are  merged  as  if  all  the statements had been written in a single BEGIN rule.  They are executed before any of the input is
       read.  Similarly, all the END rules are merged, and executed when all the input is exhausted (or when an exit statement is exe‐
       cuted).   BEGIN  and END patterns cannot be combined with other patterns in pattern expressions.  BEGIN and END patterns cannot
       have missing action parts.
    
       BEGINFILE and ENDFILE are additional special patterns whose actions are executed before reading the first record of  each  com‐
       mand-line  input  file  and  after  reading the last record of each file.  Inside the BEGINFILE rule, the value of ERRNO is the
       empty string if the file was opened successfully.  Otherwise, there is some problem with the  file  and  the  code  should  use
       nextfile to skip it. If that is not done, gawk produces its usual fatal error for files that cannot be opened.
    
       For  /regular expression/ patterns, the associated statement is executed for each input record that matches the regular expres‐
       sion.  Regular expressions are the same as those in egrep(1), and are summarized below.
    
       A relational expression may use any of the operators defined below in the section on actions.   These  generally  test  whether
       certain fields match certain regular expressions.
    
       The &&, ||, and !  operators are logical AND, logical OR, and logical NOT, respectively, as in C.  They do short-circuit evalu‐
       ation, also as in C, and are used for combining more primitive pattern expressions.  As in most languages, parentheses  may  be
       used to change the order of evaluation.
    
       The  ?:  operator is like the same operator in C.  If the first pattern is true then the pattern used for testing is the second
       pattern, otherwise it is the third.  Only one of the second and third patterns is evaluated.
    
       The pattern1, pattern2 form of an expression is called a range pattern.  It matches all input records starting  with  a  record
       that matches pattern1, and continuing until a record that matches pattern2, inclusive.  It does not combine with any other sort
       of pattern expression.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    Regular Expressions
    Regular expressions are the extended kind found in egrep. They are composed of characters as follows:

       c          Matches the non-metacharacter c.
    
       \c         Matches the literal character c.
    
       .          Matches any character including newline.
    
       ^          Matches the beginning of a string.
    
       $          Matches the end of a string.
    
       [abc...]   A character list: matches any of the characters abc....  You may include a range of characters  by  separating  them
                  with a dash.  To include a literal dash in the list, put it first or last.
    
       [^abc...]  A negated character list: matches any character except abc....
    
       r1|r2      Alternation: matches either r1 or r2.
    
       r1r2       Concatenation: matches r1, and then r2.
    
       r+         Matches one or more r's.
    
       r*         Matches zero or more r's.
    
       r?         Matches zero or one r's.
    
       (r)        Grouping: matches r.
    
       r{n}
       r{n,}
       r{n,m}     One or two numbers inside braces denote an interval expression.  If there is one number in the braces, the preceding
                  regular expression r is repeated n times.  If there are two numbers separated by a comma,  r  is  repeated  n  to  m
                  times.  If there is one number followed by a comma, then r is repeated at least n times.
    
       \y         Matches the empty string at either the beginning or the end of a word.
    
       \B         Matches the empty string within a word.
    
       \<         Matches the empty string at the beginning of a word.
    
       \>         Matches the empty string at the end of a word.
    
       \s         Matches any whitespace character.
    
       \S         Matches any nonwhitespace character.
    
       \w         Matches any word-constituent character (letter, digit, or underscore).
    
       \W         Matches any character that is not word-constituent.
    
       \`         Matches the empty string at the beginning of a buffer (string).
    
       \'         Matches the empty string at the end of a buffer.
    
       The escape sequences that are valid in string constants (see String Constants) are also valid in regular expressions.
    
       Character classes are a feature introduced in the POSIX standard.  A character class is a special notation for describing lists
       of characters that have a specific attribute, but where the actual characters themselves  can  vary  from  country  to  country
       and/or  from character set to character set.  For example, the notion of what is an alphabetic character differs in the USA and
       in France.
    
       A character class is only valid in a regular expression inside the brackets of a character list.  Character classes consist  of
       [:, a keyword denoting the class, and :].  The character classes defined by the POSIX standard are:
    
       [:alnum:]  Alphanumeric characters.
    
       [:alpha:]  Alphabetic characters.
    
       [:blank:]  Space or tab characters.
    
       [:cntrl:]  Control characters.
    
       [:digit:]  Numeric characters.
    
       [:graph:]  Characters that are both printable and visible.  (A space is printable, but not visible, while an a is both.)
    
       [:lower:]  Lowercase alphabetic characters.
    
       [:print:]  Printable characters (characters that are not control characters.)
    
       [:punct:]  Punctuation characters (characters that are not letter, digits, control characters, or space characters).
    
       [:space:]  Space characters (such as space, tab, and formfeed, to name a few).
    
       [:upper:]  Uppercase alphabetic characters.
    
       [:xdigit:] Characters that are hexadecimal digits.
    
       For  example,  before the POSIX standard, to match alphanumeric characters, you would have had to write /[A-Za-z0-9]/.  If your
       character set had other alphabetic characters in it, this would not match them, and if your character set collated  differently
       from  ASCII,  this  might  not  even  match the ASCII alphanumeric characters.  With the POSIX character classes, you can write
       /[[:alnum:]]/, and this matches the alphabetic and numeric characters in your character set, no matter what it is.
    
       Two additional special sequences can appear in character lists.  These apply to non-ASCII character sets, which can have single
       symbols  (called  collating elements) that are represented with more than one character, as well as several characters that are
       equivalent for collating, or sorting, purposes.  (E.g., in French, a plain “e” and a grave-accented “`” are equivalent.)
    
       Collating Symbols
              A collating symbol is a multi-character collating element enclosed in [.  and .].  For example, if ch is a collating el‐
              ement,  then  [[.ch.]]   is a regular expression that matches this collating element, while [ch] is a regular expression
              that matches either c or h.
    
       Equivalence Classes
              An equivalence class is a locale-specific name for a list of characters that are equivalent.  The name is enclosed in [=
              and  =].  For example, the name e might be used to represent all of “e”, “´”, and “`”.  In this case, [[=e=]] is a regu‐
              lar expression that matches any of e, ´, or `.
    
       These features are very valuable in non-English speaking locales.  The library functions that gawk uses for regular  expression
       matching currently only recognize POSIX character classes; they do not recognize collating symbols or equivalence classes.
    
       The  \y,  \B, \<, \>, \s, \S, \w, \W, \`, and \' operators are specific to gawk; they are extensions based on facilities in the
       GNU regular expression libraries.
    
       The various command line options control how gawk interprets characters in regular expressions.
    
       No options
              In the default case, gawk provides all the facilities of POSIX regular expressions and the GNU regular expression opera‐
              tors described above.
    
       --posix
              Only POSIX regular expressions are supported, the GNU operators are not special.  (E.g., \w matches a literal w).
    
       --traditional
              Traditional  UNIX  awk regular expressions are matched.  The GNU operators are not special, and interval expressions are
              not available.  Characters described by octal and hexadecimal escape sequences are treated literally, even if they  rep‐
              resent regular expression metacharacters.
    
       --re-interval
              Allow interval expressions in regular expressions, even if --traditional has been provided.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128

    Actions
    Action statements are enclosed in braces, { and }. Action statements consist of the usual assignment, conditional, and looping
    statements found in most languages. The operators, control statements, and input/output statements available are patterned af‐
    ter those in C.

    Operators
    The operators in AWK, in order of decreasing precedence, are:

       (...)       Grouping
    
       $           Field reference.
    
       ++ --       Increment and decrement, both prefix and postfix.
    
       ^           Exponentiation (** may also be used, and **= for the assignment operator).
    
       + - !       Unary plus, unary minus, and logical negation.
    
       * / %       Multiplication, division, and modulus.
    
       + -         Addition and subtraction.
    
       space       String concatenation.
    
       |   |&      Piped I/O for getline, print, and printf.
    
       < > <= >= == !=
                   The regular relational operators.
    
       ~ !~        Regular  expression  match, negated match.  NOTE: Do not use a constant regular expression (/foo/) on the left-hand
                   side of a ~ or !~.  Only use one on the right-hand side.  The expression /foo/ ~ exp has the same meaning as (($0 ~
                   /foo/) ~ exp).  This is usually not what you want.
    
       in          Array membership.
    
       &&          Logical AND.
    
       ||          Logical OR.
    
       ?:          The C conditional expression.  This has the form expr1 ? expr2 : expr3.  If expr1 is true, the value of the expres‐
                   sion is expr2, otherwise it is expr3.  Only one of expr2 and expr3 is evaluated.
    
       = += -= *= /= %= ^=
                   Assignment.  Both absolute assignment (var = value) and operator-assignment (the other forms) are supported.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    Control Statements
    The control statements are as follows:

              if (condition) statement [ else statement ]
              while (condition) statement
              do statement while (condition)
              for (expr1; expr2; expr3) statement
              for (var in array) statement
              break
              continue
              delete array[index]
              delete array
              exit [ expression ]
              { statements }
              switch (expression) {
              case value|regex : statement
              ...
              [ default: statement ]
              }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    I/O Statements
    The input/output statements are as follows:

       close(file [, how])   Close file, pipe or coprocess.  The optional how should only be used when closing one end  of  a  two-way
                             pipe to a coprocess.  It must be a string value, either "to" or "from".
    
       getline               Set $0 from the next input record; set NF, NR, FNR, RT.
    
       getline file Print expressions on file.  Each expression is separated by the value of OFS.  The output record is  ter‐
                             minated with the value of ORS.
    
       printf fmt, expr-list Format and print.  See The printf Statement, below.
    
       printf fmt, expr-list >file
                             Format and print on file.
    
       system(cmd-line)      Execute  the  command cmd-line, and return the exit status.  (This may not be available on non-POSIX sys‐
                             tems.)  See GAWK: Effective AWK Programming for the full details on the exit status.
    
       fflush([file])        Flush any buffers associated with the open output file or pipe file.  If file is missing or if it is  the
                             null string, then flush all open output files and pipes.
    
       Additional output redirections are allowed for print and printf.
    
       print ... >> file
              Append output to the file.
    
       print ... | command
              Write on a pipe.
    
       print ... |& command
              Send data to a coprocess or socket.  (See also the subsection Special File Names, below.)
    
       The  getline  command  returns 1 on success, zero on end of file, and -1 on an error.  If the errno(3) value indicates that the
       I/O operation may be retried, and PROCINFO["input", "RETRY"] is set, then -2 is returned instead of -1, and  further  calls  to
       getline may be attempted.  Upon an error, ERRNO is set to a string describing the problem.
    
       NOTE: Failure in opening a two-way socket results in a non-fatal error being returned to the calling function. If using a pipe,
       coprocess, or socket to getline, or from print or printf within a loop, you must use close() to create  new  instances  of  the
       command or socket.  AWK does not automatically close pipes, sockets, or coprocesses when they return EOF.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    The printf Statement
    The AWK versions of the printf statement and sprintf() function (see below) accept the following conversion specification for‐
    mats:

       %a, %A  A floating point number of the form [-]0xh.hhhhp+-dd (C99 hexadecimal floating point format).  For %A,  uppercase  let‐
               ters are used instead of lowercase ones.
    
       %c      A  single character.  If the argument used for %c is numeric, it is treated as a character and printed.  Otherwise, the
               argument is assumed to be a string, and the only first character of that string is printed.
    
       %d, %i  A decimal number (the integer part).
    
       %e, %E  A floating point number of the form [-]d.dddddde[+-]dd.  The %E format uses E instead of e.
    
       %f, %F  A floating point number of the form [-]ddd.dddddd.  If the system library supports it, %F is available as well. This is
               like  %f,  but uses capital letters for special “not a number” and “infinity” values. If %F is not available, gawk uses
               %f.
    
       %g, %G  Use %e or %f conversion, whichever is shorter, with nonsignificant zeros suppressed.  The %G format uses %E instead  of
               %e.
    
       %o      An unsigned octal number (also an integer).
    
       %u      An unsigned decimal number (again, an integer).
    
       %s      A character string.
    
       %x, %X  An unsigned hexadecimal number (an integer).  The %X format uses ABCDEF instead of abcdef.
    
       %%      A single % character; no argument is converted.
    
       Optional, additional parameters may lie between the % and the control letter:
    
       count$ Use  the  count'th argument at this point in the formatting.  This is called a positional specifier and is intended pri‐
              marily for use in translated versions of format strings, not in the original text of an AWK program.  It is a  gawk  ex‐
              tension.
    
       -      The expression should be left-justified within its field.
    
       space  For numeric conversions, prefix positive values with a space, and negative values with a minus sign.
    
       +      The plus sign, used before the width modifier (see below), says to always supply a sign for numeric conversions, even if
              the data to be formatted is positive.  The + overrides the space modifier.
    
       #      Use an “alternate form” for certain control letters.  For %o, supply a leading zero.  For %x, and %X, supply  a  leading
              0x  or  0X  for  a  nonzero result.  For %e, %E, %f and %F, the result always contains a decimal point.  For %g, and %G,
              trailing zeros are not removed from the result.
    
       0      A leading 0 (zero) acts as a flag, indicating that output should be padded with zeroes instead of spaces.  This  applies
              only  to  the  numeric  output formats.  This flag only has an effect when the field width is wider than the value to be
              printed.
    
       '      A single quote character instructs gawk to insert the locale's thousands-separator character into decimal  numbers,  and
              to  also  use the locale's decimal point character with floating point formats.  This requires correct locale support in
              the C library and in the definition of the current locale.
    
       width  The field should be padded to this width.  The field is normally padded with spaces.  With the 0 flag, it is padded with
              zeroes.
    
       .prec  A number that specifies the precision to use when printing.  For the %e, %E, %f and %F, formats, this specifies the num‐
              ber of digits you want printed to the right of the decimal point.  For the %g, and %G formats, it specifies the  maximum
              number  of significant digits.  For the %d, %i, %o, %u, %x, and %X formats, it specifies the minimum number of digits to
              print.  For the %s format, it specifies the maximum number of characters from the string that should be printed.
    
       The dynamic width and prec capabilities of the ISO C printf() routines are supported.  A * in place of either the width or prec
       specifications  causes  their  values to be taken from the argument list to printf or sprintf().  To use a positional specifier
       with a dynamic width or precision, supply the count$ after the * in the format string.  For example, "%3$*2$.*1$s".
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    Special File Names
    When doing I/O redirection from either print or printf into a file, or via getline from a file, gawk recognizes certain special
    filenames internally. These filenames allow access to open file descriptors inherited from gawk’s parent process (usually the
    shell). These file names may also be used on the command line to name data files. The filenames are:

       -           The standard input.
    
       /dev/stdin  The standard input.
    
       /dev/stdout The standard output.
    
       /dev/stderr The standard error output.
    
       /dev/fd/n   The file associated with the open file descriptor n.
    
       These are particularly useful for error messages.  For example:
    
              print "You blew it!" > "/dev/stderr"
    
       whereas you would otherwise have to use
    
              print "You blew it!" | "cat 1>&2"
    
       The following special filenames may be used with the |& coprocess operator for creating TCP/IP network connections:
    
       /inet/tcp/lport/rhost/rport
       /inet4/tcp/lport/rhost/rport
       /inet6/tcp/lport/rhost/rport
              Files for a TCP/IP connection on local port lport to remote host rhost on remote port rport.  Use a port of  0  to  have
              the  system  pick  a port.  Use /inet4 to force an IPv4 connection, and /inet6 to force an IPv6 connection.  Plain /inet
              uses the system default (most likely IPv4).  Usable only with the |& two-way I/O operator.
    
       /inet/udp/lport/rhost/rport
       /inet4/udp/lport/rhost/rport
       /inet6/udp/lport/rhost/rport
              Similar, but use UDP/IP instead of TCP/IP.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    Numeric Functions
    AWK has the following built-in arithmetic functions:

       atan2(y, x)   Return the arctangent of y/x in radians.
    
       cos(expr)     Return the cosine of expr, which is in radians.
    
       exp(expr)     The exponential function.
    
       int(expr)     Truncate to integer.
    
       log(expr)     The natural logarithm function.
    
       rand()        Return a random number N, between zero and one, such that 0 ≤ N < 1.
    
       sin(expr)     Return the sine of expr, which is in radians.
    
       sqrt(expr)    Return the square root of expr.
    
       srand([expr]) Use expr as the new seed for the random number generator.  If no expr is provided, use the time of  day.   Return
                     the previous seed for the random number generator.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    String Functions
    Gawk has the following built-in string functions:

       asort(s [, d [, how] ]) Return  the number of elements in the source array s.  Sort the contents of s using gawk's normal rules
                               for comparing values, and replace the indices of the sorted values s with sequential integers  starting
                               with  1.  If  the optional destination array d is specified, first duplicate s into d, and then sort d,
                               leaving the indices of the source array s unchanged. The optional string how controls the direction and
                               the  comparison mode.  Valid values for how are any of the strings valid for PROCINFO["sorted_in"].  It
                               can also be the name of a user-defined comparison function as described in PROCINFO["sorted_in"].
    
       asorti(s [, d [, how] ])
                               Return the number of elements in the source array s.  The behavior is the same as that of asort(),  ex‐
                               cept  that  the  array indices are used for sorting, not the array values.  When done, the array is in‐
                               dexed numerically, and the values are those of the original indices.  The  original  values  are  lost;
                               thus  provide  a second array if you wish to preserve the original.  The purpose of the optional string
                               how is the same as described previously for asort().
    
       gensub(r, s, h [, t])   Search the target string t for matches of the regular expression r.  If h is a string beginning with  g
                               or  G,  then  replace all matches of r with s.  Otherwise, h is a number indicating which match of r to
                               replace.  If t is not supplied, use $0 instead.  Within the replacement text s, the sequence \n,  where
                               n  is  a  digit  from 1 to 9, may be used to indicate just the text that matched the n'th parenthesized
                               subexpression.  The sequence \0 represents the entire matched text, as does the  character  &.   Unlike
                               sub()  and gsub(), the modified string is returned as the result of the function, and the original tar‐
                               get string is not changed.
    
       gsub(r, s [, t])        For each substring matching the regular expression r in the string t, substitute the string s, and  re‐
                               turn  the  number of substitutions.  If t is not supplied, use $0.  An & in the replacement text is re‐
                               placed with the text that was actually matched.  Use \& to get a literal &.  (This  must  be  typed  as
                               "\\&";  see  GAWK:  Effective  AWK  Programming for a fuller discussion of the rules for ampersands and
                               backslashes in the replacement text of sub(), gsub(), and gensub().)
    
       index(s, t)             Return the index of the string t in the string s, or zero if t is  not  present.   (This  implies  that
                               character indices start at one.)  It is a fatal error to use a regexp constant for t.
    
       length([s])             Return  the length of the string s, or the length of $0 if s is not supplied.  As a non-standard exten‐
                               sion, with an array argument, length() returns the number of elements in the array.
    
       match(s, r [, a])       Return the position in s where the regular expression r occurs, or zero if r is not  present,  and  set
                               the  values of RSTART and RLENGTH.  Note that the argument order is the same as for the ~ operator: str
                               ~ re.  If array a is provided, a is cleared and then elements 1 through n are filled with the  portions
                               of  s that match the corresponding parenthesized subexpression in r.  The zero'th element of a contains
                               the portion of s matched by the entire regular  expression  r.   Subscripts  a[n,  "start"],  and  a[n,
                               "length"] provide the starting index in the string and length respectively, of each matching substring.
    
       patsplit(s, a [, r [, seps] ])
                               Split  the string s into the array a and the separators array seps on the regular expression r, and re‐
                               turn the number of fields.  Element values are the portions of s that matched r.  The value of  seps[i]
                               is  the  possibly  null  separator that appeared after a[i].  The value of seps[0] is the possibly null
                               leading separator.  If r is omitted, FPAT is used instead.  The arrays a and seps  are  cleared  first.
                               Splitting behaves identically to field splitting with FPAT, described above.
    
       split(s, a [, r [, seps] ])
                               Split  the string s into the array a and the separators array seps on the regular expression r, and re‐
                               turn the number of fields.  If r is omitted, FS is used instead.  The arrays a  and  seps  are  cleared
                               first.   seps[i]  is the field separator matched by r between a[i] and a[i+1].  If r is a single space,
                               then leading whitespace in s goes into the extra array element seps[0]  and  trailing  whitespace  goes
                               into  the  extra array element seps[n], where n is the return value of split(s, a, r, seps).  Splitting
                               behaves identically to field splitting, described above.  In particular, if  r  is  a  single-character
                               string, that string acts as the separator, even if it happens to be a regular expression metacharacter.
    
       sprintf(fmt, expr-list) Print expr-list according to fmt, and return the resulting string.
    
       strtonum(str)           Examine  str,  and return its numeric value.  If str begins with a leading 0, treat it as an octal num‐
                               ber.  If str begins with a leading 0x or 0X, treat it as a hexadecimal number.  Otherwise, assume it is
                               a decimal number.
    
       sub(r, s [, t])         Just like gsub(), but replace only the first matching substring.  Return either zero or one.
    
       substr(s, i [, n])      Return the at most n-character substring of s starting at i.  If n is omitted, use the rest of s.
    
       tolower(str)            Return  a  copy  of the string str, with all the uppercase characters in str translated to their corre‐
                               sponding lowercase counterparts.  Non-alphabetic characters are left unchanged.
    
       toupper(str)            Return a copy of the string str, with all the lowercase characters in str translated  to  their  corre‐
                               sponding uppercase counterparts.  Non-alphabetic characters are left unchanged.
    
       Gawk is multibyte aware.  This means that index(), length(), substr() and match() all work in terms of characters, not bytes.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    Time Functions
    Since one of the primary uses of AWK programs is processing log files that contain time stamp information, gawk provides the
    following functions for obtaining time stamps and formatting them.

       mktime(datespec [, utc-flag])
                 Turn datespec into a time stamp of the same form as returned by systime(), and return the result.  The datespec is  a
                 string  of  the form YYYY MM DD HH MM SS[ DST].  The contents of the string are six or seven numbers representing re‐
                 spectively the full year including century, the month from 1 to 12, the day of the month from 1 to 31,  the  hour  of
                 the  day  from  0 to 23, the minute from 0 to 59, the second from 0 to 60, and an optional daylight saving flag.  The
                 values of these numbers need not be within the ranges specified; for example, an hour of -1 means 1 hour before  mid‐
                 night.  The origin-zero Gregorian calendar is assumed, with year 0 preceding year 1 and year -1 preceding year 0.  If
                 utc-flag is present and is non-zero or non-null, the time is assumed to be in the UTC time zone; otherwise, the  time
                 is assumed to be in the local time zone.  If the DST daylight saving flag is positive, the time is assumed to be day‐
                 light saving time; if zero, the time is assumed to be standard time; and if negative (the default), mktime() attempts
                 to  determine  whether daylight saving time is in effect for the specified time.  If datespec does not contain enough
                 elements or if the resulting time is out of range, mktime() returns -1.
    
       strftime([format [, timestamp[, utc-flag]]])
                 Format timestamp according to the specification in format.  If utc-flag is present and is non-zero or  non-null,  the
                 result  is  in  UTC,  otherwise the result is in local time.  The timestamp should be of the same form as returned by
                 systime().  If timestamp is missing, the current time of day is used.  If format is missing, a default format equiva‐
                 lent  to the output of date(1) is used.  The default format is available in PROCINFO["strftime"].  See the specifica‐
                 tion for the strftime() function in ISO C for the format conversions that are guaranteed to be available.
    
       systime() Return the current time of day as the number of seconds since the Epoch (1970-01-01 00:00:00 UTC on POSIX systems).
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    Bit Manipulations Functions
    Gawk supplies the following bit manipulation functions. They work by converting double-precision floating point values to
    uintmax_t integers, doing the operation, and then converting the result back to floating point.

       NOTE: Passing negative operands to any of these functions causes a fatal error.
    
       The functions are:
    
       and(v1, v2 [, ...]) Return the bitwise AND of the values provided in the argument list.  There must be at least two.
    
       compl(val)          Return the bitwise complement of val.
    
       lshift(val, count)  Return the value of val, shifted left by count bits.
    
       or(v1, v2 [, ...])  Return the bitwise OR of the values provided in the argument list.  There must be at least two.
    
       rshift(val, count)  Return the value of val, shifted right by count bits.
    
       xor(v1, v2 [, ...]) Return the bitwise XOR of the values provided in the argument list.  There must be at least two.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Type Functions
    The following functions provide type related information about their arguments.

       isarray(x) Return  true  if  x  is an array, false otherwise.  This function is mainly for use with the elements of multidimen‐
                  sional arrays and with function parameters.
    
       typeof(x)  Return a string indicating the type of x.  The string will be one of "array", "number",  "regexp",  "string",  "str‐
                  num", "unassigned", or "undefined".
    
    • 1
    • 2
    • 3
    • 4
    • 5

    Internationalization Functions
    The following functions may be used from within your AWK program for translating strings at run-time. For full details, see
    GAWK: Effective AWK Programming.

       bindtextdomain(directory [, domain])
              Specify the directory where gawk looks for the .gmo files, in case they will not or cannot be placed in the ``standard''
              locations (e.g., during testing).  It returns the directory where domain is ``bound.''
              The  default domain is the value of TEXTDOMAIN.  If directory is the null string (""), then bindtextdomain() returns the
              current binding for the given domain.
    
       dcgettext(string [, domain [, category]])
              Return the translation of string in text domain domain for locale category category.  The default value  for  domain  is
              the current value of TEXTDOMAIN.  The default value for category is "LC_MESSAGES".
              If  you  supply a value for category, it must be a string equal to one of the known locale categories described in GAWK:
              Effective AWK Programming.  You must also supply a text domain.  Use TEXTDOMAIN if you want to use the current domain.
    
       dcngettext(string1, string2, number [, domain [, category]])
              Return the plural form used for number of the translation of string1 and string2 in text domain domain for locale  cate‐
              gory  category.   The  default  value  for domain is the current value of TEXTDOMAIN.  The default value for category is
              "LC_MESSAGES".
              If you supply a value for category, it must be a string equal to one of the known locale categories described  in  GAWK:
              Effective AWK Programming.  You must also supply a text domain.  Use TEXTDOMAIN if you want to use the current domain.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    USER-DEFINED FUNCTIONS
    Functions in AWK are defined as follows:

              function name(parameter list) { statements }
    
       Functions  execute  when  they are called from within expressions in either patterns or actions.  Actual parameters supplied in
       the function call are used to instantiate the formal parameters declared in the function.   Arrays  are  passed  by  reference,
       other variables are passed by value.
    
       Since  functions were not originally part of the AWK language, the provision for local variables is rather clumsy: They are de‐
       clared as extra parameters in the parameter list.  The convention is to separate local variables from real parameters by  extra
       spaces in the parameter list.  For example:
    
              function  f(p, q,     a, b)   # a and b are local
              {
                   ...
              }
    
              /abc/     { ... ; f(1, 2) ; ... }
    
       The  left  parenthesis  in  a function call is required to immediately follow the function name, without any intervening white‐
       space.  This avoids a syntactic ambiguity with the concatenation operator.  This restriction does not  apply  to  the  built-in
       functions listed above.
    
       Functions  may  call  each other and may be recursive.  Function parameters used as local variables are initialized to the null
       string and the number zero upon function invocation.
    
       Use return expr to return a value from a function.  The return value is undefined if no value is provided, or if  the  function
       returns by “falling off” the end.
    
       As a gawk extension, functions may be called indirectly. To do this, assign the name of the function to be called, as a string,
       to a variable.  Then use the variable as if it were the name of a function, prefixed with an @ sign, like so:
              function myfunc()
              {
                   print "myfunc called"
                   ...
              }
    
              {    ...
                   the_func = "myfunc"
                   @the_func()    # call through the_func to myfunc
                   ...
              }
       As of version 4.1.2, this works with user-defined functions, built-in functions, and extension functions.
    
       If --lint has been provided, gawk warns about calls to undefined functions at parse time, instead of at run time.   Calling  an
       undefined function at run time is a fatal error.
    
       The word func may be used in place of function, although this is deprecated.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    DYNAMICALLY LOADING NEW FUNCTIONS
    You can dynamically add new functions written in C or C++ to the running gawk interpreter with the @load statement. The full
    details are beyond the scope of this manual page; see GAWK: Effective AWK Programming.

    SIGNALS
    The gawk profiler accepts two signals. SIGUSR1 causes it to dump a profile and function call stack to the profile file, which
    is either awkprof.out, or whatever file was named with the --profile option. It then continues to run. SIGHUP causes gawk to
    dump the profile and function call stack and then exit.

    INTERNATIONALIZATION
    String constants are sequences of characters enclosed in double quotes. In non-English speaking environments, it is possible
    to mark strings in the AWK program as requiring translation to the local natural language. Such strings are marked in the AWK
    program with a leading underscore (“_”). For example,

              gawk 'BEGIN { print "hello, world" }'
    
       always prints hello, world.  But,
    
              gawk 'BEGIN { print _"hello, world" }'
    
       might print bonjour, monde in France.
    
       There are several steps involved in producing and running a localizable AWK program.
    
       1.  Add a BEGIN action to assign a value to the TEXTDOMAIN variable to set the text domain to a name associated with your  pro‐
           gram:
    
                BEGIN { TEXTDOMAIN = "myprog" }
    
           This  allows  gawk  to find the .gmo file associated with your program.  Without this step, gawk uses the messages text do‐
           main, which likely does not contain translations for your program.
    
       2.  Mark all strings that should be translated with leading underscores.
    
       3.  If necessary, use the dcgettext() and/or bindtextdomain() functions in your program, as appropriate.
    
       4.  Run gawk --gen-pot -f myprog.awk > myprog.pot to generate a .pot file for your program.
    
       5.  Provide appropriate translations, and build and install the corresponding .gmo files.
    
       The internationalization features are described in full detail in GAWK: Effective AWK Programming.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    POSIX COMPATIBILITY
    A primary goal for gawk is compatibility with the POSIX standard, as well as with the latest version of Brian Kernighan’s awk.
    To this end, gawk incorporates the following user visible features which are not described in the AWK book, but are part of the
    Brian Kernighan’s version of awk, and are in the POSIX standard.

       The book indicates that command line variable assignment happens when awk would otherwise open the argument as a file, which is
       after the BEGIN rule is executed.  However, in earlier implementations, when such an assignment appeared before any file names,
       the assignment would happen before the BEGIN rule was run.  Applications came to  depend  on  this  “feature.”   When  awk  was
       changed to match its documentation, the -v option for assigning variables before program execution was added to accommodate ap‐
       plications that depended upon the old behavior.  (This feature was agreed upon by both the Bell Laboratories developers and the
       GNU developers.)
    
       When  processing  arguments, gawk uses the special option “--” to signal the end of arguments.  In compatibility mode, it warns
       about but otherwise ignores undefined options.  In normal operation, such arguments are passed on to the AWK program for it  to
       process.
    
       The  AWK  book  does  not define the return value of srand().  The POSIX standard has it return the seed it was using, to allow
       keeping track of random number sequences.  Therefore srand() in gawk also returns its current seed.
    
       Other features are: The use of multiple -f options (from MKS awk); the ENVIRON array; the \a, and  \v  escape  sequences  (done
       originally  in  gawk and fed back into the Bell Laboratories version); the tolower() and toupper() built-in functions (from the
       Bell Laboratories version); and the ISO C conversion specifications in printf (done first in the Bell Laboratories version).
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    HISTORICAL FEATURES
    There is one feature of historical AWK implementations that gawk supports: It is possible to call the length() built-in func‐
    tion not only with no argument, but even without parentheses! Thus,

              a = length     # Holy Algol 60, Batman!
    
       is the same as either of
    
              a = length()
              a = length($0)
    
       Using this feature is poor practice, and gawk issues a warning about its use if --lint is specified on the command line.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    GNU EXTENSIONS
    Gawk has a too-large number of extensions to POSIX awk. They are described in this section. All the extensions described here
    can be disabled by invoking gawk with the --traditional or --posix options.

       The following features of gawk are not available in POSIX awk.
    
       • No path search is performed for files named via the -f option.  Therefore the AWKPATH environment variable is not special.
    
       • There is no facility for doing file inclusion (gawk's @include mechanism).
    
       • There is no facility for dynamically adding new functions written in C (gawk's @load mechanism).
    
       • The \x escape sequence.
    
       • The ability to continue lines after ?  and :.
    
       • Octal and hexadecimal constants in AWK programs.
    
       • The ARGIND, BINMODE, ERRNO, LINT, PREC, ROUNDMODE, RT and TEXTDOMAIN variables are not special.
    
       • The IGNORECASE variable and its side-effects are not available.
    
       • The FIELDWIDTHS variable and fixed-width field splitting.
    
       • The FPAT variable and field splitting based on field values.
    
       • The FUNCTAB, SYMTAB, and PROCINFO arrays are not available.
    
       • The use of RS as a regular expression.
    
       • The special file names available for I/O redirection are not recognized.
    
       • The |& operator for creating coprocesses.
    
       • The BEGINFILE and ENDFILE special patterns are not available.
    
       • The ability to split out individual characters using the null string as the value  of  FS,  and  as  the  third  argument  to
         split().
    
       • An optional fourth argument to split() to receive the separator texts.
    
       • The optional second argument to the close() function.
    
       • The optional third argument to the match() function.
    
       • The ability to use positional specifiers with printf and sprintf().
    
       • The ability to pass an array to length().
    
       • The  and(), asort(), asorti(), bindtextdomain(), compl(), dcgettext(), dcngettext(), gensub(), lshift(), mktime(), or(), pat‐
         split(), rshift(), strftime(), strtonum(), systime() and xor() functions.
    
       • Localizable strings.
    
       • Non-fatal I/O.
    
       • Retryable I/O.
    
       The AWK book does not define the return value of the close() function.  Gawk's close() returns the  value  from  fclose(3),  or
       pclose(3), when closing an output file or pipe, respectively.  It returns the process's exit status when closing an input pipe.
       The return value is -1 if the named file, pipe or coprocess was not opened with a redirection.
    
       When gawk is invoked with the --traditional option, if the fs argument to the -F option is “t”, then FS is set to the tab char‐
       acter.   Note  that  typing  gawk  -F\t ...  simply causes the shell to quote the “t,” and does not pass “\t” to the -F option.
       Since this is a rather ugly special case, it is not the default behavior.  This behavior also does not  occur  if  --posix  has
       been specified.  To really get a tab character as the field separator, it is best to use single quotes: gawk -F'\t' ....
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    ENVIRONMENT VARIABLES
    The AWKPATH environment variable can be used to provide a list of directories that gawk searches when looking for files named
    via the -f, --file, -i and --include options, and the @include directive. If the initial search fails, the path is searched
    again after appending .awk to the filename.

       The  AWKLIBPATH  environment  variable  can  be used to provide a list of directories that gawk searches when looking for files
       named via the -l and --load options.
    
       The GAWK_READ_TIMEOUT environment variable can be used to specify a timeout in milliseconds for reading input from a  terminal,
       pipe or two-way communication including sockets.
    
       For  connection to a remote host via socket, GAWK_SOCK_RETRIES controls the number of retries, and GAWK_MSEC_SLEEP the interval
       between retries.  The interval is in milliseconds. On systems that do not support usleep(3), the value is rounded up to an  in‐
       tegral number of seconds.
    
       If  POSIXLY_CORRECT  exists in the environment, then gawk behaves exactly as if --posix had been specified on the command line.
       If --lint has been specified, gawk issues a warning message to this effect.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    EXIT STATUS
    If the exit statement is used with a value, then gawk exits with the numeric value given to it.

       Otherwise, if there were no problems during execution, gawk exits with the value of the C constant EXIT_SUCCESS.  This is  usu‐
       ally zero.
    
       If an error occurs, gawk exits with the value of the C constant EXIT_FAILURE.  This is usually one.
    
       If gawk exits because of a fatal error, the exit status is 2.  On non-POSIX systems, this value may be mapped to EXIT_FAILURE.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    VERSION INFORMATION
    This man page documents gawk, version 5.1.

    AUTHORS
    The original version of UNIX awk was designed and implemented by Alfred Aho, Peter Weinberger, and Brian Kernighan of Bell Lab‐
    oratories. Brian Kernighan continues to maintain and enhance it.

       Paul Rubin and Jay Fenlason, of the Free Software Foundation, wrote gawk, to be compatible with the  original  version  of  awk
       distributed  in  Seventh  Edition  UNIX.  John Woods contributed a number of bug fixes.  David Trueman, with contributions from
       Arnold Robbins, made gawk compatible with the new version of UNIX awk.  Arnold Robbins is the current maintainer.
    
       See GAWK: Effective AWK Programming for a full list of the contributors to gawk and its documentation.
    
       See the README file in the gawk distribution for up-to-date information about maintainers and which ports  are  currently  sup‐
       ported.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    BUG REPORTS
    If you find a bug in gawk, please send electronic mail to bug-gawk@gnu.org. Please include your operating system and its revi‐
    sion, the version of gawk (from gawk --version), which C compiler you used to compile it, and a test program and data that are
    as small as possible for reproducing the problem.

       Before  sending  a  bug  report, please do the following things.  First, verify that you have the latest version of gawk.  Many
       bugs (usually subtle ones) are fixed at each release, and if yours is out of date, the problem may already  have  been  solved.
       Second,  please see if setting the environment variable LC_ALL to LC_ALL=C causes things to behave as you expect. If so, it's a
       locale issue, and may or may not really be a bug.  Finally, please read this man page and the reference manual carefully to  be
       sure that what you think is a bug really is, instead of just a quirk in the language.
    
       Whatever  you do, do NOT post a bug report in comp.lang.awk.  While the gawk developers occasionally read this newsgroup, post‐
       ing bug reports there is an unreliable way to report bugs.  Similarly, do NOT use a web forum (such as Stack Overflow) for  re‐
       porting bugs.  Instead, please use the electronic mail addresses given above.  Really.
    
       If  you're  using  a  GNU/Linux  or  BSD-based  system, you may wish to submit a bug report to the vendor of your distribution.
       That's fine, but please send a copy to the official email address as well, since there's no guarantee that the bug report  will
       be forwarded to the gawk maintainer.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    BUGS
    The -F option is not necessary given the command line variable assignment feature; it remains only for backwards compatibility.

    SEE ALSO
    egrep(1), sed(1), getpid(2), getppid(2), getpgrp(2), getuid(2), geteuid(2), getgid(2), getegid(2), getgroups(2), printf(3),
    strftime(3), usleep(3)

       The AWK  Programming  Language,  Alfred  V.  Aho,  Brian  W.  Kernighan,  Peter  J.  Weinberger,  Addison-Wesley,  1988.   ISBN
       0-201-07981-X.
    
       GAWK:  Effective AWK Programming, Edition 5.1, shipped with the gawk source.  The current version of this document is available
       online at https://www.gnu.org/software/gawk/manual.
    
       The GNU gettext documentation, available online at https://www.gnu.org/software/gettext.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    EXAMPLES
    Print and sort the login names of all users:

            BEGIN     { FS = ":" }
                 { print $1 | "sort" }
    
       Count lines in a file:
    
                 { nlines++ }
            END  { print nlines }
    
       Precede each line by its number in the file:
    
            { print FNR, $0 }
    
       Concatenate and line number (a variation on a theme):
    
            { print NR, $0 }
    
       Run an external command for particular lines of data:
    
            tail -f access_log |
            awk '/myhome.html/ { system("nmap " $1 ">> logdir/myhome.html") }'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    ACKNOWLEDGEMENTS
    Brian Kernighan provided valuable assistance during testing and debugging. We thank him.

    COPYING PERMISSIONS
    Copyright © 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002, 2003, 2004, 2005, 2007, 2009, 2010, 2011,
    2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, Free Software Foundation, Inc.

       Permission is granted to make and distribute verbatim copies of this manual page provided the copyright notice and this permis‐
       sion notice are preserved on all copies.
    
       Permission is granted to copy and distribute modified versions of this manual page under the conditions for  verbatim  copying,
       provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.
    
       Permission is granted to copy and distribute translations of this manual page into another language, under the above conditions
       for modified versions, except that this permission notice may be stated in a translation approved by the Foundation.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Free Software Foundation Mar 23 2020 GAWK(1)




    UbuntuServer2210 的 man mawk

    MAWK(1) USER COMMANDS MAWK(1)

    NAME
    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 language is useful for manipulation of data files, text re‐
    trieval and processing, 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 conforms 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  synonymous  with
       lines.  Each record is compared against each pattern and if it matches, the program text for {action} is executed.
    
    • 1
    • 2
    • 3
    • 4
    • 5

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

       -f file        Program text is read from file instead of from the command 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 implementation of AWK.  Implementation specific options are pref‐
       aced with -W.  mawk provides these:
    
       -W dump        writes an assembler like listing of the internal representation of the program to stdout and exits  0  (on  suc‐
                      cessful compilation).
    
       -W exec file   Program text is read from file and this is the last option.
    
                      This  is  a  useful  alternative  to -f on systems that support the #!  “magic number” convention for executable
                      scripts.  Those implicitly pass the pathname of the script itself as the final parameter,  and  expect  no  more
                      than  one  “-” option on the #! line.  Because mawk can combine multiple -W options separated by commas, you can
                      use this option when an additional -W option is needed.
    
       -W help        prints a usage message to stderr and exits (same as “-W usage”).
    
       -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 posix_space forces mawk not to consider '\n' to be space.
    
       -W random=num  calls srand with the given parameter (and overrides the auto-seeding behavior).
    
       -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 usage       prints a usage message to stderr and exits (same as “-W help”).
    
       -W version     mawk writes its version and copyright to stdout and compiled limits to stderr and exits 0.
    
       mawk accepts abbreviations for any of these options, e.g., “-W v” and “-Wv” both tell mawk to show its version.
    
       mawk allows multiple -W options to be combined by separating the options with commas, e.g., -Wsprint=2000,posix.  This is  use‐
       ful for executable #!  “magic number” invocations in which only one argument is supported, e.g., -Winteractive,exec.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    THE AWK LANGUAGE

    1. Program structure
      An AWK program is a sequence of pattern {action} pairs and user function 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 omit‐
      ted, 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 statement 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
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
    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 scien‐
      tific 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"
      
      • 1

      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
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

      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 evalu‐
      ate the statements

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

      The value stored in variable y will be typed numeric. If x is not numeric, the value read from x is converted to numeric be‐
      fore 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 con‐
      verted to string if necessary 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 expres‐
      sion 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 functional‐
      ity 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 op‐
      erands 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/
      
      • 1

      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 }
      
      • 1

      are the same, and for each input record that matches r, action is executed. In fact, /r/ is an AWK expression that is equiva‐
      lent 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 the -E option of grep(1). The regular expression metacharacters, i.e., those
      with special meaning in regular expressions are

        \ ^ $ . [ ] | ( ) * + ?
      
      • 1

      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...
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15

      Regular expressions are built up from other regular expressions as follows:

        r1r2         matches r1 followed immediately by r2 (concatenation).
      
        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.
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11

      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]+)?$/
      
      • 1
      • 2

      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 !~ operators or passed to a built-in that expects a regular ex‐
      pression. 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
      
      • 1
      • 2
      • 3

      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
      
      • 1
      • 2
    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
      
      • 1
      • 2
      • 3

      $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    in
        matching       ~   !~
        relational          <  >   <=  >=  ==  !=
        concatenation       (no explicit operator)
        add ops             +  -
        mul ops             *  /  %
        unary               +  -
        logical not         !
        exponentiation      ^
        inc and dec         ++ -- (both post and pre)
        field               $
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15

      Assignment, conditional and exponentiation associate right to left; the other operators associate left to right. Any expres‐
      sion can be parenthesized.

    6. Arrays
      Awk provides one-dimensional arrays. Array elements are expressed as array[expr]. Expr is internally converted to string
      type, so, for example, A[1] and A[“1”] are the same element and the actual index is “1”. Arrays indexed by strings are called
      associative arrays. Initially an array is empty; elements exist when first accessed. An expression, expr in array evaluates
      to 1 if array[expr] exists, else to 0.

      There is a form of the for statement that loops over each index of an array.

        for ( var in array ) statement
      
      • 1

      sets var to each index of array and executes statement. The order that var transverses the indices of array is not defined.

      The statement, delete array[expr], causes array[expr] not to exist. mawk supports an extension, delete array, which deletes
      all elements of array.

      Multidimensional arrays are synthesized with concatenation using the built-in variable SUBSEP. array[expr1,expr2] is equiva‐
      lent to array[expr1 SUBSEP expr2]. Testing for a multidimensional element uses a parenthesized index, such as

        if ( (i, j) in A )  print A[i, j]
      
      • 1
    7. Builtin-variables
      The following variables are built-in and initialized before program execution.

        ARGC      number of command line arguments.
      
        ARGV      array of command line arguments, 0..ARGC-1.
      
        CONVFMT   format for internal conversion of numbers to string, initially = "%.6g".
      
        ENVIRON   array indexed by environment variables.  An environment string, var=value is stored as ENVIRON[var] = value.
      
        FILENAME  name of the current input file.
      
        FNR       current record number in FILENAME.
      
        FS        splits records into fields as a regular expression.
      
        NF        number of fields in the current record.
      
        NR        current record number in the total input stream.
      
        OFMT      format for printing numbers; initially = "%.6g".
      
        OFS       inserted between fields on output, initially = " ".
      
        ORS       terminates each record on output, initially = "\n".
      
        RLENGTH   length set by the last call to the built-in function, match().
      
        RS        input record separator, initially = "\n".
      
        RSTART    index set by the last call to match().
      
        SUBSEP    used to build multiple array subscripts, initially = "\034".
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
    8. Built-in functions
      String functions

        gsub(r,s,t)  gsub(r,s)
               Global  substitution, every match of regular expression r in variable t is replaced by string s.  The number of re‐
               placements is returned.  If t is omitted, $0 is used.  An & in the replacement string s is replaced by the  matched
               substring of t.  \& and \\ put  literal & and \, respectively, in the replacement string.
      
        index(s,t)
               If t is a substring of s, then the position where t starts is returned, else 0 is returned.  The first character of
               s is in position 1.
      
        length(s)
               Returns the length of string or array.  s.
      
        match(s,r)
               Returns the index of the first longest match of regular expression r in string s.  Returns 0 if  no  match.   As  a
               side  effect,  RSTART is set to the return value.  RLENGTH is set to the length of the match or -1 if no match.  If
               the empty string is matched, RLENGTH is set to 0, and 1 is returned if the match is at the front,  and  length(s)+1
               is returned if the match is at the back.
      
        split(s,A,r)  split(s,A)
               String s is split into fields by regular expression r and the fields are loaded into array A.  The number of fields
               is returned.  See section 11 below for more detail.  If r is omitted, FS is used.
      
        sprintf(format,expr-list)
               Returns a string constructed from expr-list according to format.  See the description of printf() below.
      
        sub(r,s,t)  sub(r,s)
               Single substitution, same as gsub() except at most one substitution.
      
        substr(s,i,n)  substr(s,i)
               Returns the substring of string s, starting at index i, of length n.  If n is omitted, the suffix of s, starting at
               i is returned.
      
        tolower(s)
               Returns a copy of s with all upper case characters converted to lower case.
      
        toupper(s)
               Returns a copy of s with all lower case characters converted to upper case.
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37

      Time functions

      These are available on systems which support the corresponding C mktime and strftime functions:

        mktime(specification)
               converts  a  date  specification to a timestamp with the same units as systime.  The date specification is a string
               containing the components of the date as decimal integers:
      
               YYYY
                  the year, e.g., 2012
      
               MM the month of the year starting at 1
      
               DD the day of the month starting at 1
      
               HH hour (0-23)
      
               MM minute (0-59)
      
               SS seconds (0-59)
      
               DST
                  tells how to treat timezone versus daylight savings time:
      
                    positive
                       DST is in effect
      
                    zero (default)
                       DST is not in effect
      
                    negative
                       mktime() should (use timezone information and system databases to) attempt  to determine whether DST is  in
                       effect at the specified time.
      
        strftime([format [, timestamp [, utc ]]])
               formats the given timestamp using the format (passed to the C strftime function):
      
               •   If the format parameter is missing, "%c" is used.
      
               •   If the timestamp parameter is missing, the current value from systime is used.
      
               •   If the utc parameter is present and nonzero, the result is in UTC.  Otherwise local time is used.
      
        systime()
               returns  the  current  time  of day as the number of seconds since the Epoch (1970-01-01 00:00:00 UTC on POSIX sys‐
               tems).
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42

      Arithmetic functions

        atan2(y,x)     Arctan of y/x between -pi and pi.
      
        cos(x)         Cosine function, x in radians.
      
        exp(x)         Exponential function.
      
        int(x)         Returns x truncated towards zero.
      
        log(x)         Natural logarithm.
      
        rand()         Returns a random number between zero and one.
      
        sin(x)         Sine function, x in radians.
      
        sqrt(x)        Returns square root of x.
      
        srand(expr)  srand()
               Seeds the random number generator, using the clock if expr is omitted, and returns the value of the previous  seed.
               Srand(expr) is useful for repeating pseudo random sequences.
      
               Note: mawk is normally configured to seed the random number generator from the clock at startup, making it unneces‐
               sary to call srand().  This feature can be suppressed via conditional compile, or overridden using the -Wrandom op‐
               tion.
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
    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 output.  Numeric expressions are converted to string with
               OFMT.
      
        printf format, expr-list
               duplicates the printf C library function writing to standard 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 qualifiers h
               and l.
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10

      The argument list to print or printf can optionally be enclosed in parentheses. Print formats numbers using OFMT or “%d” for
      exact integers. “%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, subsequent redirections ap‐
      pend to the already open stream. By convention, mawk associates the filename

      •   "/dev/stderr" with stderr,
      
      •   "/dev/stdout" with stdout,
      
      •   "-" and "/dev/stdin" with stdin.
      
      • 1
      • 2
      • 3
      • 4
      • 5

      The association with stderr is especially useful because it allows print and printf to be redirected to stderr. These names
      can also 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.
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17

      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 sta‐
      tus 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 conserve 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 argument (“”) flushes all open output.

      The function system(expr) uses the C runtime system call to execute expr and returns the corresponding wait status of the com‐
      mand as follows:

      • if the system call failed, setting the status to -1, mawk returns that value.

      • if the command exited normally, mawk returns its exit-status.

      • if the command exited due to a signal such as SIGHUP, mawk returns the signal number plus 256.

      Changes made to the ENVIRON array are not passed to commands executed with system or pipes.

    10. User defined functions
      The syntax for a user defined function is

       function name( args ) { statements }
      
      • 1

      The function body can contain a return statement

       return opt_expr
      
      • 1

      A return statement is not required. Function calls may be nested or recursive. Functions are passed expressions by value and
      arrays by reference. Extra arguments serve as local variables and are initialized to null. For example, csplit(s,A) puts each
      character of s into array A and returns the length of s.

       function csplit(s, A,    n, i)
       {
         n = length(s)
         for( i = 1 ; i <= n ; i++ ) A[i] = substr(s, i, 1)
         return n
       }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6

      Putting extra space between passed arguments and local variables is conventional. Functions can be referenced before they are
      defined, but the function name and the ‘(’ of the arguments must touch to avoid confusion with concatenation.

      A function parameter is normally a scalar value (number or string). If there is a forward reference to a function using an ar‐
      ray as a parameter, the function’s corresponding parameter will be treated as an array.

    11. Splitting strings, records and files
      Awk programs use the same algorithm to split strings into arrays with split(), and records into fields on FS. mawk uses essen‐
      tially the same algorithm to split files into records on RS.

      Split(expr,A,sep) works as follows:

      (1) If sep is omitted, it is replaced by FS. Sep can be an expression or regular expression. If it is an expression of
      non-string type, it is converted to string.

      (2) If sep = " " (a single space), then is trimmed from the front and back of expr, and sep becomes . mawk
      defines as the regular expression /[ \t\n]+/. Otherwise sep is treated as a regular expression, except that
      meta-characters are ignored for a string of length 1, e.g., split(x, A, “*”) and split(x, A, /*/) are the same.

      (3) If expr is not string, it is converted to string. If expr is then the empty string “”, split() returns 0 and A is set
      empty. Otherwise, all non-overlapping, non-null and longest matches of sep in expr, separate expr into fields which
      are loaded into A. The fields are placed in A[1], A[2], …, A[n] and split() returns n, the number of fields which is
      the number of matches plus one. Data placed in A that looks numeric is typed number and string.

      Splitting records into fields works the same except the pieces are loaded into $1, $2,…, $NF. If $0 is empty, NF is set to 0
      and all $i to “”.

      mawk splits files into records by the same algorithm, but with the slight difference that RS is really a terminator instead of
      a separator. (ORS is really a terminator too).

       E.g., if FS = “:+” and $0 = “a::b:” , then NF = 3 and $1 = “a”, $2 = “b” and $3 = "", but if “a::b:” is the contents of an
       input file and RS = “:+”, then there are two records “a” and “b”.
      
      • 1
      • 2

      RS = " " is not special.

      If FS = “”, then mawk breaks the record into individual characters, and, similarly, split(s,A,“”) places the individual charac‐
      ters of s into A.

    12. Multi-line records
      Since mawk interprets RS as a regular expression, multi-line records are easy. Setting RS = “\n\n+”, makes one or more blank
      lines separate records. If FS = " " (the default), then single newlines, by the rules for above, become space and sin‐
      gle newlines are field separators.

       For example, if
      
       •   a file is "a b\nc\n\n",
      
       •   RS = "\n\n+" and
      
       •   FS = " ",
      
       then there is one record “a b\nc” with three fields “a”, “b” and “c”:
      
       •   Changing FS = “\n”, gives two fields “a b” and “c”;
      
       •   changing FS = “”, gives one field identical to the record.
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13

      If you want lines with spaces or tabs to be considered blank, set RS = “\n([ \t]*\n)+”. For compatibility with other awks,
      setting RS = “” has the same effect as if blank lines are stripped from the front and back of files and then records are deter‐
      mined as if RS = “\n\n+”. POSIX requires that “\n” always separates records when RS = “” regardless of the value of FS. mawk
      does not support this convention, because defining “\n” as makes it unnecessary.

      Most of the time when you change RS for multi-line records, you will also want to change ORS to “\n\n” so the record spacing is
      preserved on output.

    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 execution phase of the program. ARGV[0] is set the name of the AWK interpreter 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
      
      • 1

      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 i 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 ex‐
      ecuted. An expression pattern matches if it is boolean true (see the end of section 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
       nextfile
       exit  opt_expr
      
      • 1
      • 2
      • 3

      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.

      • A nextfile statement tells mawk to stop processing the current input file. It then updates FILENAME to the next file
      listed on the command line, and resets FNR to 1.

      • An exit statement causes immediate execution of the END actions or program termination if there are none or if the exit oc‐
      curs in an END action. The opt_expr sets the exit value of the program unless overridden by a later exit or subsequent er‐
      ror.

    EXAMPLES
    1. emulate cat.

            { print }
    
       2. emulate wc.
    
            { chars += length($0) + 1  # add one for the \n
              words += NF
            }
    
            END{ print NR, words, chars }
    
       3. count the number of unique “real words”.
    
            BEGIN { FS = "[^A-Za-z]+" }
    
            { for(i = 1 ; i <= NF ; i++)  word[$i] = "" }
    
            END { delete word[""]
                  for ( i in word )  cnt++
                  print cnt
            }
    
       4. sum the second field of every record based on the first field.
    
            $1 ~ /credit|gain/ { sum += $2 }
            $1 ~ /debit|loss/  { sum -= $2 }
    
            END { print sum }
    
       5. sort a file, comparing as string
    
            { line[NR] = $0 "" }  # make sure of comparison type
                            # in case some lines look numeric
    
            END {  isort(line, NR)
              for(i = 1 ; i <= NR ; i++) print line[i]
            }
    
            #insertion sort of A[1..n]
            function isort( A, n,    i, j, hold)
            {
              for( i = 2 ; i <= n ; i++)
              {
                hold = A[j = i]
                while ( A[j-1] > hold )
                { j-- ; A[j+1] = A[j] }
                A[j] = hold
              }
              # sentinel A[0] = "" will be created if needed
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    COMPATIBILITY ISSUES
    MAWK 1.3.3 versus POSIX 1003.2 Draft 11.3
    The POSIX 1003.2(draft 11.3) definition of the AWK language is AWK as described in the AWK book with a few extensions that ap‐
    peared in SystemVR4 nawk. The extensions are:

          •   New functions: toupper() and tolower().
    
          •   New variables: ENVIRON[] and CONVFMT.
    
          •   ANSI C conversion specifications for printf() and sprintf().
    
          •   New command options:  -v var=value, multiple -f options and implementation options as arguments to -W.
    
          •   For  systems  (MS-DOS  or  Windows) which provide a setmode function, an environment variable MAWKBINMODE and a built-in
              variable BINMODE.  The bits of the BINMODE value tell mawk how to modify the RS and ORS variables:
    
              0  set standard input to binary mode, and if BIT-2 is unset, set RS to "\r\n" (CR/LF) rather than "\n" (LF).
    
              1  set standard output to binary mode, and if BIT-2 is unset, set ORS to "\r\n" (CR/LF) rather than "\n" (LF).
    
              2  suppress the assignment to RS and ORS of CR/LF, making it possible to run scripts and generate output compatible with
                 Unix line-endings.
    
       POSIX AWK is oriented to operate on files a line at a time.  RS can be changed from "\n" to another single character, but it is
       hard to find any use for this — there are no examples in the AWK book.  By convention, RS = "", makes one or more  blank  lines
       separate records, allowing multi-line records.  When RS = "", "\n" is always a field separator regardless of the value in FS.
    
       mawk,  on  the  other hand, allows RS to be a regular expression.  When "\n" appears in records, it is treated as space, and FS
       always determines fields.
    
       Removing the line at a time paradigm can make some programs simpler and can often improve performance.   For  example,  redoing
       example 3 from above,
    
            BEGIN { RS = "[^A-Za-z]+" }
    
            { word[ $0 ] = "" }
    
            END { delete  word[ "" ]
              for( i in word )  cnt++
              print cnt
            }
    
       counts  the  number of unique words by making each word a record.  On moderate size files, mawk executes twice as fast, because
       of the simplified inner loop.
    
       The following program replaces each comment by a single space in a C program file,
    
            BEGIN {
              RS = "/\*([^*]|\*+[^/*])*\*+/"
                 # comment is record separator
              ORS = " "
              getline  hold
              }
    
              { print hold ; hold = $0 }
    
              END { printf "%s" , hold }
    
       Buffering one record is needed to avoid terminating the last record with a space.
    
       With mawk, the following are all equivalent,
    
            x ~ /a\+b/    x ~ "a\+b"     x ~ "a\\+b"
    
       The strings get scanned twice, once as string and once as regular expression.  On the string scan, mawk ignores the  escape  on
       non-escape characters while the AWK book advocates \c be recognized as c which necessitates the double escaping of meta-charac‐
       ters in strings.  POSIX explicitly declines to define the behavior which passively forces programs that must run under a  vari‐
       ety of awks to use the more portable but less readable, double escape.
    
       POSIX  AWK  does  not recognize "/dev/std{in,out,err}".  Some systems provide an actual device for this, allowing AWKs which do
       not implement the feature directly to support it.
    
       POSIX AWK does not recognize \x hex escape sequences in strings.  Unlike ANSI C, mawk limits the number of digits that  follows
       \x  to two as the current implementation only supports 8 bit characters.  The built-in fflush first appeared in a recent (1993)
       AT&T awk released to netlib, and is not part of the POSIX standard.  Aggregate deletion with delete array is not  part  of  the
       POSIX standard.
    
       POSIX  explicitly leaves the behavior of FS = "" undefined, and mentions splitting the record into characters as a possible in‐
       terpretation, but currently this use is not portable across implementations.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    Random numbers
    POSIX does not prescribe a method for initializing random numbers at startup.

       In practice, most implementations do nothing special, which makes srand and rand follow the C runtime library, making the  ini‐
       tial  seed  value 1.  Some implementations (Solaris XPG4 and Tru64) return 0 from the first call to srand, although the results
       from rand behave as if the initial seed is 1.  Other implementations return 1.
    
       While mawk can call srand at startup with no parameter (initializing random numbers from the clock), this feature may  be  sup‐
       pressed using conditional compilation.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Extensions added for compatibility for GAWK and BWK
    Nextfile is a gawk extension (also implemented by BWK awk), is not yet part of the POSIX standard (as of October 2012), al‐
    though it has been accepted for the next revision of the standard.

       Mktime, strftime and systime are gawk extensions.
    
       The "/dev/stdin" feature was added to mawk after 1.3.4, for compatibility with gawk and BWK awk.  The corresponding "-"  (alias
       for /dev/stdin) was present in mawk 1.3.3.
    
    • 1
    • 2
    • 3
    • 4

    Subtle Differences not in POSIX or the AWK Book
    Finally, here is how mawk handles exceptional cases not discussed in the AWK book or the POSIX draft. It is unsafe to assume
    consistency across awks and safe to skip to the next section.

          •   substr(s, i, n) returns the characters of s in the intersection of the closed interval [1, length(s)] and the  half-open
              interval  [i, i+n).  When this intersection is empty, the empty string is returned; so substr("ABC", 1, 0) = "" and sub‐
              str("ABC", -4, 6) = "A".
    
          •   Every string, including the empty string, matches the empty string at the front so, s ~ // and s ~ "", are always  1  as
              is match(s, //) and match(s, "").  The last two set RLENGTH to 0.
    
          •   index(s, t) is always the same as match(s, t1) where t1 is the same as t with metacharacters escaped.  Hence consistency
              with match requires that index(s, "") always returns 1.  Also the condition, index(s,t) != 0 if and only  t  is  a  sub‐
              string of s, requires index("","") = 1.
    
          •   If  getline  encounters end of file, getline var, leaves var unchanged.  Similarly, on entry to the END actions, $0, the
              fields and NF have their value unaltered from the last record.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    ENVIRONMENT VARIABLES
    Mawk recognizes these variables:

          MAWKBINMODE
             (see COMPATIBILITY ISSUES)
    
          MAWK_LONG_OPTIONS
             If this is set, mawk uses its value to decide what to do with GNU-style long options:
    
               allow  Mawk allows the option to be checked against the (small) set of long options it recognizes.
    
               error  Mawk prints an error message and exits.  This is the default.
    
               ignore Mawk ignores the option.
    
               warn   Print an warning message and otherwise ignore the option.
    
             If the variable is unset, mawk prints an error message and exits.
    
          WHINY_USERS
             This is an undocumented gawk feature.  It tells mawk to sort array indices before it starts to iterate over the  elements
             of an array.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    SEE ALSO
    grep(1)

       Aho,  Kernighan and Weinberger, The AWK Programming Language, Addison-Wesley Publishing, 1988, (the AWK book), defines the lan‐
       guage, opening with a tutorial and advancing to many interesting programs that delve into issues of software design and  analy‐
       sis relevant to programming in any language.
    
       The  GAWK  Manual,  The Free Software Foundation, 1991, is a tutorial and language reference that does not attempt the depth of
       the AWK book and assumes the reader may be a novice programmer.  The section on AWK arrays is  excellent.   It  also  discusses
       POSIX requirements for AWK.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    BUGS
    mawk implements printf() and sprintf() using the C library functions, printf and sprintf, so full ANSI compatibility requires
    an ANSI C library. In practice this means the h conversion qualifier may not be available. Also mawk inherits any bugs or
    limitations of the library functions.

       Implementors of the AWK language have shown a consistent lack of imagination when naming their programs.
    
    • 1

    AUTHOR
    Mike Brennan (brennan@whidbey.com).
    Thomas E. Dickey dickey@invisible-island.net.

    Version 1.3.4 2019-12-31 MAWK(1)

  • 相关阅读:
    fast planner代码解析--topo_prm.cpp
    【SpringMVC笔记12】SpringMVC集成Thymeleaf模板引擎
    深度学习基础知识 最近邻插值法、双线性插值法、双三次插值算法
    (附源码)springboorCRM客户关系管理系统 毕业设计 316631
    【知识点】分布式系统相关名词/概念/知识点
    R语言中做VIF分析的问题探索
    【开源】使用PhenoCV-WeedCam进行更智能、更精确的杂草管理
    JavaScript - canvas - 放大镜
    数据分区设计(0)-前言
    使用PYQT5简单制作动态仪表盘
  • 原文地址:https://blog.csdn.net/kfepiza/article/details/127742962