AWK(1) | User Commands | AWK(1) |
awk - pattern scanning and processing language
/usr/bin/awk [-F ERE] [-v assignment] 'program' | -f progfile...
[argument]...
/usr/bin/nawk [-F ERE] [-v assignment] 'program' | -f progfile...
[argument]...
/usr/xpg4/bin/awk [-F ERE] [-v assignment]... 'program' | -f progfile...
[argument]...
NOTE: The nawk command is now the system default awk for illumos.
The /usr/bin/awk and /usr/xpg4/bin/awk utilities execute programs written in the awk programming language, which is specialized for textual data manipulation. A awk program is a sequence of patterns and corresponding actions. The string specifying program must be enclosed in single quotes (') to protect it from interpretation by the shell. The sequence of pattern - action statements can be specified in the command line as program or in one, or more, file(s) specified by the -fprogfile option. When input is read that matches a pattern, the action associated with the pattern is performed.
Input is interpreted as a sequence of records. By default, a record is a line, but this can be changed by using the RS built-in variable. Each record of input is matched to each pattern in the program. For each pattern matched, the associated action is executed.
The awk utility interprets each input record as a sequence of fields where, by default, a field is a string of non-blank characters. This default white-space field delimiter (blanks and/or tabs) can be changed by using the FS built-in variable or the -FERE option. The awk utility denotes the first field in a record $1, the second $2, and so forth. The symbol $0 refers to the entire record; setting any other field causes the reevaluation of $0. Assigning to $0 resets the values of all fields and the NF built-in variable.
The following options are supported:
-F ERE
-f progfile
-v assignment
-safe
The following operands are supported:
program
argument
file
assignment
Input files to the awk program from any of the following sources:
must be text files. Whether the variable RS is set to a value other than a newline character or not, for these files, implementations support records terminated with the specified separator up to {LINE_MAX} bytes and can support longer records.
If -f progfile is specified, the files named by each of the progfile option-arguments must be text files containing an awk program.
The standard input are used only if no file operands are specified, or if a file operand is −.
A awk program is composed of pairs of the form:
pattern { action }
Either the pattern or the action (including the enclosing brace characters) can be omitted. Pattern-action statements are separated by a semicolon or by a newline.
A missing pattern matches any record of input, and a missing action is equivalent to an action that writes the matched record of input to standard output.
Execution of the awk program starts by first executing the actions associated with all BEGIN patterns in the order they occur in the program. Then each file operand (or standard input if no files were specified) is processed by reading data from the file until a record separator is seen (a newline character by default), splitting the current record into fields using the current value of FS, evaluating each pattern in the program in the order of occurrence, and executing the action associated with each pattern that matches the current record. The action for a matching pattern is executed before evaluating subsequent patterns. Last, the actions associated with all END patterns is executed in the order they occur in the program.
Expressions describe computations used in patterns and actions. In the following table, valid expression operations are given in groups from highest precedence first to lowest precedence last, with equal-precedence operators grouped between horizontal lines. In expression evaluation, where the grammar is formally ambiguous, higher precedence operators are evaluated before lower precedence operators. In this table expr, expr1, expr2, and expr3 represent any expression, while lvalue represents any entity that can be assigned to (that is, on the left side of an assignment operator).
Syntax | Name | Type of Result | Associativity |
( expr ) | Grouping | type of expr | n/a |
$expr | Field reference | string | n/a |
++ lvalue | Pre-increment | numeric | n/a |
−− lvalue | Pre-decrement | numeric | n/a |
lvalue ++ | Post-increment | numeric | n/a |
lvalue −− | Post-decrement | numeric | n/a |
expr ^ expr | Exponentiation | numeric | right |
! expr | Logical not | numeric | n/a |
+ expr | Unary plus | numeric | n/a |
− expr | Unary minus | numeric | n/a |
expr * expr | Multiplication | numeric | left |
expr / expr | Division | numeric | left |
expr % expr | Modulus | numeric | left |
expr + expr | Addition | numeric | left |
expr − expr | Subtraction | numeric | left |
expr expr | String concatenation | string | left |
expr < expr | Less than | numeric | none |
expr <= expr | Less than or equal to | numeric | none |
expr != expr | Not equal to | numeric | none |
expr == expr | Equal to | numeric | none |
expr > expr | Greater than | numeric | none |
expr >= expr | Greater than or equal to | numeric | none |
expr ~ expr | ERE match | numeric | none |
expr !~ expr | ERE non-match | numeric | none |
expr in array | Array membership | numeric | left |
( index ) in | Multi-dimension array | numeric | left |
array | membership | ||
expr && expr | Logical AND | numeric | left |
expr || expr | Logical OR | numeric | left |
expr1 ? expr2 | Conditional expression | type of selected | right |
: expr3 | expr2 or expr3 | ||
lvalue ^= expr | Exponentiation | numeric | right |
assignment | |||
lvalue %= expr | Modulus assignment | numeric | right |
lvalue *= expr | Multiplication | numeric | right |
assignment | |||
lvalue /= expr | Division assignment | numeric | right |
lvalue += expr | Addition assignment | numeric | right |
lvalue −= expr | Subtraction assignment | numeric | right |
lvalue = expr | Assignment | type of expr | right |
Each expression has either a string value, a numeric value or both. Except as stated for specific contexts, the value of an expression is implicitly converted to the type needed for the context in which it is used. A string value is converted to a numeric value by the equivalent of the following calls:
setlocale(LC_NUMERIC, ""); numeric_value = atof(string_value);
A numeric value that is exactly equal to the value of an integer is converted to a string by the equivalent of a call to the sprintf function with the string %d as the fmt argument and the numeric value being converted as the first and only expr argument. Any other numeric value is converted to a string by the equivalent of a call to the sprintf function with the value of the variable CONVFMT as the fmt argument and the numeric value being converted as the first and only expr argument.
A string value is considered to be a numeric string in the following case:
If a − character is ignored in the above steps, the numeric value of the numeric string is the negation of the numeric value of the recognized NUMBER token. Otherwise the numeric value of the numeric string is the numeric value of the recognized NUMBER token. Whether or not a string is a numeric string is relevant only in contexts where that term is used in this section.
When an expression is used in a Boolean context, if it has a numeric value, a value of zero is treated as false and any other value is treated as true. Otherwise, a string value of the null string is treated as false and any other value is treated as true. A Boolean context is one of the following:
The awk language supplies arrays that are used for storing numbers or strings. Arrays need not be declared. They are initially empty, and their sizes changes dynamically. The subscripts, or element identifiers, are strings, providing a type of associative array capability. An array name followed by a subscript within square brackets can be used as an lvalue and as an expression, as described in the grammar. Unsubscripted array names are used in only the following contexts:
A valid array index consists of one or more comma-separated expressions, similar to the way in which multi-dimensional arrays are indexed in some programming languages. Because awk arrays are really one-dimensional, such a comma-separated list is converted to a single string by concatenating the string values of the separate expressions, each separated from the other by the value of the SUBSEP variable.
Thus, the following two index operations are equivalent:
var[expr1, expr2, ... exprn] var[expr1 SUBSEP expr2 SUBSEP ... SUBSEP exprn]
A multi-dimensioned index used with the in operator must be put in parentheses. The in operator, which tests for the existence of a particular array element, does not create the element if it does not exist. Any other reference to a non-existent array element automatically creates it.
Variables can be used in an awk program by referencing them. With the exception of function parameters, they are not explicitly declared. Uninitialized scalar variables and array elements have both a numeric value of zero and a string value of the empty string.
Field variables are designated by a $ followed by a number or numerical expression. The effect of the field number expression evaluating to anything other than a non-negative integer is unspecified. Uninitialized variables or string values need not be converted to numeric values in this context. New field variables are created by assigning a value to them. References to non-existent fields (that is, fields after $NF) produce the null string. However, assigning to a non-existent field (for example, $(NF+2) = 5) increases the value of NF, create any intervening fields with the null string as their values and cause the value of $0 to be recomputed, with the fields being separated by the value of OFS. Each field variable has a string value when created. If the string, with any occurrence of the decimal-point character from the current locale changed to a period character, is considered a numeric string (see Expressions in awk above), the field variable also has the numeric value of the numeric string.
awk sets the following special variables that are supported by both /usr/bin/awk and /usr/xpg4/bin/awk:
ARGC
ARGV
The arguments in ARGV can be modified or added to; ARGC can be altered. As each input file ends, awk treats the next non-null element of ARGV, up to the current value of ARGC−1, inclusive, as the name of the next input file. Setting an element of ARGV to null means that it is not treated as an input file. The name − indicates the standard input. If an argument matches the format of an assignment operand, this argument is treated as an assignment rather than a file argument.
CONVFMT
ENVIRON
In all cases where awk behavior is affected by environment variables (including the environment of any commands that awk executes via the system function or via pipeline redirections with the print statement, the printf statement, or the getline function), the environment used is the environment at the time awk began executing.
FILENAME
FNR
FS
NF
NR
OFMT
OFS
ORS
RLENGTH
RS
RSTART
SUBSEP
The following variable is supported for /usr/bin/awk only:
RT
The awk utility makes use of the extended regular expression notation (see regex(7)) except that it allows the use of C-language conventions to escape special characters within the EREs, namely \\, \a, \b, \f, \n, \r, \t, \v, and those specified in the following table. These escape sequences are recognized both inside and outside bracket expressions. Note that records need not be separated by newline characters and string constants can contain newline characters, so even the \n sequence is valid in awk EREs. Using a slash character within the regular expression requires escaping as shown in the table below:
Escape Sequence | Description | Meaning |
\" | Backslash quotation-mark | Quotation-mark character |
\/ | Backslash slash | Slash character |
\ddd | A backslash character followed by the longest sequence of one, two, or three octal-digit characters (01234567). If all of the digits are 0, (that is, representation of the NULL character), the behavior is undefined. | The character encoded by the one-, two- or three-digit octal integer. Multi-byte characters require multiple, concatenated escape sequences, including the leading \ for each byte. |
\c | A backslash character followed by any character not described in this table or special characters (\\, \a, \b, \f, \n, \r, \t, \v). | Undefined |
A regular expression can be matched against a specific field or string by using one of the two regular expression matching operators, ~ and !~. These operators interpret their right-hand operand as a regular expression and their left-hand operand as a string. If the regular expression matches the string, the ~ expression evaluates to the value 1, and the !~ expression evaluates to the value 0. If the regular expression does not match the string, the ~ expression evaluates to the value 0, and the !~ expression evaluates to the value 1. If the right-hand operand is any expression other than the lexical token ERE, the string value of the expression is interpreted as an extended regular expression, including the escape conventions described above. Notice that these same escape conventions also are applied in the determining the value of a string literal (the lexical token STRING), and is applied a second time when a string literal is used in this context.
When an ERE token appears as an expression in any context other than as the right-hand of the ~ or !~ operator or as one of the built-in function arguments described below, the value of the resulting expression is the equivalent of:
$0 ~ /ere/
The ere argument to the gsub, match, sub functions, and the fs argument to the split function (see String Functions) is interpreted as extended regular expressions. These can be either ERE tokens or arbitrary expressions, and are interpreted in the same manner as the right-hand side of the ~ or !~ operator.
An extended regular expression can be used to separate fields by using the -F ERE option or by assigning a string containing the expression to the built-in variable FS. The default value of the FS variable is a single space character. The following describes FS behavior:
Except in the gsub, match, split, and sub built-in functions, regular expression matching is based on input records. That is, record separator characters (the first character of the value of the variable RS, a newline character by default) cannot be embedded in the expression, and no expression matches the record separator character. If the record separator is not a newline character, newline characters embedded in the expression can be matched. In those four built-in functions, regular expression matching are based on text strings. So, any character (including the newline character and the record separator) can be embedded in the pattern and an appropriate pattern matches any character. However, in all awk regular expression matching, the use of one or more NULL characters in the pattern, input record or text string produces undefined results.
A pattern is any valid expression, a range specified by two expressions separated by comma, or one of the two special patterns BEGIN or END.
The awk utility recognizes two special patterns, BEGIN and END. Each BEGIN pattern is matched once and its associated action executed before the first record of input is read (except possibly by use of the getline function in a prior BEGIN action) and before command line assignment is done. Each END pattern is matched once and its associated action executed after the last record of input has been read. These two patterns have associated actions.
BEGIN and END do not combine with other patterns. Multiple BEGIN and END patterns are allowed. The actions associated with the BEGIN patterns are executed in the order specified in the program, as are the END actions. An END pattern can precede a BEGIN pattern in a program.
If an awk program consists of only actions with the pattern BEGIN, and the BEGIN action contains no getline function, awk exits without reading its input when the last statement in the last BEGIN action is executed. If an awk program consists of only actions with the pattern END or only actions with the patterns BEGIN and END, the input is read before the statements in the END actions are executed.
An expression pattern is evaluated as if it were an expression in a Boolean context. If the result is true, the pattern is considered to match, and the associated action (if any) is executed. If the result is false, the action is not executed.
A pattern range consists of two expressions separated by a comma. In this case, the action is performed for all records between a match of the first expression and the following match of the second expression, inclusive. At this point, the pattern range can be repeated starting at input records subsequent to the end of the matched range.
An action is a sequence of statements. A statement can be one of the following:
if ( expression ) statement [ else statement ] while ( expression ) statement do statement while ( expression ) for ( expression ; expression ; expression ) statement for ( var in array ) statement delete array[subscript] #delete an array element delete array #delete all elements within an array break continue { [ statement ] ... } expression # commonly variable = expression print [ expression-list ] [ >expression ] printf format [ ,expression-list ] [ >expression ] next # skip remaining patterns on this input line nextfile # skip remaining patterns on this input file exit [expr] # skip the rest of the input; exit status is expr return [expr]
Any single statement can be replaced by a statement list enclosed in braces. The statements are terminated by newline characters or semicolons, and are executed sequentially in the order that they appear.
The next statement causes all further processing of the current input record to be abandoned. The behavior is undefined if a next statement appears or is invoked in a BEGIN or END action.
The nextfile statement is similar to next, but also skips all other records in the current file, and moves on to processing the next input file if available (or exits the program if there are none). (Note that this keyword is not supported by /usr/xpg4/bin/awk.)
The exit statement invokes all END actions in the order in which they occur in the program source and then terminate the program without reading further input. An exit statement inside an END action terminates the program without further execution of END actions. If an expression is specified in an exit statement, its numeric value is the exit status of awk, unless subsequent errors are encountered or a subsequent exit statement with an expression is executed.
Both print and printf statements write to standard output by default. The output is written to the location specified by output_redirection if one is supplied, as follows:
> expression>> expression| expression
In all cases, the expression is evaluated to produce a string that is used as a full pathname to write into (for > or >>) or as a command to be executed (for |). Using the first two forms, if the file of that name is not currently open, it is opened, creating it if necessary and using the first form, truncating the file. The output then is appended to the file. As long as the file remains open, subsequent calls in which expression evaluates to the same string value simply appends output to the file. The file remains open until the close function, which is called with an expression that evaluates to the same string value.
The third form writes output onto a stream piped to the input of a command. The stream is created if no stream is currently open with the value of expression as its command name. The stream created is equivalent to one created by a call to the popen(3C) function with the value of expression as the command argument and a value of w as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value writes output to the existing stream. The stream remains open until the close function is called with an expression that evaluates to the same string value. At that time, the stream is closed as if by a call to the pclose function.
These output statements take a comma-separated list of expression s referred in the grammar by the non-terminal symbols expr_list, print_expr_list or print_expr_list_opt. This list is referred to here as the expression list, and each member is referred to as an expression argument.
The print statement writes the value of each expression argument onto the indicated output stream separated by the current output field separator (see variable OFS above), and terminated by the output record separator (see variable ORS above). All expression arguments is taken as strings, being converted if necessary; with the exception that the printf format in OFMT is used instead of the value in CONVFMT. An empty expression list stands for the whole input record ($0).
The printf statement produces output based on a notation similar to the File Format Notation used to describe file formats in this document Output is produced as specified with the first expression argument as the string format and subsequent expression arguments as the strings arg1 to argn, inclusive, with the following exceptions:
Both print and printf can output at least {LINE_MAX} bytes.
The awk language has a variety of built-in functions: arithmetic, string, input/output and general.
The arithmetic functions, except for int, are based on the ISO C standard. The behavior is undefined in cases where the ISO C standard specifies that an error be returned or that the behavior is undefined. Although the grammar permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the [ ] brackets), such use is undefined.
atan2(y,x)
cos(x)
sin(x)
exp(x)
log(x)
sqrt(x)
int(x)
rand()
srand([expr])
The string functions in the following list shall be supported. Although the grammar permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the [ ] brackets), such use is undefined.
gsub(ere,repl[,in])
index(s,t)
length[([v])]
match(s,ere)
split(s,a[,fs])
sprintf(fmt,expr,expr,...)
sub(ere,repl[,in])
substr(s,m[,n])
tolower(s)
toupper(s)
All of the preceding functions that take ERE as a parameter expect a pattern or a string valued expression that is a regular expression as defined below.
The input/output and general functions are:
close(expression)
fflush(expression)
expression|getline[var]
The getline operator can form ambiguous constructs when there are operators that are not in parentheses (including concatenate) to the left of the | (to the beginning of the expression containing getline). In the context of the $ operator, | behaves as if it had a lower precedence than $. The result of evaluating other operators is unspecified, and all such uses of portable applications must be put in parentheses properly.
getline
getline var
getline [var] < expression
The getline operator can form ambiguous constructs when there are binary operators that are not in parentheses (including concatenate) to the right of the < (up to the end of the expression containing the getline). The result of evaluating such a construct is unspecified, and all such uses of portable applications must be put in parentheses properly.
system(expression)
All forms of getline return 1 for successful input, 0 for end of file, and −1 for an error.
Where strings are used as the name of a file or pipeline, the strings must be textually identical. The terminology ``same string value'' implies that ``equivalent strings'', even those that differ only by space characters, represent different files.
The awk language also provides user-defined functions. Such functions can be defined as:
function name(args,...) { statements }
A function can be referred to anywhere in an awk program; in particular, its use can precede its definition. The scope of a function is global.
Function arguments can be either scalars or arrays; the behavior is undefined if an array name is passed as an argument that the function uses as a scalar, or if a scalar expression is passed as an argument that the function uses as an array. Function arguments are passed by value if scalar and by reference if array name. Argument names are local to the function; all other variable names are global. The same name is not used as both an argument name and as the name of a function or a special awk variable. The same name must not be used both as a variable name with global scope and as the name of a function. The same name must not be used within the same scope both as a scalar variable and as an array.
The number of parameters in the function definition need not match the number of parameters in the function call. Excess formal parameters can be used as local variables. If fewer arguments are supplied in a function call than are in the function definition, the extra parameters that are used in the function body as scalars are initialized with a string value of the null string and a numeric value of zero, and the extra parameters that are used in the function body as arrays are initialized as empty arrays. If more arguments are supplied in a function call than are in the function definition, the behavior is undefined.
When invoking a function, no white space can be placed between the function name and the opening parenthesis. Function calls can be nested and recursive calls can be made upon functions. Upon return from any nested or recursive function call, the values of all of the calling function's parameters are unchanged, except for array parameters passed by reference. The return statement can be used to return a value. If a return statement appears outside of a function definition, the behavior is undefined.
In the function definition, newline characters are optional before the opening brace and after the closing brace. Function definitions can appear anywhere in the program where a pattern-action pair is allowed.
The index, length, match, and substr functions should not be confused with similar functions in the ISO C standard; the awk versions deal with characters, while the ISO C standard deals with bytes.
Because the concatenation operation is represented by adjacent expressions rather than an explicit operator, it is often necessary to use parentheses to enforce the proper evaluation precedence.
See largefile(7) for the description of the behavior of awk when encountering files greater than or equal to 2 Gbyte (2^31 bytes).
The awk program specified in the command line is most easily specified within single-quotes (for example, 'program') for applications using sh, because awk programs commonly contain characters that are special to the shell, including double-quotes. In the cases where a awk program contains single-quote characters, it is usually easiest to specify most of the program as strings within single-quotes concatenated by the shell with quoted single-quote characters. For example:
awk '/'\''/ { print "quote:", $0 }'
prints all lines from the standard input containing a single-quote character, prefixed with quote:.
The following are examples of simple awk programs:
Example 1 Write to the standard output all input lines for which field 3 is greater than 5:
$3 > 5
Example 2 Write every tenth line:
(NR % 10) == 0
Example 3 Write any line with a substring matching the regular expression:
/(G|D)(2[0-9][[:alpha:]]*)/
Example 4 Print any line with a substring containing a G or D, followed by a sequence of digits and characters:
This example uses character classes digit and alpha to match language-independent digit and alphabetic characters, respectively.
/(G|D)([[:digit:][:alpha:]]*)/
Example 5 Write any line in which the second field matches the regular expression and the fourth field does not:
$2 ~ /xyz/ && $4 !~ /xyz/
Example 6 Write any line in which the second field contains a backslash:
$2 ~ /\\/
Example 7 Write any line in which the second field contains a backslash (alternate method):
Notice that backslash escapes are interpreted twice, once in lexical processing of the string and once in processing the regular expression.
$2 ~ "\\\\"
Example 8 Write the second to the last and the last field in each line, separating the fields by a colon:
{OFS=":";print $(NF-1), $NF}
Example 9 Write the line number and number of fields in each line:
The three strings representing the line number, the colon and the number of fields are concatenated and that string is written to standard output.
{print NR ":" NF}
Example 10 Write lines longer than 72 characters:
{length($0) > 72}
Example 11 Write first two fields in opposite order separated by the OFS:
{ print $2, $1 }
Example 12 Same, with input fields separated by comma or space and tab characters, or both:
BEGIN { FS = ",[\t]*|[\t]+" }
{ print $2, $1 }
Example 13 Add up first column, print sum and average:
{s += $1 } END {print "sum is ", s, " average is", s/NR}
Example 14 Write fields in reverse order, one per line (many lines out for each line in):
{ for (i = NF; i > 0; --i) print $i }
Example 15 Write all lines between occurrences of the strings "start" and "stop":
/start/, /stop/
Example 16 Write all lines whose first field is different from the previous one:
$1 != prev { print; prev = $1 }
Example 17 Simulate the echo command:
BEGIN {
for (i = 1; i < ARGC; ++i)
printf "%s%s", ARGV[i], i==ARGC-1?"\n":""
}
Example 18 Write the path prefixes contained in the PATH environment variable, one per line:
BEGIN {
n = split (ENVIRON["PATH"], path, ":")
for (i = 1; i <= n; ++i)
print path[i]
}
Example 19 Print the file "input", filling in page numbers starting at 5:
If there is a file named input containing page headers of the form
Page#
and a file named program that contains
/Page/{ $2 = n++; } { print }
then the command line
awk -f program n=5 input
prints the file input, filling in page numbers starting at 5.
See environ(7) for descriptions of the following environment variables that affect execution: LC_COLLATE, LC_CTYPE, LC_MESSAGES, and NLSPATH.
LC_NUMERIC
The following exit values are returned:
0
>0
The exit status can be altered within the program by using an exit expression.
ed(1), egrep(1), grep(1), lex(1), oawk(1), sed(1), popen(3C), printf(3C), system(3C), XPG4(7), attributes(7), environ(7), largefile(7), regex(7)
Aho, A. V., B. W. Kernighan, and P. J. Weinberger, The AWK Programming Language, Addison-Wesley, 1988.
If any file operand is specified and the named file cannot be accessed, awk writes a diagnostic message to standard error and terminate without any further action.
If the program specified by either the program operand or a progfile operand is not a valid awk program (as specified in EXTENDED DESCRIPTION), the behavior is undefined.
Input white space is not preserved on output if fields are involved.
There are no explicit conversions between numbers and strings. To force an expression to be treated as a number add 0 to it; to force it to be treated as a string concatenate the null string ("") to it.
June 13, 2021 | OmniOS |