GAWK(1)
GAWK(1) ๐ โจ
hey bestie, this is the Utility Commands manual page for gawk and we are going to get through it together, no cap
๐ 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 ...
๐จ README FIRST ๐จ
okay so before anything else, real talk: this manual page is provided as a courtesy. That's it. The actual One Source Of Truth for gawk is the Texinfo manual, which lives online in several formats at https://www.gnu.org/software/gawk/manual ๐ฆ It might also be installed in the Info subsystem on your system, so you can reach it through the info(1) command.
โ ๏ธ If the Texinfo manual and this manual page ever contradict each other, the Texinfo manual wins. Periodt. It's authoritative, this page is not.
Also, just so you know: the Info documentation, the HTML web page(s), and the PDF version of the manual all have the same content, because they're all generated from the same Texinfo source file. Sibling energy ๐
And ngl, there's a heads up: the gawk maintainer reserves the right in the future to remove this manual page from the distribution or to severely truncate the content in order to ease his maintenance burden. So enjoy it while it's here ๐
๐ 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. ๐
On top of all that, gawk provides the additional features found in the current version of Brian Kernighan's awk plus numerous GNU-specific extensions โ she's giving main character energy, fr fr.
The command line consists of:
- options to
gawkitself ๐ - the AWK program text (if it wasn't supplied via the
-for--includeoptions) - values to be made available in the
ARGCandARGVpre-defined AWK variables
๐ฆ PREFACE ๐ฆ
This manual page is intentionally as terse as possible, bestie โ she's on a diet. ๐ Full details are provided in GAWK: Effective AWK Programming, and you should look there for the full story on any specific feature. Where possible, links to the online version of the manual are provided. โจ
๐ OPTION FORMAT ๐
Gawk options may be either traditional POSIX-style one letter options, or GNU-style long options.
- POSIX options start with a single
<hotpink>-</hotpink> - long options start with
<hotpink>--</hotpink> - Long options are provided for both GNU-specific features and for POSIX-mandated 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 abbreviated, as long as the abbreviation remains unique. ๐
Additionally โ and this is lowkey iconic โ every long option has a corresponding short option, so that the option's functionality may be used from within #! executable scripts. ๐
โจ OPTIONS โจ
Gawk accepts the following options. Standard options are listed first, followed by options for gawk extensions, listed alphabetically by short option. (yes, alphabetically, she's organized like that)
-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-foptions may be used. Files read with-fare 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 theFSpredefined 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 theBEGINrule of an AWK program. ๐ซถ-b,--characters-as-bytesโ Treat all input data as single-byte characters. The--posixoption overrides this one.-c,--traditionalโ Run in compatibility mode. In compatibility mode, gawk behaves identically to Brian Kernighan'sawk; none of the GNU-specific extensions are recognized. ๐-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. The default file isawkvars.outin the current directory.-D[file],--debug[=file]โ Enable debugging of AWK programs. By default, the debugger reads commands interactively from the keyboard (standard input). The optional file argument specifies a file with a list of commands for the debugger to execute non-interactively.
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 Programming; see https://www.gnu.org/software/gawk/manual/html_node/Debugger.html#Debugger. ๐ฅ
-e program-text,--source program-textโ Use program-text as AWK program source code. Each argument supplied via-eis treated as if it begins with an implicit@namespace "awk"statement.-E file,--exec fileโ Similar to-f, however, this 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 disables 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. ๐ธ-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 theAWKPATHenvironment variable. If the initial search fails, another attempt will be made after appending the.awksuffix. 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--includeare treated as if they begin with an implicit@namespace "awk"statement. ๐-I,--traceโ Print the internal byte code names as they are executed when running the program. The trace is printed to standard error. Each "op code" is preceded by a+sign in the output.-k,--csvโ Enable CSV special processing. See Comma Separated Values, below, for more detail.-l lib,--load libโ Load a gawk extension from the shared library lib. This searches for the library using theAWKLIBPATHenvironment variable. 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 nameddl_load(). ๐ฆ-L [value],--lint[=value]โ Provide warnings about constructs that are dubious or non-portable to other AWK implementations. See https://www.gnu.org/software/gawk/manual/html_node/Options.html#Options for the list of possible values for value.-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.)
๐ NOTE: This feature is on parole. The primary gawk maintainer is no longer supporting it, although there is a member of the development team who is. If this situation changes, the feature will be removed from gawk. ๐
-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.-o[file],--pretty-print[=file]โ Output a pretty printed version of the program to file. The default file isawkprof.outin the current directory. This option implies--no-optimize. ๐-O,--optimizeโ Enable gawk's default optimizations upon the internal representation of the program. 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 isawkprof.outin the current directory. The profile contains execution counts of each statement in the program in the left margin and function call counts for each user-defined function. Gawk runs more slowly in this mode. This option implies--no-optimize. ๐ข-P,--posixโ This turns on compatibility mode, and disables a number of common extensions.-r,--re-intervalโ Enable the use of interval expressions in regular expression matching. Interval expressions are enabled by default, but this option remains for backwards compatibility.-s,--no-optimizeโ Disable gawk's default optimizations upon the internal representation of the program.-S,--sandboxโ Run gawk in sandbox mode, disabling thesystem()function, input redirection withgetline, output redirection withprintandprintf, and loading dynamic extensions. Command execution (through pipelines) is also disabled. ๐-t,--lint-oldโ Provide warnings about constructs that are not portable to the original version of UNIXawk.-V,--versionโ Print version information for this particular copy of gawk on the standard output. This is 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<hotpink>-</hotpink>.
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. ๐
For POSIX compatibility, the -W option may be used, followed by the name of a long option. โจ
๐ AWK PROGRAM EXECUTION ๐
okay bestie, so an AWK program is literally just a sequence of optional directives, pattern-action statements, and optional function definitions. It's giving โจbuild your own adventureโจ.
@include "filename"
@nsinclude "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. No cap.
In addition, lines beginning with @include may be used to include other source files into your program. This is equivalent to using the --include option.
Lines beginning with @nsinclude also include files, but with two differences. First, the namespace in the included file is not reset to the default of awk, and such files may be included multiple times.
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 options. If this variable does not exist, the default path is .:/usr/local/share/awk. (The actual directory may vary, depending 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 assigned the value val. (This happens after any BEGIN rule(s) have been run.)
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 rules 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).
๐ 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. ๐ฑ
For 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. So yeah, don't test it unless you wanna see sparks. ๐
๐ 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. However, gawk provides true arrays of arrays. Several pre-defined variables are set as a program runs; these are described as needed and summarized below.
๐ Records ๐
Normally, records are separated by newline characters. You can control how records are separated by assigning values to the built-in variable RS. See https://www.gnu.org/software/gawk/manual/html_node/Records.html for the details.
๐ธ Fields ๐ธ
As each input record is read, gawk splits the record into fields, using the value of the FS variable as the field separator. Additionally, FIELDWIDTHS and FPAT may be used to control input field splitting. See the details, starting at https://www.gnu.org/software/gawk/manual/html_node/Fields.html.
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.
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 recomputed, 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.
๐ Comma Separated Values ๐
When invoked with either the -k or the --csv option, gawk does not use regular record determination and field splitting as described above. Instead, records are terminated by unquoted newlines, and fields are separated by commas. Double-quotes may be used to enclose fields containing commas, newlines, or doubled double-quotes. See https://www.gnu.org/software/gawk/manual/html_node/Comma-Separated-Fields.html for more details.
๐ Built-in Variables ๐
Gawk's built-in variables are listed below. This list is purposely terse. For details, see https://www.gnu.org/software/gawk/manual/html_node/Built_002din-Variables.
ARGCโ The number of command line arguments.ARGINDโ The index inARGVof the current file being processed.ARGVโ Array of command line arguments. The array is indexed from0toARGC - 1.BINMODEโ On non-POSIX systems, specifies use of โbinaryโ mode for all file I/O. Seehttps://www.gnu.org/software/gawk/manual/html_node/PC-Using.htmlfor the details.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.ERRNOโ If a system error occurs either doing a redirection forgetline, during a read forgetline, or during aclose(), thenERRNOis set to a string describing the error. The value is subject to translation in non-English locales.FIELDWIDTHSโ A whitespace-separated list of field widths. When set,gawkparses the input into fields of fixed width, instead of using the value of theFSvariable 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.FILENAMEโ The name of the current input file. If no files are specified on the command line, the value ofFILENAMEis"-". However,FILENAMEis undefined inside theBEGINrule (unless set bygetline).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,gawkparses the input into fields, where the fields match the regular expression, instead of using the value ofFSas the field separator.FSโ The input field separator, a space by default. Seehttps://www.gnu.org/software/gawk/manual/html_node/Field-Separators.htmlfor the details.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 thedeletestatement with theFUNCTABarray.IGNORECASEโ Controls the case-sensitivity of all regular expression and string operations. Seehttps://www.gnu.org/software/gawk/manual/html_node/Case_002dsensitivity.htmlfor details.LINTโ Provides dynamic control of the--lintoption from within an AWK program.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,53by default.PROCINFOโ The elements of this array provide access to information about the running AWK program. Seehttps://www.gnu.org/software/gawk/manual/html_node/Auto_002dsetfor the details.ROUNDMODEโ The rounding mode to use for arbitrary precision arithmetic on numbers, by default"N"(IEEE-754 roundTiesToEven mode). Seehttps://www.gnu.org/software/gawk/manual/html_node/Setting-the-rounding-modefor the details.RSโ The input record separator, by default a newline.RTโ The record terminator. Gawk setsRTto the input text that matched the character or regular expression specified byRS.RSTARTโ The index of the first character matched bymatch();0if no match.RLENGTHโ The length of the string matched bymatch();-1if 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. You may not use thedeletestatement with theSYMTABarray, nor assign to elements with an index that is not a variable name.TEXTDOMAINโ the text domain of ur AWK program ๐ฌ it's what gets used to go find the localized translations for the program's strings.
โจ Arrays โจ
okay so arrays?? absolute icons. u subscript them with an expression tucked between square brackets ([ and ]) ๐
if that expression is an expression list (expr, expr ...) then the array subscript becomes a string made by concatenating the (string) value of every expression, with the value of the SUBSEP variable separating them. this whole trick is how u simulate multiply dimensioned arrays. like:
i = "A"; j = "B"; k = "C"
x[i, j, k] = "hello, world\n"
that assigns the string "hello, world\n" to the element of the array x indexed by the string "A\034B\034C". and literally all arrays in AWK are associative, i.e. indexed by string values. no cap ๐
the special in operator can test whether 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 can 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. important, bestie ๐
u can delete an element from an array with the delete statement. the delete statement can also nuke the entire contents of an array, just by naming the array without a subscript ๐๏ธ
gawk supports true multidimensional arrays โ it does not require them to be "rectangular" like in C or C++. see https://www.gnu.org/software/gawk/manual/html_node/Arrays for the details.
๐ Namespaces ๐
Gawk gives u a simple namespace facility to help work around the fact that all variables in AWK are global ๐ญ
a qualified name consists of two simple identifiers joined by a double colon (::). the left-hand identifier is the namespace, the right-hand identifier is the variable within it. all simple (non-qualified) names are considered to be in the "current" namespace, and the default namespace is awk. however โ plot twist โ simple identifiers consisting solely of uppercase letters are forced into the awk namespace, even if the current namespace is different. periodt ๐
u 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 deets, see https://www.gnu.org/software/gawk/manual/html_node/Namespaces.html#Namespaces.
๐ Variable Typing And Conversion ๐
variables and fields may be (floating point) numbers, or strings, or both. they may also be regular expressions. how a variable's value gets interpreted depends on its context: use it in a numeric expression and it's treated as a number; use it as a string and it's 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. little life hacks ๐
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 done using strtod(3). a number gets 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. but โ even though all numbers in AWK are floating-point โ integral values are always converted as integers. slay โจ
Gawk performs comparisons like this: if two variables are numeric, they're compared numerically. if one value is numeric and the other has a string value that's a "numeric string," the comparison is also done numerically. otherwise, the numeric value gets converted to a string and a string comparison happens. two strings are compared, of course, as strings ๐ธ
note that string constants, like"57", are not numeric strings โ they're string constants. the whole idea of "numeric string" only applies to fields,getlineinput,FILENAME,ARGVelements,ENVIRONelements and the elements of an array created bysplit()orpatsplit()that are numeric strings. the basic idea is that user input โ and only user input โ that looks numeric should be treated that way. iykyk ๐
๐ Octal and Hexadecimal Constants ๐
u may use C-style octal and hexadecimal constants in ur AWK program source code ๐ for example, the octal value 011 equals decimal 9, and the hexadecimal value 0x11 equals decimal 17. math is math ๐ง
โญ String Constants โญ
string constants in AWK are sequences of characters enclosed between double quotes (like "value"). inside strings, certain escape sequences are recognized, just like in C. see https://www.gnu.org/software/gawk/manual/html_node/Escape-Sequences for the details โจ
๐ฆ Regexp Constants ๐ฆ
a regular expression constant is a sequence of characters enclosed between forward slashes (like /value/) ๐ฅ
the escape sequences described in the manual 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. iconic behavior tbh ๐
๐ 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 action 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, that's not the case for lines ending in a comma, {, ?, :, &&, or ||. lines ending in do or else also have their statements automatically continued onto the following line. in other cases, a line can be continued by ending it with a \, in which case the newline is ignored. but a \ after a # is not special ๐
multiple statements may be put on one line by separating them with a ;. this applies both to the statements within the action part of a pattern-action pair (the usual case) and to the pattern-action statements themselves ๐
๐ธ 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're 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 executed). BEGIN and END patterns cannot be combined with other patterns in pattern expressions. and BEGIN and END patterns cannot have missing action parts. no exceptions bestie ๐ซ
BEGINFILE and ENDFILE are additional special patterns whose actions are executed before reading the first record of each command-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's some problem with the file and the code should use nextfile to skip it. if that's 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 expression. regular expressions are essentially the same as those in egrep(1). see https://www.gnu.org/software/gawk/manual/html_node/Regexp.html for the details on regular expressions โจ
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 evaluation, 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's 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 ๐
๐ 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 after those in C. classic ๐
๐ Operators ๐
the operators in AWK, in order of decreasing precedence, are:
(...)โ grouping$โ field reference++ --โ increment and decrement, both prefix and postfix^โ exponentiation+ - !โ unary plus, unary minus, and logical negation* / %โ multiplication, division, and modulus+ -โ addition and subtractionspaceโ string concatenation||&โ piped I/O forgetline,print, andprintf< > <= >= == !=โ the regular relational operators~ !~โ regular expression match, negated matchinโ array membership&&โ logical AND||โ logical OR?:โ the C conditional expression. this has the formexpr1 ? expr2 : expr3. ifexpr1is true, the value of the expression isexpr2, otherwise it'sexpr3. only one ofexpr2andexpr3is evaluated โจ= += -= *= /= %= ^=โ assignment. both absolute assignment (var = value) and operator-assignment (the other forms) are supported ๐
๐ 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 ]
}
okay bestie we're entering the I/O era and it's giving everything ๐
๐ I/O Statements ๐
the input/output statements are, in all their glory:
close(file [, how])โ closes an open file, pipe, or coprocess. that optionalhow? only for when you're closing one end of a two-way pipe to a coprocess. it has to be a string value, and it's either"to"or"from". no other options, she's picky ๐getlineโ sets$0from the next input record; setsNF,NR,FNR,RT. ๐getline <fileโ sets$0from the next record of file; setsNF,RT.getline varโ sets var from the next input record; setsNR,FNR,RT.getline var <fileโ sets var from the next record of file; setsRT.command | getline [var]โ runs command, piping the output either into$0or var, as above, and setsRT.command |& getline [var]โ runs command as a coprocess, piping the output either into$0or var, as above, and setsRT. (the command can also be a socket, bestie. see the subsection Special File Names, below. ๐ง)fflush([file])โ flushes any buffers associated with the open output file or pipe file. if file is missing, or if it's the null string, then it flushes all open output files and pipes. spring cleaning fr fr โจnextโ stops processing the current input record. reads the next input record and starts processing over with the first pattern in the AWK program. upon reaching the end of the input data, execute anyENDrule(s).nextfileโ stops processing the current input file. the next input record read comes from the next input file. updatesFILENAMEandARGIND, resetsFNRto1, and starts processing over with the first pattern in the AWK program. upon reaching the end of the input data, execute anyENDFILEandENDrule(s).printโ prints the current record. the output record is terminated with the value ofORS.print expr-listโ prints expressions. each expression is separated by the value ofOFS. the output record is terminated with the value ofORS.print expr-list >fileโ prints expressions on file. each expression is separated by the value ofOFS. the output record is terminated with the value ofORS.printf fmt, expr-listโ format and print.printf fmt, expr-list >fileโ format and print on file.system(cmd-line)โ executes the command cmd-line, and returns the exit status. (this may not be available on non-POSIX systems, heads up ๐ญ) seehttps://www.gnu.org/software/gawk/manual/html_node/I_002fO-Functions.html#I_002fO-Functionsfor the full details on the exit status.
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 function 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. iconic behavior tbh ๐ซถ
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 togetline, or fromprintfwithin a loop, you must useclose()to create new instances of the command or socket. AWK does not automatically close pipes, sockets, or coprocesses when they return EOF. no cap, this one bites people ๐
The AWK versions of the printf statement and sprintf() function are similar to those of C. for details, see https://www.gnu.org/software/gawk/manual/html_node/Printf.html.
๐ฆ 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, bestie ๐). 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.
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. UDP support is obsolete and will be removed in the future. ๐ญ rest in peace girl
๐ข Numeric Functions ๐ข
AWK has the following built-in arithmetic functions, and they're all lowkey serving:
atan2(y, x)โ returns the arctangent ofy/xin radians.cos(expr)โ returns the cosine of expr, which is in radians.exp(expr)โ the exponential function.int(expr)โ truncates to integer.log(expr)โ the natural logarithm function.rand()โ returns a random number N, between zero and one, such that0 โค N < 1.sin(expr)โ returns the sine of expr, which is in radians.sqrt(expr)โ returns the square root of expr.srand([expr])โ uses expr as the new seed for the random number generator. if no expr is provided, use the time of day. returns the previous seed for the random number generator. ๐ฒ
๐ธ String Functions ๐ธ
Gawk has the following built-in string functions; the details are provided in https://www.gnu.org/software/gawk/manual/html_node/String-Functions. these ones are the moment, fr fr ๐
asort(s [, d [, how] ])โ returns the number of elements in the source array s. sorts the contents of s usinggawk's normal rules for comparing values, and replaces the indices of the sorted values s with sequential integers starting with1. 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 described inhttps://www.gnu.org/software/gawk/manual/html_node/String-Functions.html#String-Functions. s and d are allowed to be the same array; this only makes sense when supplying the third argument as well. ๐asorti(s [, d [, how] ])โ returns the number of elements in the source array s. the behavior is the same as that ofasort(), except that the array indices are used for sorting, not the array values. when done, the array is indexed numerically, and the values are those of the original indices. the original values are lost ๐ญ so provide a second array if you wish to preserve the original. the purpose of the optional string how is the same as forasort(). here too, s and d are allowed to be the same array; this only makes sense when supplying the third argument as well.gensub(r, s, h [, t])โ searches the target string t for matches of the regular expression r. if h is a string beginning withgorG, 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$0instead. within the replacement text s, the sequence\n, where n is a digit from1to9, may be used to indicate just the text that matched the n'th parenthesized subexpression. the sequence\0represents the entire matched text, as does the character&. unlikesub()andgsub(), the modified string is returned as the result of the function, and the original target string is not changed. she's not like other girls ๐gsub(r, s [, t])โ bestie, for every single substring matching the regexrin the stringt, swap in the strings, and hand back the number of substitutions it made. Didn't give it at? Then it works on$0, obvi. And here's the tea: an&in the replacement text gets replaced with the text that was actually matched. Want a literal&? Use\&. (You gotta type it as"\\&"โ the full rules for ampersands and backslashes in the replacement text ofsub(),gsub(), andgensub()live athttps://www.gnu.org/software/gawk/manual/html_node/Gory-Details.html#Gory-Detailsif you wanna go full lore mode.)index(s, t)โ returns the index of the stringtinside the strings, or zero iftisn't in there at all. (Which, lowkey, means character indices start at one. iconic behaviour.)length([s])โ returns the length of the strings, or the length of$0if you didn't passs. Give it an array instead andlength()returns the number of elements in that array. versatile queen.match(s, r [, a])โ returns the position inswhere the regexrshows up, or zero ifrisn't there, and sets the values ofRSTARTandRLENGTH. Heads up: the argument order is the same as for the~operator โstr ~ re. How the arrayagets filled when you supply it is described athttps://www.gnu.org/software/gawk/manual/html_node/String-Functions.html#String-Functions.patsplit(s, a [, r [, seps] ])โ splits the stringsinto the arrayaand the separators arraysepson the regexr, and returns the number of fields. The element values are the portions ofsthat matchedr.seps[i]holds the possibly null separator that appeared aftera[i], andseps[0]holds the possibly null leading separator. OmitrandFPATgets used instead. Both arraysaandsepsget cleared first, no leftovers. Splitting behaves identically to field splitting withFPAT. ๐split(s, a [, r [, seps] ])โ splits the stringsinto the arrayaand the separators arraysepson the regexr, and returns the number of fields. OmitrandFSgets used instead. Arraysaandsepsare cleared first.seps[i]is the field separator matched byrbetweena[i]anda[i+1]. Splitting behaves identically to field splitting.sprintf(fmt, expr-list)โ printsexpr-listaccording tofmt, and returns the resulting string. it's giving printf but make it a return value โจstrtonum(str)โ peeps atstrand returns its numeric value. Starts with a leading0? Treated as octal. Starts with a leading0xor0X? Treated as hexadecimal. Otherwise? Assume decimal, babe.sub(r, s [, t])โ literally just likegsub(), except it only replaces the first matching substring. Returns either zero or one.substr(s, i [, n])โ returns the at mostn-character substring ofsstarting ati. Skipnand you get the rest ofs.tolower(str)โ returns a copy of the stringstrwith all the uppercase characters translated to their corresponding lowercase counterparts. Non-alphabetic characters stay exactly as they are. no notes.toupper(str)โ returns a copy of the stringstrwith all the lowercase characters translated to their corresponding uppercase counterparts. Non-alphabetic characters are left unchanged.
Gawk is multibyte aware. Which means index(), length(), substr() and match() all work in terms of characters, not bytes. we love an inclusive king ๐ซถ
โฐ Time Functions โฐ
Gawk hands you the following functions for grabbing time stamps and formatting them. The details live at https://www.gnu.org/software/gawk/manual/html_node/Time-Functions.
mktime(datespec [, utc-flag])โ turnsdatespecinto a time stamp of the same form thatsystime()returns, and gives it back to you. Ifutc-flagis present and is non-zero or non-null, the time is assumed to be in the UTC time zone; otherwise it's assumed to be in the local time zone. Ifdatespecdoesn't have enough elements, or the resulting time is out of range,mktime()returns-1. The deets ondatespecare athttps://www.gnu.org/software/gawk/manual/html_node/Time-Functions.html#Time-Functions.strftime([format [, timestamp[, utc-flag]]])โ formatstimestampaccording to the spec informat. Ifutc-flagis present and is non-zero or non-null, the result comes out in UTC; otherwise it's in local time. Thetimestampshould be the same form thatsystime()returns. Notimestamp? Then it uses the current time of day. Noformat? Then it uses a default format equivalent to the output ofdate(1)โ and that default format is available to you inPROCINFO["strftime"]. The format conversions that are guaranteed to be available are the ones in the spec for thestrftime()function in ISO C.systime()โ returns the current time of day as the number of seconds since the Epoch (1970-01-01 00:00:00 UTCon POSIX systems). โญ
๐ข 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.
โ ๏ธ Bestie, listen: passing negative operands to any of these functions causes a fatal error. Do not do it. fr fr.
The functions are:
and(v1, v2 [, ...])โ returns the bitwise AND of the values in the argument list. There must be at least two.compl(val)โ returns the bitwise complement ofval.lshift(val, count)โ returns the value ofval, shifted left bycountbits.or(v1, v2 [, ...])โ returns the bitwise OR of the values in the argument list. There must be at least two.rshift(val, count)โ returns the value ofval, shifted right bycountbits.xor(v1, v2 [, ...])โ returns the bitwise XOR of the values in the argument list. There must be at least two.
๐ท๏ธ Type Functions ๐ท๏ธ
The following functions provide type related info about their arguments. it's giving detective energy ๐ต๏ธ
isarray(x)โ returns true ifxis an array, false otherwise.typeof(x)โ returns a string telling you the type ofx. That string will be one of"array","number","number|bool","regexp","string","strnum","unassigned", or"untyped".
๐ Internationalization Functions ๐
The following functions may be used from within your AWK program for translating strings at run-time. For full details, see https://www.gnu.org/software/gawk/manual/html_node/I18N-Functions.html#I18N-Functions.
bindtextdomain(directory [, domain])โ specifies the directory where gawk looks for the.gmofiles, in case they will not or cannot be placed in the "standard" locations. It returns the directory wheredomainis "bound." The default domain is the value ofTEXTDOMAIN. Ifdirectoryis the null string (""), thenbindtextdomain()returns the current binding for the given domain.dcgettext(string [, domain [, category]])โ returns the translation ofstringin text domaindomainfor locale categorycategory. The default value fordomainis the current value ofTEXTDOMAIN. The default value forcategoryis"LC_MESSAGES".dcngettext(string1, string2, number [, domain [, category]])โ returns the plural form used fornumberof the translation ofstring1andstring2in text domaindomainfor locale categorycategory. The default value fordomainis the current value ofTEXTDOMAIN. The default value forcategoryis"LC_MESSAGES".
โ Boolean Valued Functions โ
You can create special Boolean-typed values; the manual has the whole story on how they work and why they even exist. ๐ฆ
mkbool(expression)โ based on the boolean value ofexpression, returns either a true value or a false value. True values have numeric value one. False values have numeric value zero.
๐ USER-DEFINED FUNCTIONS ๐
okay bestie, you can literally write your own functions in AWK. here's the fit:
function name(parameter list) { statements }
they run whenever something calls them from inside an expression โ in a pattern or an action, both work. the actual params you hand over in the call get used to instantiate the formal params declared in the function. and here's the tea: arrays are passed by reference, everything else is passed by value. periodt.
local variables? you just declare them as extra parameters in the param list ๐ซถ the convention is to separate the local ones from the real ones with extra spaces. like so:
function f(p, q, a, b) # a and b are local
{
...
}
/abc/ { ... ; f(1, 2) ; ... }
the left paren in a function call has to immediately follow the function name โ no whitespace in between, not even one space ๐ and that restriction does not apply to the built-in functions listed above, they're chill like that.
functions can call each other, and yes they can be recursive (iconic behavior honestly). function parameters used as local variables get initialized to the null string and the number zero every time the function is invoked. ๐
use return expr to send a value back. the return value is undefined if you don't provide one, or if the function returns by "falling off" the end. yeah. undefined. don't do that.
functions can also be called indirectly ๐ assign the name of the function you want, as a string, to a variable. then use that variable like it is the function name, prefixed with an @ sign, like so:
function myfunc()
{
print "myfunc called"
...
}
{ ...
the_func = "myfunc"
@the_func() # call through the_func to myfunc
...
}
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 ๐ so like, don't.
๐ DYNAMICALLY LOADING NEW FUNCTIONS ๐
you can dynamically add new functions written in C or C++ into the running gawk interpreter with the @load statement โจ the full details are beyond the scope of this manual page, so go read:
https://www.gnu.org/software/gawk/manual/html_node/Dynamic-Extensions.html#Dynamic-Extensions
๐จ SIGNALS ๐จ
the gawk profiler accepts two signals:
SIGUSR1โ makes it dump a profile and function call stack to the profile file, which is eitherawkprof.out, or whatever file was named with the--profileoption. then it justโฆ keeps running. main character energy.SIGHUPโ makes gawk 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, you can mark strings in the AWK program as requiring translation into the local natural language ๐ฆ you mark them 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 ๐ฅ see:
https://www.gnu.org/software/gawk/manual/html_node/Internationalization.html#Internationalization
for the steps involved in producing and running a localizable AWK program.
โจ GNU EXTENSIONS โจ
gawk has a too-large number of extensions to POSIX awk (not me saying it, the manpage said it ๐ญ). they're described at:
https://www.gnu.org/software/gawk/manual/html_node/POSIX_002fGNU.html
all the extensions can be disabled by invoking gawk with the --traditional or --posix options. your choice bestie ๐
๐ฑ ENVIRONMENT VARIABLES ๐ฑ
AWKPATHโ can be used to provide a list of directories that gawk searches when looking for files named via the-f,--file,-iand--includeoptions, and the@includeand@nsincludedirectives. if the initial search fails, the path is searched again after appending.awkto the filename ๐AWKLIBPATHโ can be used to provide a list of directories that gawk searches when looking for files named via the-land--loadoptions.GAWK_PERSIST_FILEโ if present, specifies a file to use as the backing store for persistent memory ๐พ see GAWK: Effective AWK Programming for the details.GAWK_READ_TIMEOUTโ can be used to specify a timeout in milliseconds for reading input from a terminal, pipe or two-way communication including sockets โฑ๏ธGAWK_SOCK_RETRIESโ for connection to a remote host via socket, this controls the number of retries ๐GAWK_MSEC_SLEEPโ the interval between those retries. the interval is in milliseconds. on systems that do not supportusleep(3), the value is rounded up to an integral number of seconds.POSIXLY_CORRECTโ if it exists in the environment, then gawk behaves exactly as if--posixhad been specified on the command line. if--linthas been specified, gawk issues a warning message to this effect. โ ๏ธ
๐ช EXIT STATUS ๐ช
- if the
exitstatement 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 usually 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 toEXIT_FAILURE.
๐ท๏ธ VERSION INFORMATION ๐ท๏ธ
this man page documents gawk, version 5.4.
๐ AUTHORS ๐
the original version of UNIX awk was designed and implemented by Alfred Aho, Peter Weinberger, and Brian Kernighan of Bell Laboratories. Ozan Yigit is the current maintainer. Brian Kernighan occasionally dabbles in its development. (dabbles. he said dabbles. icon.)
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 supported.
๐ BUG REPORTS AND QUESTIONS ๐
if you find a bug in gawk, please use the gawkbug(1) program to report it.
full instructions for reporting a bug are provided in:
https://www.gnu.org/software/gawk/manual/html_node/Bugs.html
please carefully read and follow the instructions given there. this will make bug reporting and resolution much easier for everyone involved. really. ๐
on the other hand, if you have a question as to how to accomplish a particular task using awk or gawk, send an email to help-gawk@gnu.org with your request for help ๐
๐ BUGS ๐
- the
-Foption is not necessary given the command line variable assignment feature; it remains only for backwards compatibility. - this manual page is too long; gawk has too many features. (no notes, it's true ๐ญ)
๐ SEE ALSO ๐
egrep(1), sed(1), gawkbug(1), printf(3), and strftime(3).
The AWK Programming Language, second edition, Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger, Addison-Wesley, 2023. ISBN 9-780138-269722.
GAWK: Effective AWK Programming, Edition 5.4, 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
๐ธ 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") }'
๐ 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, 2021, 2022, 2023, 2024, 2025, 2026 Free Software Foundation, Inc.
permission is granted to make and distribute verbatim copies of this manual page provided the copyright notice and this permission 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.
that's the whole page bestie, you made it to the end ๐๐
and that's a wrap from the Free Software Foundation โ page GAWK(1), dated March 2 2026. slay. go write some awk. ๐ฆโจ
๐ฆ where this page comes from
- arch rolling: gawk 5.4.1-1 ยท GPL-3.0-or-later
- nixos 26.05: gawk-interactive 5.4.1
- nixpkgs unstable: gawk 5.4.1
- nixpkgs unstable: gawk-interactive 5.4.1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms