awk - pattern scanning and processing language
awk [-F ERE][-v assignment] ... program [argument ...] awk [-F ERE] -v progfile] ... [-v assignment] ...[argument ...]
The awk utility executes programs written in the awk programming language, which is specialised for textual data manipulation. An awk program is a sequence of patterns and corresponding actions. When input is read that matches a pattern, the action associated with that pattern will be carried out.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 in turn against each pattern in the program. For each pattern matched, the associated action will be 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 can be changed by using the FS built-in variable or the -F ERE. The awk utility denotes the first field in a record $1, the second $2, and so on. The symbol $0 refers to the entire record; setting any other field will cause the reevaluation of $0. Assigning to $0 will reset the values of all other fields and the NF built-in variable.
The awk utility supports the XBD specification, Utility Syntax Guidelines .The following options are supported:
- -F ERE
- Define the input field separator to be the extended regular expression ERE, before any input is read; see
Regular Expressions .- -f progfile
- Specifies the pathname of the file progfile containing an awk program. If multiple instances of this option are specified, the concatenation of the files specified as progfile in the order specified will be the awk program. The awk program can alternatively be specified in the command line as a single argument.
- -v assignment
- The assignment argument must be in the same form as an assignment operand. The specified variable assignment will occur prior to executing the awk program, including the actions associated with BEGIN patterns (if any). Multiple occurrences of this option can be specified.
The following operands are supported:
- program
- If no -f option is specified, the first operand to awk will be the text of the awk program. The application will supply the program operand as a single argument to awk. If the text does not end in a newline character, awk will interpret the text as if it did.
- argument
- Either of the following two types of argument can be intermixed:
- file
- A pathname of a file that contains the input to be read, which is matched against the set of patterns in the program. If no file operands are specified, or if a file operand is "-", the standard input will be used.
- assignment
- An operand that begins with an underscore or alphabetic character from the portable character set (see the table in the XBD specification, Portable Character Set ), followed by a sequence of underscores, digits and alphabetics from the portable character set, followed by the "=" character will specify a variable assignment rather than a pathname. The characters before the "=" represent the name of an awk variable; if that name is an awk reserved word (see
Grammar ) the behaviour is undefined. The characters following the equal sign will be interpreted as if they appeared in the awk program preceded and followed by a double-quote (") character, as a STRING token (seeGrammar ), except that if the last character is an unescaped backslash, it will be interpreted as a literal backslash rather than as the first character of the sequence \". The variable will be assigned the value of that STRING token. If that value is considered a numeric string (seeExpressions in awk ), the variable will also be assigned its numeric value. Each such variable assignment will occur just prior to the processing of the following file, if any. Thus, an assignment before the first file argument will be executed after the BEGIN actions (if any), while an assignment after the last file argument will occur before the END actions (if any). If there are no file arguments, assignments will be executed before processing the standard input.
The standard input will be used only if no file operands are specified, or if a file operand is "-". See the INPUT FILES section.
Input files to the awk program from any of the following sources:
- any file operands or their equivalents, achieved by modifying the awk variables ARGV and ARGC
- standard input in the absence of any file operands
- arguments to the getline function
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 awk program.
The following environment variables affect the execution of awk:
- LANG
- Provide a default value for the internationalisation variables that are unset or null. If LANG is unset or null, the corresponding value from the implementation-dependent default locale will be used. If any of the internationalisation variables contains an invalid setting, the utility will behave as if none of the variables had been defined.
- LC_ALL
- If set to a non-empty string value, override the values of all the other internationalisation variables.
- LC_COLLATE
- Determine the locale for the behaviour of ranges, equivalence classes and multi-character collating elements within regular expressions and in comparisons of string values.
- LC_CTYPE
- Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single- versus multi-byte characters in arguments and input files), the behaviour of character classes within regular expressions, the identification of characters as letters, and the mapping of upper- and lower-case characters for the toupper and tolower functions.
- LC_MESSAGES
- Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
- LC_NUMERIC
- Determine the radix character used when interpreting numeric input, performing conversions between numeric and string values and formatting numeric output. Regardless of locale, the period character (the decimal-point character of the POSIX locale) is the decimal-point character recognised in processing awk programs (including assignments in command-line arguments).
- NLSPATH
- Determine the location of message catalogues for the processing of LC_MESSAGES .
- PATH
- Determine the search path when looking for commands executed by system(expr), or input and output pipes. See the XBD specification, Environment Variables .
In addition, all environment variables will be visible via the awk variable ENVIRON.
Default.
The nature of the output files depends on the awk program.
Used only for diagnostic messages.
The nature of the output files depends on the awk program.
Overall Program Structure
An awk program is composed of pairs of the form:Either the pattern or the action (including the enclosing brace characters) can be omitted.pattern { action }
A missing pattern will match any record of input, and a missing action will be 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) will be processed in turn 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 according to the rules in
Regular Expressions , 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 will be executed before evaluating subsequent patterns. Last, the actions associated with all END patterns will be executed in the order they occur in the program.Expressions in awk
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 will be 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). The precise syntax of expressions is given in Grammar .
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 array Multi-dimension array membership numeric left expr && expr Logical AND numeric left expr || expr Logical OR numeric left expr1 ? expr2 : expr3 Conditional expression type of selected expr2 or expr3 right lvalue ^= expr Exponentiation assignment numeric right lvalue %= expr Modulus assignment numeric right lvalue *= expr Multiplication assignment numeric right 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
Table: Expressions in Decreasing Precedence in awk
Each expression has either a string value, a numeric value or both. Except as stated for specific contexts, the value of an expression will be implicitly converted to the type needed for the context in which it is used. A string value will be converted to a numeric value by the equivalent of the following calls to functions defined by the ISO C standard:
A numeric value that is exactly equal to the value of an integer will be converted to a string by the equivalent of a call to the sprintf function (seesetlocale(LC_NUMERIC, ""); numeric_value = atof(string_value);
String Functions ) 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 will be 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. The result of the conversion is unspecified if the value of CONVFMT is not a floating-point format specification. This specification specifies no explicit conversions between numbers and strings. An application can force an expression to be treated as a number by adding zero to it, or can force it to be treated as a string by concatenating the null string ("") to it.A string value will be considered to be a numeric string in the following case:
- Any leading and trailing blank characters will be ignored.
- If the first unignored character is a "+" or "-", it will be ignored.
- If the remaining unignored characters would be lexically recognised as a NUMBER token (as described by the lexical conventions in
Grammar ), the string will be considered a numeric string .
If a "-" character is ignored in the above steps, the numeric value of the numeric string will be the negation of the numeric value of the recognised NUMBER token. Otherwise the numeric value of the numeric string will be the numeric value of the recognised NUMBER token. Whether or not a string is a numeric string will be 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).
All arithmetic will follow the semantics of floating-point arithmetic as specified by the ISO C standard.
The value of the expression:
will be equivalent to the value returned by the ISO C standard function call:expr1 ^ expr2
pow(expr1, expr2)
The expression:
will be equivalent to the ISO C standard expression:lvalue ^= expr
except that lvalue will be evaluated only once. The value of the expression:lvalue = pow(lvalue, expr)
will be equivalent to the value returned by the ISO C standard function call:expr1 % expr2
The expression:fmod(expr1, expr2)
will be equivalent to the ISO C standard expression:lvalue %= expr
except that lvalue will be evaluated only once.lvalue = fmod(lvalue, expr)
Variables and fields will be set by the assignment statement:
and the type of expression will determine the resulting variable type. The assignment includes the arithmetic assignments (+=, -=, *=, /=, %=, ^=, ++, --) all of which produce a numeric result. The left-hand side of an assignment and the target of increment and decrement operators can be one of a variable, an array with index or a field selector.lvalue = expression
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 will change 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 thus as an expression, as described in the grammar (see
Grammar ). Unsubscripted array names can be 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 as specified in the grammar (see
Grammar ); if the name used in this context is not an array name, the behaviour is undefined.
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 will be 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 will be equivalent:
var[expr1, expr2, ... exprn] var[expr1 SUBSEP expr2 SUBSEP ... SUBSEP exprn]
A multi-dimensioned index used with the in operator must be parenthesised. The in operator, which tests for the existence of a particular array element, will not cause that element to exist. Any other reference to a non-existent array element will automatically create it.
Comparisons (with the "<", "<=", "!=", "==", ">" and ">=" operators) will be made numerically if both operands are numeric or if one is numeric and the other has a string value that is a numeric string. Otherwise, operands will be converted to strings as required and a string comparison will be made using the locale-specific collation sequence. The value of the comparison expression will be 1 if the relation is true, or 0 if the relation is false.
Variables and Special Variables
Variables can be used in an awk program by referencing them. With the exception of function parameters (seeUser-defined Functions ), they are not explicitly declared. Uninitialised 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; uninitialised variables or string values need not be converted to numeric values in this context. New field variables can be created by assigning a value to them. References to non-existent fields (that is, fields after $NF), will produce the null string. However, assigning to a non-existent field (for example, $(NF +2) = 5) will increase 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 will have 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, would be considered a numeric string (see
Expressions in awk ), the field variable will also have the numeric value of the numeric string .Implementations support the following other special variables that are set by awk:
- ARGC
- The number of elements in the ARGV array.
- ARGV
- An array of command line arguments, excluding options and the program argument, numbered from zero to ARGC-1. The arguments in ARGV can be modified or added to; ARGC can be altered. As each input file ends, awk will treat the next non-null element of ARGV, up to the current value of ARGC-1, inclusive, as the name of the next input file. Thus, setting an element of ARGV to null means that it will not be treated as an input file. The name "-" indicates the standard input. If an argument matches the format of an assignment operand, this argument will be treated as an assignment rather than a file argument.
- CONVFMT
- The printf format for converting numbers to strings (except for output statements, where OFMT is used); %.6g by default.
- ENVIRON
- The variable ENVIRON is an array representing the value of the environment, as described in the XSH specification under the exec functions. The indices of the array are strings consisting of the names of the environment variables, and the value of each array element is a string consisting of the value of that variable. If the value of an environment variable is considered a numeric string (see
Expressions in awk ), the array element will also have its numeric value. In all cases where the behaviour of awk 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 will be the environment at the time awk began executing; it is implementation-dependent whether any modification of ENVIRON affects this environment.- FILENAME
- A pathname of the current input file. Inside a BEGIN action the value is undefined. Inside an END action the value is the name of the last input file processed.
- FNR
- The ordinal number of the current record in the current file. Inside a BEGIN action the value is zero. Inside an END action the value is the number of the last record processed in the last file processed.
- FS
Input field separator regular expression; a space character by default. - NF
- The number of fields in the current record. Inside a BEGIN action, the use of NF is undefined unless a getline function without a var argument is executed previously. Inside an END action, NF will retain the value it had for the last record read, unless a subsequent, redirected, getline function without a var argument is performed prior to entering the END action.
- NR
- The ordinal number of the current record from the start of input. Inside a BEGIN action the value is zero. Inside an END action the value is the number of the last record processed.
- OFMT
- The printf format for converting numbers to strings in output statements (see
Output Statements ); %.6g by default. The result of the conversion is unspecified if the value of OFMT is not a floating-point format specification.- OFS
- The print statement output field separation; a space character by default.
- ORS
- The print statement output record separator; a newline character by default.
- RLENGTH
- The length of the string matched by the match function.
- RS
- The first character of the string value of RS is the input record separator; a newline character by default. If RS contains more than one character, the results are unspecified. If RS is null, then records are separated by sequences of one or more blank lines, leading or trailing blank lines do not result in empty records at the beginning or end of the input, and a newline character is always a field separator, no matter what the value of FS is.
- RSTART
- The starting position of the string matched by the match function, numbering from 1. This is always equivalent to the return value of the match function.
- SUBSEP
- The subscript separator string for multi-dimensional arrays; the default value is implementation-dependent.
Regular Expressions
The awk utility makes use of the extended regular expression notation (see the XBD specification, Extended Regular Expressions ) except that it will allow the use of C-language conventions for escaping special characters within the EREs, as specified in the table in the XBD specification, File Format Notation (\\, \a, \b, \f, \n, \r, \t, \v) and the following table; these escape sequences will be recognised 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 the escaping shown in the following table:
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 NUL character), the behaviour is undefined. The character whose encoding is represented by the one-, two- or three-digit octal integer. If the size of a byte on the system is greater than nine bits, the valid escape sequence used to represent a byte is implementation-dependent. Multi-byte characters require multiple, concatenated escape sequences of this type, including the leading \ for each byte. \c A backslash character followed by any character not described in this table or in the table in the XBD specification, File Format Notation ( \\,\a,\b,\f,\n,\r,\t,\v
)Undefined
Table: Escape Sequences in awk 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 will evaluate to a value of 1, and the !~ expression will evaluate to a value of 0. (The regular expression matching operation is as defined by the term matched in the XBD specification, Regular Expression Definitions , where a match occurs on any part of the string unless the regular expression is limited with the circumflex or dollar sign special characters.) If the regular expression does not match the string, the ~ expression will evaluate to a value of 0, and the !~ expression will evaluate to a value of 1. If the right-hand operand is any expression other than the lexical token ERE, the string value of the expression will be interpreted as an extended regular expression, including the escape conventions described above. Note that these same escape conventions also will be applied in the determining the value of a string literal (the lexical token STRING), and thus will be 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 will be 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 ) will be interpreted as extended regular expressions. These can be either ERE tokens or arbitrary expressions, and will be 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 will be a single space character. The following describes FS behaviour:
- If FS is a single character:
- If FS is the space character, skip leading and trailing blank characters; fields will be delimited by sets of one or more blank characters.
- Otherwise, if FS is any other character c, fields will be delimited by each single occurrence of c .
- Otherwise, the string value of FS will be considered to be an extended regular expression. Each occurrence of a sequence matching the extended regular expression will delimit fields.
Except in the gsub, match, split and sub built-in functions, regular expression matching will be 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 will match 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 will be based on text strings; that is, 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 awk regular expression matching, the use of one or more NUL characters in the pattern, input record or text string produces undefined results.
Patterns
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.Special Patterns
The awk utility recognises two special patterns, BEGIN and END. Each BEGIN pattern will be matched once and its associated action executed before the first record of input is read (except possibly by use of the getline function (seeInput/Output and General Functions ) in a prior BEGIN action) and before command line assignment is done. Each END pattern will be matched once and its associated action executed after the last record of input has been read. These two patterns will have associated actions.BEGIN and END will not combine with other patterns. Multiple BEGIN and END patterns are allowed. The actions associated with the BEGIN patterns will be 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 will exit 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 will be read before the statements in the END actions are executed.
Expression Patterns
An expression pattern will be evaluated as if it were an expression in a Boolean context. If the result is true, the pattern will be considered to match, and the associated action (if any) will be executed. If the result is false, the action will not be executed.Pattern Ranges
A pattern range consists of two expressions separated by a comma; in this case, the action will be 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.Actions
An action is a sequence of statements as shown in the grammar inGrammar . Any single statement can be replaced by a statement list enclosed in braces. The statements in a statement list must be separated by newline characters or semicolons, and will be executed sequentially in the order that they appear.The expression acting as the conditional in an if statement will be evaluated and if it is non-zero or non-null, the following statement will be executed; otherwise, if else is present, the statement following the else will be executed.
The if, while, do ... while, for, break and continue statements are based on the ISO C standard, except that the Boolean expressions are treated as described in
Expressions in awk , and except in the case of:which will iterate, assigning each index of array to variable in an unspecified order. The results of adding new elements to array within such a for loop are undefined. If a break or continue statement occurs outside of a loop, the behaviour is undefined.for (variable in array)
The delete statement will remove an individual array element. Thus, the following code will delete an entire array:
for (index in array) delete array[index]
The next statement will cause all further processing of the current input record to be abandoned. The behaviour is undefined if a next statement appears or is invoked in a BEGIN or END action.
The exit statement will invoke 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 will terminate the program without further execution of END actions. If an expression is specified in an exit statement, its numeric value will be the exit status of awk, unless subsequent errors are encountered or a subsequent exit statement with an expression is executed.
Output Statements
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 will be 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 will be opened, creating it if necessary and using the first form, truncating the file. The output then will be appended to the file. As long as the file remains open, subsequent calls in which expression evaluates to the same string value simply will append output to the file. The file remains open until the close function (see
Input/Output and General Functions ) is called with an expression that evaluates to the same string value.The third form will write output onto a stream piped to the input of a command. The stream will be created if no stream is currently open with the value of expression as its command name. The stream created will be equivalent to one created by a call to the XSH specification popen() 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 will write output to the existing stream. The stream will remain open until the close function (see
Input/Output and General Functions ) is called with an expression that evaluates to the same string value. At that time, the stream will be closed as if by a call to the XSH specification pclose() function.As described in detail by the grammar in
Grammar , these output statements take a comma-separated list of expressions 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 will write 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 will be taken as strings, being converted if necessary; this conversion will be as described in
Expressions in awk , with the exception that the printf format in OFMT will be used instead of the value in CONVFMT. An empty expression list will stand for the whole input record ($0).The printf statement will produce output based on a notation similar to the File Format Notation used to describe file formats in this specification (see the XBD specification, File Format Notation ). Output will be 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:
- The format will be 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, will be treated as an ordinary character that is copied to the output.
- If the character set contains a character and that character appears in the format string, it will be treated as an ordinary character that is copied to the output.
- The escape sequences beginning with a backslash character will be treated as sequences of ordinary characters that are copied to the output. Note that these same sequences will be interpreted lexically by awk when they appear in literal strings, but they will not be treated specially by the printf statement.
- 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 will be fetched and its numeric value taken as the field width or precision.
- The implementation will not precede or follow output from the d or u conversion specifications with blank characters not specified by the format string.
- The implementation will not precede output from the o conversion specification with leading zeros not specified by the format string.
- For the c conversion specification: if the argument has a numeric value, the character whose encoding is that value will be output. If the value is zero or is not the encoding of any character in the character set, the behaviour 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 behaviour is undefined.
- 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 (according to the rules specified in
Expressions in awk ) to the appropriate type for the conversion specification.
- If there are insufficient expression arguments to satisfy all the conversion specifications in the format string, the behaviour is undefined.
- If any character sequence in the format string begins with a % character, but does not form a valid conversion specification, the behaviour is unspecified.
Both print and printf can output at least {LINE_MAX} bytes.
Functions
The awk language has a variety of built-in functions: arithmetic, string, input/output and general.Arithmetic Functions
The arithmetic functions, except for int, are based on the ISO C standard. The behaviour is undefined in cases where the ISO C standard specifies that an error be returned or that the behaviour is undefined. Although the grammar (seeGrammar ) 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)
- Return arctangent of y/x.
- cos(x)
- Return cosine of x, where x is in radians.
- sin(x)
- Return sine of x, where x is in radians.
- exp(x)
- Return the exponential function of x.
- log(x)
- Return the natural logarithm of x.
- sqrt(x)
- Return the square root of x.
- int(x)
- Truncate its argument to an integer. It will be truncated toward 0 when x > 0.
- rand()
- Return a random number n, such that 0 <= n < 1.
- srand([expr])
- Set the seed value for rand to expr or use the time of day if expr is omitted. The previous seed value will be returned.
String Functions
The string functions in the following list shall be supported. Although the grammar (see 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])
- Behave like sub (see below), except that it will replace all occurrences of the regular expression (like the ed utility global substitute) in $0 or in the in argument, when specified.
- index(s, t)
- Return the position, in characters, numbering from 1, in string s where string t first occurs, or zero if it does not occur at all.
- length[([s])]
- Return the length, in characters, of its argument taken as a string, or of the whole record, $0, if there is no argument. The use of no argument and no parentheses with length is obsolescent in the ISO/IEC 9945-2:1993 standard; to be fully portable to POSIX systems, the application must use length($0) for the length of the whole record. However, XSI-conformant systems will continue to support this usage indefinitely.
- match(s, ere)
- Return the position, in characters, numbering from 1, in string s where the extended regular expression ere occurs, or zero if it does not occur at all. RSTART will be set to the starting position (which is the same as the returned value), zero if no match is found; RLENGTH will be set to the length of the matched string, -1 if no match is found.
- split(s, a[,fs])
- Split the string s into array elements a [1], a [2], ... a [ n and return n . The separation will be done with the extended regular expression fs or with the field separator FS if fs is not given. Each array element will have a string value when created. If the string assigned to any array element, with any occurrence of the decimal-point character from the current locale changed to a period character, would be considered a numeric string (see
Expressions in awk ), the array element will also have the numeric value of the numeric string . The effect of a null string as the value of fs is unspecified.- sprintf(fmt, expr, expr, ...)
- Format the expressions according to the printf format given by fmt and return the resulting string.
- sub(ere, repl[,in])
- Substitute the string repl in place of the first instance of the extended regular expression ERE in string in and return the number of substitutions. An ampersand (&) appearing in the string repl will be replaced by the string from in that matches the regular expression. For each occurrence of backslash (\) encountered when scanning the string repl from beginning to end, the next character is taken literally and loses its special meaning (for example, \& will be interpreted as a literal ampersand character). Except for & and \, it is unspecified what the special meaning of any such character is. If in is specified and it is not an lvalue (see
Expressions in awk ), the behaviour is undefined. If in is omitted, awk will substitute in the current record ($0).- substr(s, m[,n])
- Return the at most n -character substring of s that begins at position m, numbering from 1. If n is missing, the length of the substring will be limited by the length of the string s .
- tolower(s)
- Return a string based on the string s . Each character in s that is an upper-case letter specified to have a tolower mapping by the LC_CTYPE category of the current locale will be replaced in the returned string by the lower-case letter specified by the mapping. Other characters in s will be unchanged in the returned string.
- toupper(s)
- Return a string based on the string s . Each character in s that is a lower-case letter specified to have a toupper mapping by the LC_CTYPE category of the current locale will be replaced in the returned string by the upper-case letter specified by the mapping. Other characters in s will be unchanged in the returned string.
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 in
Regular Expressions .Input/Output and General Functions
The input/output and general functions are:
- close(expression)
- Close the file or pipe opened by a print or printf statement or a call to getline with the same string-valued expression. The limit on the number of open expression arguments is implementation-dependent. If the close was successful, the function will return zero; otherwise, it will return non-zero.
- expression | getline [var]
- Read a record of input from a stream piped from the output of a command. The stream will be created if no stream is currently open with the value of expression as its command name. The stream created will be equivalent to one created by a call to the popen() function with the value of expression as the command argument and a value of r as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value will read subsequent records from the file. 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 will be closed as if by a call to the pclose() function. If var is missing, $0 and NF will be set; otherwise, var will be set. The getline operator can form ambiguous constructs when there are unparenthesised operators (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 portable applications must parenthesise properly all such usages.
- getline
- Set $0 to the next input record from the current input file. This form of getline will set the NF, NR and FNR variables.
- getline var
- Set variable var to the next input record from the current input file. This form of getline will set the FNR and NR variables.
- getline [var] < expression
- Read the next record of input from a named file. The expression will be evaluated to produce a string that is used as a full pathname. If the file of that name is not currently open, it will be opened. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value will read subsequent records from the file. The file will remain open until the close function is called with an expression that evaluates to the same string value. If var is missing, $0 and NF will be set; otherwise, var will be set. The getline operator can form ambiguous constructs when there are unparenthesised binary operators (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 portable applications must parenthesise properly all such usages.
- system(expression)
- Execute the command given by expression in a manner equivalent to the XSH specification system() function and return the exit status of the command.
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.
User-defined Functions
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 will be global.
Function arguments can be either scalars or arrays; the behaviour 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 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 will be initialised 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 initialised as empty arrays. If more arguments are supplied in a function call than are in the function definition, the behaviour 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 behaviour 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.
Grammar
The grammar in this section and the lexical conventions in the following section will together describe the syntax for awk programs. The general conventions for this style of grammar are described in . A valid program can be represented as the non-terminal symbol program in the grammar. This formal syntax takes precedence over the preceding text syntax description. %token NAME NUMBER STRING ERE %token FUNC_NAME /* name followed by '(' without white space */ /* Keywords */ %token Begin End /* 'BEGIN' 'END' */ %token Break Continue Delete Do Else /* 'break' 'continue' 'delete' 'do' 'else' */ %token Exit For Function If In /* 'exit' 'for' 'function' 'if' 'in' */ %token Next Print Printf Return While /* 'next' 'print' 'printf' 'return' 'while' */ /* Reserved function names */ %token BUILTIN_FUNC_NAME /* one token for the following: * atan2 cos sin exp log sqrt int rand srand * gsub index length match split sprintf sub * substr tolower toupper close system */ %token GETLINE /* Syntactically different from other built-ins */ /* Two-character tokens */ %token ADD_ASSIGN SUB_ASSIGN MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN POW_ASSIGN /* '+=' '-=' '*=' '/=' '%=' '^=' */ %token OR AND NO_MATCH EQ LE GE NE INCR DECR APPEND /* '||' '&&' '!' '==' '<=' '>=' '!=' '++' '--' '>>' */ /* One-character tokens */ %token '{' '}' '(' ')' '[' ']' ',' ';' NEWLINE %token '+' '-' '*' '%' '^' '!' '>' '<' '|' '?' ':' '~' '$' '=' %start program %% program : item_list | actionless_item_list ; item_list : newline_opt | actionless_item_list item terminator | item_list item terminator | item_list action terminator ; actionless_item_list : item_list pattern terminator | actionless_item_list pattern terminator ; item : pattern action | Function NAME '(' param_list_opt ')' newline_opt action | Function FUNC_NAME '(' param_list_opt ')' newline_opt action ; param_list_opt : /* empty */ | param_list ; param_list : NAME | param_list ',' NAME ; pattern : Begin | End | expr | expr ',' newline_opt expr ; action : '{' newline_opt '}' | '{' newline_opt terminated_statement_list '}' | '{' newline_opt unterminated_statement_list '}' ; terminator : terminator ';' | terminator NEWLINE | ';' | NEWLINE ; terminated_statement_list : terminated_statement | terminated_statement_list terminated_statement ; unterminated_statement_list : unterminated_statement | terminated_statement_list unterminated_statement ; terminated_statement : action newline_opt | If '(' expr ')' newline_opt terminated_statement | If '(' expr ')' newline_opt terminated_statement Else newline_opt terminated_statement | While '(' expr ')' newline_opt terminated_statement | For '(' simple_statement_opt ';' expr_opt ';' simple_statement_opt ')' newline_opt terminated_statement | For '(' NAME In NAME ')' newline_opt terminated_statement | ';' newline_opt | terminatable_statement NEWLINE newline_opt | terminatable_statement ';' newline_opt ; unterminated_statement : terminatable_statement | If '(' expr ')' newline_opt unterminated_statement | If '(' expr ')' newline_opt terminated_statement Else newline_opt unterminated_statement | While '(' expr ')' newline_opt unterminated_statement | For '(' simple_statement_opt ';' expr_opt ';' simple_statement_opt ')' newline_opt unterminated_statement | For '(' NAME In NAME ')' newline_opt unterminated_statement ; terminatable_statement : simple_statement | Break | Continue | Next | Exit expr_opt | Return expr_opt | Do newline_opt terminated_statement While '(' expr ')' ; simple_statement_opt : /* empty */ | simple_statement ; simple_statement : Delete NAME '[' expr_list ']' | expr | print_statement ; print_statement : simple_print_statement | simple_print_statement output_redirection ; simple_print_statement : Print print_expr_list_opt | Print '(' multiple_expr_list ')' | Printf print_expr_list | Printf '(' multiple_expr_list ')' ; output_redirection : '>' expr | APPEND expr | '|' expr ; expr_list_opt : /* empty */ | expr_list ; expr_list : expr | multiple_expr_list ; multiple_expr_list : expr ',' newline_opt expr | multiple_expr_list ',' newline_opt expr ; expr_opt : /* empty */ | expr ; expr : unary_expr | non_unary_expr ; unary_expr : '+' expr | '-' expr | unary_expr '^' expr | unary_expr '*' expr | unary_expr '/' expr | unary_expr '%' expr | unary_expr '+' expr | unary_expr '-' expr | unary_expr non_unary_expr | unary_expr '<' expr | unary_expr LE expr | unary_expr NE expr | unary_expr EQ expr | unary_expr '>' expr | unary_expr GE expr | unary_expr '~' expr | unary_expr NO_MATCH expr | unary_expr In NAME | unary_expr AND newline_opt expr | unary_expr OR newline_opt expr | unary_expr '?' expr ':' expr | unary_input_function ; non_unary_expr : '(' expr ')' | '!' expr | non_unary_expr '^' expr | non_unary_expr '*' expr | non_unary_expr '/' expr | non_unary_expr '%' expr | non_unary_expr '+' expr | non_unary_expr '-' expr | non_unary_expr non_unary_expr | non_unary_expr '<' expr | non_unary_expr LE expr | non_unary_expr NE expr | non_unary_expr EQ expr | non_unary_expr '>' expr | non_unary_expr GE expr | non_unary_expr '~' expr | non_unary_expr NO_MATCH expr | non_unary_expr In NAME | '(' multiple_expr_list ')' In NAME | non_unary_expr AND newline_opt expr | non_unary_expr OR newline_opt expr | non_unary_expr '?' expr ':' expr | NUMBER | STRING | lvalue | ERE | lvalue INCR | lvalue DECR | INCR lvalue | DECR lvalue | lvalue POW_ASSIGN expr | lvalue MOD_ASSIGN expr | lvalue MUL_ASSIGN expr | lvalue DIV_ASSIGN expr | lvalue ADD_ASSIGN expr | lvalue SUB_ASSIGN expr | lvalue '=' expr | FUNC_NAME '(' expr_list_opt ')' /* no white space allowed before '(' */ | BUILTIN_FUNC_NAME '(' expr_list_opt ')' | BUILTIN_FUNC_NAME | non_unary_input_function ; print_expr_list_opt : /* empty */ | print_expr_list ; print_expr_list : print_expr | print_expr_list ',' newline_opt print_expr ; print_expr : unary_print_expr | non_unary_print_expr ; unary_print_expr : '+' print_expr | '-' print_expr | unary_print_expr '^' print_expr | unary_print_expr '*' print_expr | unary_print_expr '/' print_expr | unary_print_expr '%' print_expr | unary_print_expr '+' print_expr | unary_print_expr '-' print_expr | unary_print_expr non_unary_print_expr | unary_print_expr '~' print_expr | unary_print_expr NO_MATCH print_expr | unary_print_expr In NAME | unary_print_expr AND newline_opt print_expr | unary_print_expr OR newline_opt print_expr | unary_print_expr '?' print_expr ':' print_expr ; non_unary_print_expr : '(' expr ')' | '!' print_expr | non_unary_print_expr '^' print_expr | non_unary_print_expr '*' print_expr | non_unary_print_expr '/' print_expr | non_unary_print_expr '%' print_expr | non_unary_print_expr '+' print_expr | non_unary_print_expr '-' print_expr | non_unary_print_expr non_unary_print_expr | non_unary_print_expr '~' print_expr | non_unary_print_expr NO_MATCH print_expr | non_unary_print_expr In NAME | '(' multiple_expr_list ')' In NAME | non_unary_print_expr AND newline_opt print_expr | non_unary_print_expr OR newline_opt print_expr | non_unary_print_expr '?' print_expr ':' print_expr | NUMBER | STRING | lvalue | ERE | lvalue INCR | lvalue DECR | INCR lvalue | DECR lvalue | lvalue POW_ASSIGN print_expr | lvalue MOD_ASSIGN print_expr | lvalue MUL_ASSIGN print_expr | lvalue DIV_ASSIGN print_expr | lvalue ADD_ASSIGN print_expr | lvalue SUB_ASSIGN print_expr | lvalue '=' print_expr | FUNC_NAME '(' expr_list_opt ')' /* no white space allowed before '(' */ | BUILTIN_FUNC_NAME '(' expr_list_opt ')' | BUILTIN_FUNC_NAME ; lvalue : NAME | NAME '[' expr_list ']' | '$' expr ; non_unary_input_function : simple_get | simple_get '<' expr | non_unary_expr '|' simple_get ; unary_input_function : unary_expr '|' simple_get ; simple_get : GETLINE | GETLINE lvalue ; newline_opt : /* empty */ | newline_opt NEWLINE ;
This grammar has several ambiguities that are resolved as follows:
- Operator precedence and associativity are as described in
.
- In case of ambiguity, an else will be associated with the most immediately preceding if that would satisfy the grammar.
- In some contexts, a slash (/) that is used to surround an ERE could also be the division operator. This is resolved in such a way that wherever the division operator could appear, a slash is assumed to be the division operator. (There is no unary division operator.)
One convention that might not be obvious from the formal grammar is where newline characters are acceptable. There are several obvious placements such as terminating a statement, and a backslash can be used to escape newline characters between any lexical tokens. In addition, newline characters without backslashes can follow a comma, an open brace, logical AND operator (&&), logical OR operator (||), the do keyword, the else keyword, and the closing parenthesis of an if, for or while statement. For example:
{ print $1, $2 }
Lexical Conventions
The lexical conventions for awk programs, with respect to the preceding grammar, are as follows:
- Except as noted, awk will recognise the longest possible token or delimiter beginning at a given point.
- A comment consists of any characters beginning with the number sign character and terminated by, but excluding the next occurrence of, a newline character. Comments will have no effect, except to delimit lexical tokens.
- The character newline will be recognised as the token NEWLINE.
- A backslash character immediately followed by a newline character will have no effect.
- The token STRING represents a string constant. A string constant begins with the character . Within a string constant, a backslash character will be considered to begin an escape sequence as specified in the table in the XBD specification, File Format Notation (\\, \a, \b, \f, \n, \r, \t, \v). In addition, the escape sequences in
will be recognised. A newline character will not occur within a string constant. A string constant will be terminated by the first unescaped occurrence of the character after the one that begins the string constant. The value of the string will be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting characters.
- The token ERE represents an extended regular expression constant. An ERE constant begins with the slash character. Within an ERE constant, a backslash character will be considered to begin an escape sequence as specified in the table in the XBD specification, File Format Notation . In addition, the escape sequences in
will be recognised. A newline character must not occur within an ERE constant. An ERE constant will be terminated by the first unescaped occurrence of the slash character after the one that begins the string constant. The extended regular expression represented by the ERE constant will be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting slash characters.
- A blank character has no effect, except to delimit lexical tokens or within STRING or ERE tokens.
- The token NUMBER represents a numeric constant. Its form and numeric value are equivalent to either of the tokens floating-constant or integer-constant as specified by the ISO C standard, with the following exceptions:
- An integer constant cannot begin with 0x or include the hexadecimal digits a, b, c, d, e, f, A, B, C, D, E or F.
- The value of an integer constant beginning with 0 will be taken in decimal rather than octal.
- An integer constant cannot include a suffix (u, U, l or L).
- A floating constant cannot include a suffix (f, F, l or L).
If the value is too large or too small to be representable, the behaviour is undefined.
- A sequence of underscores, digits and alphabetics from the portable character set (see the XBD specification, Portable Character Set ), beginning with an underscore or alphabetic, will be considered a word.
- The following words are keywords that will be recognised as individual tokens; the name of the token is the same as the keyword:
BEGIN delete for in printf END do function next return break else getline while continue exit if
- The following words are names of built-in functions and will be recognised as the token BUILTIN_FUNC_NAME:
atan2 index match sprintf substr close int rand sqrt system cos length sin srand tolower exp log split sub toupper gsub The above-listed keywords and names of built-in functions are considered reserved words.
- The token NAME consists of a word that is not a keyword or a name of a built-in function and is not followed immediately (without any delimiters) by the "(" character.
- The token FUNC_NAME consists of a word that is not a keyword or a name of a built-in function, followed immediately (without any delimiters) by the "(" character. The "(" character will not be included as part of the token.
- The following two-character sequences will be recognised as the named tokens:
Token Name Sequence Token Name Sequence ADD_ASSIGN += NO_MATCH !~ SUB_ASSIGN -= EQ == MUL_ASSIGN *= LE <= DIV_ASSIGN /= GE >= MOD_ASSIGN %= NE != POW_ASSIGN ^= INCR ++ OR || DECR -- AND && APPEND >>
- The following single characters will be recognised as tokens whose names are the character:
<newline> { } ( ) [ ] , ; + - * % ^ ! > < | ? : ~ $ =
There is a lexical ambiguity between the token ERE and the tokens "/" and DIV_ASSIGN. When an input sequence begins with a slash character in any syntactic context where the token "/" or DIV_ASSIGN could appear as the next token in a valid program, the longer of those two tokens that can be recognised will be recognised. In any other syntactic context where the token ERE could appear as the next token in a valid program, the token ERE will be recognised.
The following exit values are returned:
- 0
- All input files were processed successfully.
- >0
- An error occurred.
The exit status can be altered within the program by using an exit expression.
If any file operand is specified and the named file cannot be accessed, awk will write 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 the EXTENDED DESCRIPTION section), the behaviour is undefined.
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.
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 an 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:prints all lines from the standard input containing a single-quote character, prefixed with quote:.awk '/'\"/ { print "quote:", $0 }'
The following are examples of simple awk 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 }
- Add up first column, print sum and average:
{s += $1 } END {print "sum is ", s, " average is", s/NR}
- Write fields in reverse order, one per line (many lines out for each line in):
{ for (i = NF; i > 0; --i) print $i }
- Write all lines between occurrences of the strings start and stop:
/start/, /stop/
- Write all lines whose first field is different from the previous one:
$1 != prev { print; prev = $1 }
- Simulate echo :
BEGIN { for (i = 1; i < ARGC; ++i) printf("%s%s", ARGV[i], i==ARGC-1?"\n":" ") }
- 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] }
- If there is a file named input containing page headers of the form:
and a file named program that contains:
- Page #
then the command line:/Page/ { $2 = n++; } { print }
will print the file input, filling in page numbers starting at 5.awk -f program n=5 input
The IEEE PASC 1003.2 Interpretations Committee has forwarded concerns about parts of this interface definition to the IEEE PASC Shell and Utilities Working Group which is identifying the corrections. A future revision of this specification will align with IEEE Std. 1003.2b when finalised.
grep, lex, sed.