/usr/xpg4/bin/awk [ -F ERE ] [ -v assignment ... ] ’program’ | -f progfile ... [ argument ... ]
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 nawk 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 -F ERE option. The nawk 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.
arguments to the getline function
- any file operands or their equivalents, achieved by modifying the nawk variables ARGV and ARGC
- standard input in the absence of any file operands
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 may support longer records.
If -f progfile is specified, the files named by each of the progfile option-arguments must be text files containing an nawk program.
The standard input are used only if no file operands are specified, or if a file operand is -.
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 nawk 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.
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:
.
- Any leading and trailing blank characters is ignored.
.- If the first unignored character is a + or -, it is ignored.
.- If the remaining unignored characters would be lexically recognized as a NUMBER token, the string is considered a numeric string.
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 first subexpression of a conditional expression.
- an expression operated on by logical NOT , logical AND, or logical OR .
- the second expression of a for statement.
- the expression of an if statement.
- the expression of the while clause in either a while or do ... while statement.
- an expression used as a pattern (as in Overall Program Structure).
The nawk 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 parameter in a function definition or function call.
- the NAME token following any use of the keyword in.
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 nawk 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.
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 nawk above), the field variable also has the numeric value of the numeric string.
nawk sets the following special variables:
Escape | Description | Meaning |
Sequence | ||
\" | Backslash quotation-mark | |
Quotation-mark character | ||
T} | ||
\/ | Backslash slash | |
Slash character | ||
T} | ||
\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. | ||
T} | ||
\c | A backslash character followed by any character not described in this table or special characters (\\, \a, \b, \f, \n, \r, \t, \v). |
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. Note 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:
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:
.
- If FS is a single character:
- a.
- If FS is the space character, skip leading and trailing blank characters; fields are delimited by sets of one or more blank characters.
- b.
- Otherwise, if FS is any other character c, fields are delimited by each single occurrence of c.
.
- Otherwise, the string value of FS is considered to be an extended regular expression. Each occurrence of a sequence matching the extended regular expression delimits fields.
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 will match any character. However, in all nawk regular expression matching, the use of one or more NUL characters in the pattern, input record or text string produces undefined results.
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 nawk program consists of only actions with the pattern BEGIN , and the BEGIN action contains no getline function, nawk exits without reading its input when the last statement in the last BEGIN action is executed. If an nawk 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 action is a sequence of statements. A statement may 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 break continue { [ statement ] ... } expression # commonly variable = expression print [ expression-list ] [ >expression ] printf format [ , expression-list ] [ >expression ] next # skip remaining patterns on this input line 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 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 nawk, unless subsequent errors are encountered or a subsequent exit statement with an expression is executed.
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(3S) 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 will remain 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:
1. The format is an actual character string rather than a graphical representation. Therefore, it cannot contain empty character positions. The space character in the format string, in any context other than a flag of a conversion specification, is treated as an ordinary character that is copied to the output.
2. If the character set contains a *D character and that character appears in the format string, it is treated as an ordinary character that is copied to the output.
3. The escape sequences beginning with a backslash character is treated as sequences of ordinary characters that are copied to the output. Note that these same sequences is interpreted lexically by nawk when they appear in literal strings, but they is not treated specially by the printf statement.
4. A field width or precision can be specified as the * character instead of a digit string. In this case the next argument from the expression list is fetched and its numeric value taken as the field width or precision.
5. The implementation does not precede or follow output from the d or u conversion specifications with blank characters not specified by the format string.
6. The implementation does not precede output from the o conversion specification with leading zeros not specified by the format string.
7. For the c conversion specification: if the argument has a numeric value, the character whose encoding is that value is output. If the value is zero or is not the encoding of any character in the character set, the behavior is undefined. If the argument does not have a numeric value, the first character of the string value will be output; if the string does not contain any characters the behavior is undefined.
8. For each conversion specification that consumes an argument, the next expression argument will be evaluated. With the exception of the c conversion, the value will be converted to the appropriate type for the conversion specification.
9. If there are insufficient expression arguments to satisfy all the conversion specifications in the format string, the behavior is undefined.
10. If any character sequence in the format string begins with a % character, but does not form a valid conversion specification, the behavior is unspecified.
Both print and printf can output at least {LINE_MAX } bytes.
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.
All forms of getline will return 1 for successful input, zero 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.
A function can be referred to anywhere in an nawk program; in particular, its use can precede its definition. The scope of a function will be 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 will be passed by value if scalar and by reference if array name. Argument names will be local to the function; all other variable names will be global. The same name will not be used as both an argument name and as the name of a function or a special nawk 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 will be 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 will be 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 will be 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.
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.
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 nawk programs:
.
- Write to the standard output all input lines for which field 3 is greater than 5:
$3 > 5.
- Write every tenth line:
(NR % 10) == 0.
- Write any line with a substring matching the regular expression:
/(G|D)(2[0-9][[:alpha:]]*)/.
- 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:]]*)/.
- Write any line in which the second field matches the regular expression and the fourth field does not:
$2 ~ /xyz/ && $4 !~ /xyz/.
- Write any line in which the second field contains a backslash:
$2 ~ /\\/
.
- Write any line in which the second field contains a backslash. Note that backslash escapes are interpreted twice, once in lexical processing of the string and once in processing the regular expression:
$2 ~ "\\\\".
- Write the second to the last and the last field in each line. Separate the fields by a colon:
{OFS=":";print $(NF-1), $NF}.
- 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}.
- Write lines longer than 72 characters:
{length($0) > 72}.
- Write first two fields in opposite order separated by the OFS :
{ print $2, $1 }.
- Same, with input fields separated by comma or space and tab characters, or both:
BEGIN { FS = ",[ \t]*|[ \t]+" } { print $2, $1 }
{s += $1 } END {print "sum is ", s, " average is", s/NR}
{ for (i = NF; i > 0; --i) print $i }
/start/, /stop/
$1 != prev { print; prev = $1 }
BEGIN {
for (i = 1; i < ARGC; ++i)
printf "%s%s", ARGV[i], i==ARGC-1?"\n":""
}
BEGIN {
n = split (ENVIRON["PATH"], path, ":")
for (i = 1; i <= n; ++i)
print path[i]
}
Page#
and a file named program that contains:
/Page/{ $2 = n++; }
{ print }
then the command line:
nawk -f program n=5 input
will print the file input, filling in page numbers starting at 5.
The exit status can be altered within the program by using an exit expression.
The awk chapter in the
A. V. Aho, B. W. Kerninghan, P. J. Weinberger, The AWK Programming Language Addison-Wesley, 1988.
If the program specified by either the program operand or a progfile operand is not a valid nawk 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.