mawk - pattern scanning and text processing language compiled to JavaScript
mawk is an interpreter for the AWK Programming Language. The AWK language is useful for manipulation of data files, text retrieval and pro cessing, and for prototyping and experimenting with algorithms. mawk is a new awk meaning it implements the AWK language as defined in Aho, Kernighan and Weinberger, The AWK Programming Language, Addison-Wesley Publishing, 1988 (hereafter referred to as the AWK book.) mawk conforms to the POSIX 1003.2 (draft 11.3) definition of the AWK language which contains a few features not described in the AWK book, and mawk provides a small number of extensions.
An AWK program is a sequence of pattern {action} pairs and function definitions. Data input is broken into records as determined by the record separator variable, RS. Initially, RS = "\n" and records are synonymous with lines. Each record is compared against each pattern and if it matches, the program text for {action} is executed.
May be invoked with the following command-line options:
-F value
sets the field separator, FS, to value.
-v var=value
assigns value to program variable var.
-W dump
writes an assembler like listing of the internal representation
of the program to stdout and exits 0 (on successful compilation).
-W help
prints a usage message to stderr and exits (same as
-W usage
).
-W posix_space
forces mawk not to consider '\n' to be space.
-W random=num
calls srand with the given parameter (and overrides the
auto-seeding behavior).
-W sprintf=num
adjusts the size of mawk's internal sprintf buffer to
num bytes. More than rare use of this option indicates
mawk should be recompiled.
-W version
mawk writes its version and copyright to stdout and compiled limits to stderr.
mawk accepts abbreviations for any of these options, e.g., -W v
and
-Wv
both tell mawk to show its version.
mawk allows multiple -W
options to be combined by separating the
options with commas, e.g., -Wsprint=2000,posix
.
An AWK program is a sequence of pattern {action} pairs and user function definitions.
A pattern can be:
BEGIN
END
expression
expression , expression
One, but not both, of pattern {action} can be omitted.
If {action} is omitted it is implicitly { print }
.
If pattern is omitted, then it is implicitly matched.
BEGIN and END patterns require an action.
Statements are terminated by newlines, semi-colons or both. Groups of
statements such as actions or loop bodies are blocked via { ... } as in
C. The last statement in a block doesn't need a terminator. Blank
lines have no meaning; an empty statement is terminated with a
semicolon. Long statements can be continued with a backslash, \
.
A statement
can be broken without a backslash after a comma, left brace, &&
,
||
, do
, else
, the right parenthesis of an if
, while
or for
statement,
and the right parenthesis of a function definition. A comment starts
with #
and extends to, but does not include the end of line.
The following statements control program flow inside blocks.
if ( expr ) statement
if ( expr ) statement else statement
while ( expr ) statement
do statement while ( expr )
for ( opt_expr ; opt_expr ; opt_expr ) statement
for ( var in array ) statement
continue
break
There are two basic data types, numeric and string. Numeric constants can be integer like -2, decimal like 1.08, or in scientific notation like -1.1e4 or .28E-3. All numbers are represented internally and all computations are done in floating point arithmetic. So for example, the expression 0.2e2 == 20 is true and true is represented as 1.0.
String constants are enclosed in double quotes: "This is a string with a newline at the end.\n"
Strings can be continued across a line by escaping (\) the newline. The following escape sequences are recognized.
\\ | \ | |
\" | " | |
\a | alert, ascii 7 | |
\b | backspace, ascii 8 | |
\t | tab, ascii 9 | |
\n | newline, ascii 10 | |
\v | vertical tab, ascii 11 | |
\f | formfeed, ascii 12 | |
\r | carriage return, ascii 13 | |
\ddd | 1, 2 or 3 octal digits for ascii ddd | |
\xhh | 1 or 2 hex digits for ascii hh |
If you escape any other character \c, you get \c, i.e., mawk ignores the escape.
There are really three basic data types; the third is number and string which has both a numeric value and a string value at the same time. User defined variables come into existence when first referenced and are initialized to null, a number and string value which has numeric value 0 and string value "". Non-trivial number and string typed data come from input and are typically stored in fields.
The type of an expression is determined by its context and automatic type conversion occurs if needed. For example, to evaluate the statements:
y = x + 2 ; z = x "hello"
the value stored in variable y will be typed numeric. If x is not
numeric, the value read from x is converted to numeric before it is
added to 2 and stored in y. The value stored in variable z will be
typed string, and the value of x will be converted to string if necessary and concatenated with "hello". (Of course, the value and type
stored in x is not changed by any conversions.) A string expression is
converted to numeric using its longest numeric prefix as with atof
.
A numeric expression is converted to string by replacing expr with
sprintf(CONVFMT, expr), unless expr can be represented on the host
machine as an exact integer then it is converted to sprintf("%d",
expr). Sprintf() is an AWK built-in that duplicates the functionality
of sprintf
, and CONVFMT is a built-in variable used for internal
conversion from number to string and initialized to "%.6g". Explicit
type conversions can be forced, expr "" is string and expr+0 is
numeric.
To evaluate, expr1 rel-op expr2, if both operands are numeric or number and string then the comparison is numeric; if both operands are string the comparison is string; if one operand is string, the non-string op- erand is converted and the comparison is string. The result is numeric, 1 or 0.
In boolean contexts such as, if ( expr ) statement
, a string expression
evaluates true if and only if it is not the empty string ""; numeric
values if and only if not numerically zero.
In the AWK language, records, fields and strings are often tested for matching a regular expression. Regular expressions are enclosed in slashes, and
expr ~ /r/
is an AWK expression that evaluates to 1 if expr "matches" r, which means a substring of expr is in the set of strings defined by r. With no match the expression evaluates to 0; replacing ~ with the "not match" operator, !~ , reverses the meaning. As pattern-action pairs,
/r/ { action }
and $0 ~ /r/ { action }
are the same, and for each input record that matches r, action is executed.
In fact, /r/
is an AWK expression that is equivalent to $0 ~
/r/
anywhere except when on the right side of a match operator or
passed as an argument to a built-in function that expects a regular
expression argument.
AWK uses extended regular expressions as with egrep. The regular expression metacharacters, i.e., those with special meaning in regular expressions are
^ $ . [ ] | ( ) * + ?
Regular expressions are built up from characters as follows:
c
matches any non-metacharacter c
\c
matches a character defined by the same escape
sequences used in string constants or the literal
character c if \c is not an escape sequence
.
matches any character (including newline)
^
matches the front of a string
$
matches the back of a string
[c1c2c3...]
matches any character in the class c1c2c3... . An
interval of characters is denoted c1-c2 inside a class [...]
[^c1c2c3...]
matches any character not in the class c1c2c3...
r1r2
matches r1 followed immediately by r2 (concatenation)
r1 | r2
matches r1 or r2 (alternation)
r*
matches r repeated zero or more times
r+
matches r repeated one or more times
r?
matches r zero or once
(r)
matches r, providing grouping
The increasing precedence of operators is alternation, concatenation and unary (*, + or ?).
For example:
/^[_a-zA-Z][_a-zA-Z0-9]*$/
and
/^[-+]?([0-9]+\.?|\.[0-9])[0-9]*([eE][-+]?[0-9]+)?$/
are matched by AWK identifiers and AWK numeric constants respectively. Note that "." has to be escaped to be recognized as a decimal point, and that metacharacters are not special inside character classes
Any expression can be used on the right hand side of the ~ or !~ operators or passed to a built-in that expects a regular expression. If needed, it is converted to string, and then interpreted as a regular expression. For example:
prints all lines that start with an AWK identifier
Records are read in one at a time, and stored in the field variable $0. The record is split into fields which are stored in $1, $2, ..., $NF. The built-in variable NF is set to the number of fields, and NR and FNR are incremented by 1. Fields above $NF are set to "".
Assignment to $0 causes the fields and NF to be recomputed. Assignment to NF or to a field causes $0 to be reconstructed by concatenating the $i's separated by OFS. Assignment to a field with index greater than NF, increases NF and causes $0 to be reconstructed.
Data input stored in fields is string, unless the entire field has numeric form and then the type is number and string. For example GIST:
$0 and $2 are string and $1 is number and string. The first comparison is numeric, the second is string, the third is string (100 is converted to "100"), and the last is string.
The expression syntax is similar to C. Primary expressions are numeric constants, string constants, variables, fields, arrays and function calls. The identifier for a variable, array or function can be a sequence of letters, digits and underscores, that does not start with a digit. Variables are not declared; they exist when first referenced and are initialized to null.
New expressions are composed with the following operators in order of increasing precedence.
assignment | = += -= *= /= %= ^= | |
conditional | ? : | |
logical or | || | |
logical and | && | |
array membership | in | |
matching | ~ !~ | |
relational | < > <= >= == != | |
concatenation | (no explicit operator) | |
add ops | + - | |
mul ops | * / % | |
unary | + - | |
logical not | ! | |
exponentiation | ^ | |
inc and dec | ++ -- (both post and pre) | |
field | $ |
Assignment, conditional and exponentiation associate right to left; the other operators associate left to right. Any expression can be parenthesized.
Awk provides one-dimensional arrays. Array elements are expressed as
array[expr]
. Expr is internally converted to string type, so, for
example, A[1]
and A["1"]
are the same element and the actual index is
"1". Arrays indexed by strings are called associative arrays. Initially an array is empty; elements exist when first accessed. An
expression, expr in array evaluates to 1 if array[expr]
exists, else to
0.
There is a form of the for statement that loops over each index of an array.
for ( var in array ) statement
sets var to each index of array and executes statement. The order that var transverses the indices of array is not defined.
The statement, delete array[expr]
, causes array[expr] not to exist.
mawk supports an extension, delete array, which deletes all elements of
array.
Multidimensional arrays are synthesized with concatenation using the
built-in variable SUBSEP. array[expr1,expr2]
is equivalent to
array[expr1 SUBSEP expr2]
. Testing for a multidimensional element uses
a parenthesized index, such as:
if ( (i, j) in A ) print A[i, j]
The following variables are built-in and initialized before program execution.
ARGC
number of command line arguments.
ARGV
array of command line arguments, 0..ARGC-1.
CONVFMT
format for internal conversion of numbers to string,
initially = "%.6g".
ENVIRON
array indexed by environment variables.
An environment string, var=value
is stored as
ENVIRON[var] = value
.
FILENAME
name of the current input file.
FNR
current record number in FILENAME
.
FS
splits records into fields as a regular expression.
NF
number of fields in the current record.
NF
number of fields in the current record.
NR
current record number in the total input stream.
OFMT
format for printing numbers; initially = "%.6g".
OFS
inserted between fields on output, initially = " ".
ORS
terminates each record on output, initially = "\n".
RLENGTH
length set by the last call to the built-in function,
match()
.
RS
input record separator, initially = "\n".
RSTART
index set by the last call to match()
.
SUBSEP
used to build multiple array subscripts, initially =
"\034".
String functions:
gsub(r,s,t)
gsub(r,s)
Global substitution, every match of regular expression r
in variable t is replaced by string s. The number of
replacements is returned. If t is omitted, $0 is used.
An & in the replacement string s is replaced by the
matched substring of t. \& and \\ put literal & and \,
respectively, in the replacement string.
index(s,t)
If t is a substring of s, then the position where t
starts is returned, else 0 is returned. The first char-
acter of s is in position 1.
length(s)
Returns the length of string or array. s.
match(s,r)
Returns the index of the first longest match of regular
expression r in string s. Returns 0 if no match. As a
side effect, RSTART is set to the return value. RLENGTH
is set to the length of the match or -1 if no match. If
the empty string is matched, RLENGTH is set to 0, and 1
is returned if the match is at the front, and length(s)+1
is returned if the match is at the back.
split(s,A,r)
split(s,A)
String s is split into fields by regular expression r and
the fields are loaded into array A. The number of fields
is returned. See section 11 below for more detail. If r
is omitted, FS is used.
sprintf(format,expr-list)
Returns a string constructed from expr-list according to
format. See the description of printf()
below..
sub(r,s,t)
sub(r,s)
Single substitution, same as gsub()
except at most one
substitution.
substr(s,i,n)
substr(s,i)
Returns the substring of string s, starting at index i,
of length n. If n is omitted, the suffix of s, starting
at i is returned.
tolower(s)
Returns a copy of s with all upper case characters
converted to lower case.
toupper(s)
Returns a copy of s with all lower case characters
converted to upper case.
Time functions:
mktime(specification)
converts a date specification to a timestamp with the
same units as systime. The date specification is a
string containing the components of the date as decimal
integers
strftime([format [, timestamp [, utc ]]])
formats the given timestamp using the format (passed to
the C strftime function)
systime()
returns the current time of day as the number of seconds
since the Epoch (1970-01-01 00:00:00 UTC on POSIX systems).
Arithmetic functions:
atan2(y,x)
Arctan of y/x between -pi and pi.
cos(x)
Cosine function, x in radians.
exp(x)
Exponential function.
int(x)
Returns x truncated towards zero.
log(x)
Natural logarithm.
rand()
Returns a random number between zero and one.
sin(x)
Sine function, x in radians.
sqrt(x)
Returns square root of x.
srand(expr)
srand()
Seeds the random number generator, using the clock if
expr is omitted, and returns the value of the previous
seed. srand(expr)
is useful for repeating pseudo random
sequences.
There are two output statements, print
and printf
.
print
writes $0 ORS to standard output.
print expr1, expr2, ..., exprn
writes expr1 OFS expr2 OFS ... exprn ORS to standard output.
Numeric expressions are converted to string with OFMT.
printf format, expr-list
duplicates the printf C library function writing to standard
output. The complete ANSI C format specifications
are recognized with conversions
%c
%d
%e
%E
%f
%g
%G
%i
%o
%s
%u
%x
%X
and %%
and conversion qualifiers h
and l
.
The input function getline
has the following variations.
getline
reads into $0, updates the fields, NF, NR and FNR.
getline var
reads the next record into var, updates NR and FNR.
Getline returns 0 on end-of-file, -1 on error, otherwise 1.
The syntax for a user defined function is:
function name( args ) { statements }
The function body can contain a return statement:
return opt_expr
A return statement is not required. Function calls may be nested or
recursive. Functions are passed expressions by value and arrays by
reference. Extra arguments serve as local variables and are initialized
to null. For example, csplit(s,A)
puts each character of s into
array A and returns the length of s:
Putting extra space between passed arguments and local variables is conventional. Functions can be referenced before they are defined, but the function name and the '(' of the arguments must touch to avoid confusion with concatenation.
A function parameter is normally a scalar value (number or string). If there is a forward reference to a function using an array as a parameter, the function's corresponding parameter will be treated as an array.
Awk programs use the same algorithm to split strings into arrays with
split()
, and records into fields on FS.
mawk uses essentially the same
algorithm to split files into records on RS.
split(expr,A,sep)
works as follows:
If sep is omitted, it is replaced by FS. Sep can be an expression or regular expression. If it is an expression of nonstring type, it is converted to string.
If sep = " " (a single space), then <SPACE> is trimmed from the
front and back of expr, and sep becomes <SPACE>. mawk defines
<SPACE> as the regular expression /[ \t\n]+/
. Otherwise sep is
treated as a regular expression, except that meta-characters
are ignored for a string of length 1, e.g., split(x, A, "*")
and split(x, A, /\*/)
are the same.
If expr is not string, it is converted to string. If expr is
then the empty string "", split()
returns 0 and A is set empty.
Otherwise, all non-overlapping, non-null and longest matches of
sep in expr, separate expr into fields which are loaded into A.
The fields are placed in A[1], A[2], ..., A[n] and split()
returns n, the number of fields which is the number of matches
plus one. Data placed in A that looks numeric is typed number
and string.
Splitting records into fields works the same except the pieces are loaded into $1, $2,..., $NF. If $0 is empty, NF is set to 0 and all $i to "".
If FS = "", then mawk breaks the record into individual characters,
and, similarly, split(s,A,"")
places the individual characters of s
into A.
GIST | In its simplest form, we can use awk like cat to simply print all lines of a text file out to the screen.
GIST | Let's try out awk's search filtering capabilities:
GIST | We can use the action section to specify which pieces of information we want to print. For instance, to print only the first column:
GIST | ARGC implies the number of arguments provided at the command line:
GIST | ARGV is an array that stores the command-line arguments. The array's valid index ranges from 0 to ARGC-1:
GIST | FS represents the (input) field separator and its default value is space. You can also change this by using -F command line option:
GIST | NF represents the number of fields in the current record:
GIST | NR represents the number of the current record. For instance, the following example prints only the first two records:
AWK has associative arrays and one of the best thing about it is – the indexes need not to be continuous set of number; you can use either string or number as an array index. Also, there is no need to declare the size of an array in advance – arrays can expand/shrink at runtime.
GIST | To gain more insight on array, let us create and access the elements of an array:
GIST | The following example deletes the element orange:
AWK only supports one-dimensional arrays. But you can easily simulate a multi-dimensional array using the one-dimensional array itself.
GIST | The following example simulates a 2-D array:
GIST | Initially, the for statement performs initialization action, then it checks the condition. If the condition is true, it executes actions, thereafter it performs increment or decrement operation. The loop execution continues as long as the condition is true. For instance, the following example prints 1 to 5 using for loop:
GIST | The following example prints 1 to 3 using while loop:
GIST | The following example prints 1 to 5 numbers using do-while loop:
GIST | Here is an example which ends the loop when the sum becomes greater than 50:
GIST | The following example uses continue statement to print the even numbers between 1 to 20:
GIST | Let us write two functions that calculate the minimum and the maximum number and call these functions from another function called main: