MAN page from Old RedHat 5.X mawk-1.2.2-7.i386.rpm
MAWK
Section: USER COMMANDS (1)
Updated: Dec 22 1994
Index NAME
mawk - pattern scanning and text processing language
SYNOPSIS
mawk[-
Woption][-
Fvalue][-
vvar=value][--] 'program text' [file ...]
mawk[-
Woption][-
Fvalue][-
vvar=value][-
fprogram-file][--] [file ...]
DESCRIPTION
mawkis an interpreter for the AWK Programming Language.The AWK languageis useful for manipulation of data files,text retrieval and processing,and for prototyping and experimenting with algorithms.
mawkis a
new awk meaning it implements the AWK language asdefined in Aho, Kernighan and Weinberger,
The AWK Programming Language,Addison-Wesley Publishing, 1988. (Hereafter referred to asthe AWK book.)
mawkconforms to the Posix 1003.2(draft 11.3)definition of the AWK languagewhich contains a few features not described in the AWKbook, and
mawkprovides a small number of extensions.
An AWK program is a sequence of pattern {action} pairs andfunction definitions.Short programs are entered on the command lineusually enclosed in ' ' to avoid shellinterpretation.Longer programs can be read in from afile with the -f option.Data input is read from the list of files onthe command line or from standard input when the list is empty.The input is broken into records as determined by therecord separator variable, RS. Initially,RS= "\n" and records are synonymous with lines.Each record is compared against eachpatternand if it matches, the program text for{action}is executed.
OPTIONS
- -F value
- sets the field separator, FS, to value.
- -f file
- Program text is read from file
instead of from thecommand line. Multiple-foptions are allowed.- -v var=value
- assigns valueto program variable var.
- --
- indicates the unambiguous end of options.
The above options will be available with any Posix compatibleimplementation of AWK, and implementation specific options areprefaced with-W.mawk provides six:
- -W version
- mawkwrites its version and copyrightto stdout and compiled limits tostderr and exits 0.
- -W dump
- writes an assembler like listing of the internalrepresentation of the program to stdout and exits 0 (on successful compilation).
- -W interactive
- sets unbuffered writes to stdout and line buffered reads from stdin.Records from stdin are lines regardless of the value ofRS.
- -W exec file
- Program text is read from file
and this is the last option. Useful on systems that support the#!"magic number" convention for executable scripts.- -W sprintf=num
- adjusts the size of mawk'sinternal sprintf buffer to numbytes. More than rare use of this option indicatesmawkshould be recompiled.
- -W posix_space
- forcesmawknot to consider '\n' to be space.
The short forms -W[vdiesp]are recognized and on some systems -We is mandatory to avoidcommand line length limitations.
THE AWK LANGUAGE
1. Program structure
An AWK program is a sequence of
pattern {action} pairs and userfunction definitions.
A pattern can be:
- BEGINENDexpressionexpression , 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.
BEGINand
ENDpatterns require an action.
Statements are terminated by newlines, semi-colons or both.Groups of statements such asactions or loop bodies are blocked via { ... } as in C. Thelast statement in a block doesn't need a terminator. Blank lineshave no meaning; an empty statement is terminated with asemi-colon. Long statementscan be continued with a backslash, \. A statement can be brokenwithout a backslash after a comma, left brace, &&, ||, do,else,the right parenthesis of an if,while orforstatement, and theright parenthesis of a function definition.A comment starts with # and extends to, but does not includethe end of line.
The following statements control program flow inside blocks.
if ( expr )statement
if ( expr )statementelse statement
while( expr )statement
dostatementwhile( expr )
for(opt_expr ;opt_expr ;opt_expr )statement
for( var in array )statement
continue
break
2. Data types, conversion and comparison
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 allcomputations are done in floating point arithmetic.So for example, the expression0.2e2 == 20is 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.,
mawkignores the escape.
There are really three basic data types; the third is number and stringwhich has both a numeric value and a string valueat the same time.User defined variables come into existence when first referencedand 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. (See section 4).
The type of an expression is determined by its context and automatictype conversion occurs if needed. For example, to evaluate thestatements
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 to2 and stored in y. The value stored in variable z will be typedstring, and the value of x will be converted to string if necessaryand concatenated with "hello". (Of course, the value and typestored in x is not changed by any conversions.)A string expression is converted to numeric using its longestnumeric prefix as with
atof(3).A numeric expression is converted to string by replacing
exprwith
sprintf(CONVFMT,
expr),unless
exprcan be represented on the host machine as an exact integer thenit is converted to
sprintf("%d",
expr).
Sprintf()is an AWK built-in that duplicates the functionality of
sprintf(3),and
CONVFMTis a built-in variable used for internal conversionfrom number to string and initialized to "%.6g".Explicit type conversions can be forced,
expr ""is string and
expr+0is numeric.
To evaluate,expr1 rel-op expr2,if both operands are numeric or number and string then the comparisonis numeric; if both operands are string the comparison is string;if one operand is string, the non-string operand is converted andthe 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 theempty string ""; numeric values if and only if not numerically zero.
3. Regular expressions
In the AWK language, records, fields and strings are oftentested 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 stringsdefined 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,
actionis executed.In fact, /
r/ is an AWK expression that isequivalent to (
$0 ~ /
r/) anywhere except when on theright side of a match operator or passed as an argument toa built-in function that expects a regular expression argument.
AWK uses extended regular expressions as withegrep(1).The regular expression metacharacters, i.e., those with specialmeaning in regular expressions are
^ $ . [ ] | ( ) * + ?
Regular expressions are built up from characters as follows:
- c
- matches any non-metacharacterc.
- \c
- matches a character defined by the same escape sequences usedin string constants or the literalcharacterc if\cis 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 classc1c2c3... . An interval of characters is denotedc1-c2 inside a class [...].
- [^c1c2c3...]
- matches any character not in the classc1c2c3...
Regular expressions are built up from other regular expressionsas follows:
- r1r2
- matches r1followed immediately byr2(concatenation).
- r1 | r2
- matches r1 orr2(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 andunary (*, + 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 constantsrespectively. Note that . has to be escaped to berecognized as a decimal point, and that metacharacters are notspecial inside character classes.
Any expression can be used on the right hand side of the ~ or !~operators orpassed to a built-in that expectsa regular expression.If needed, it is converted to string, and then interpretedas a regular expression. For example,
BEGIN { identifier = "[_a-zA-Z][_a-zA-Z0-9]*" } $0 ~ "^" identifierprints all lines that start with an AWK identifier.
mawkrecognizes the empty regular expression, //, which matches theempty string and hence is matched by any string at the front,back and between every character. For example,
echo abc | mawk { gsub(//, "X") ; print } XaXbXcX 4. Records and fields
Records are read in one at a time, and stored in the
fieldvariable
$0.The record is split into
fieldswhich are stored in
$1,
$2, ...,
$NF.The built-in variable
NFis set to the number of fields,and
NRand
FNRare incremented by 1.Fields above
$NFare set to "".
Assignment to$0causes the fields and NFto be recomputed.Assignment toNFor to a fieldcauses $0to be reconstructed byconcatenating the$i'sseparated byOFS.Assignment to a field with index greater thanNF,increasesNFand causes$0to be reconstructed.
Data input stored in fieldsis string, unless the entire field has numericform and then the type is number and string.For example,
echo 24 24E | mawk '{ print($1>100, $1>"100", $2>100, $2>"100") }' 0 1 1 1$0and$2are string and$1is 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.
5. Expressions and operators
The expression syntax is similar to C. Primary expressions are numeric constants,string constants, variables, fields, arrays and function calls. The identifierfor a variable, array or function can be a sequence ofletters, digits and underscores, that doesnot start with a digit.Variables are not declared; they exist when first referenced andare initialized tonull.
Newexpressions are composed with the following operators inorder of increasing precedence.
assignment = += -= *= /= %= ^=conditional ? :logical or ||logical and &&array membership inmatching ~ !~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 toleft; the other operators associate left to right. Anyexpression can be parenthesized.
6. Arrays
Awk provides one-dimensional arrays. Array elements are expressedas
array[
expr].
Expris internally converted to string type, so, for example,A[1] and A["1"] are the same element and the actualindex is "1".Arrays indexed by strings are called associative arrays.Initially an array is empty; elements exist when first accessed.An expression,
expr in arrayevaluates to 1 if
array[
expr]exists, else to 0.
There is a form of theforstatement that loops over each index of an array.
for ( var in array ) statement
sets
varto each index of
arrayand executes
statement.The order that
vartransverses the indices of
arrayis not defined.
The statement,deletearray[expr],causesarray[expr]not to exist.mawk supports an extension,delete array,which deletes all elements of array.
Multidimensional arrays are synthesized with concatenation usingthe built-in variableSUBSEP.array[expr1,expr2]is equivalent toarray[expr1 SUBSEP expr2].Testing for a multidimensional element uses a parenthesized index,such as
if ( (i, j) in A ) print A[i, j]
7. Builtin-variables
The following variables are built-in and initialized before programexecution.
- 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 inFILENAME.
- FS
- splits records into fields as a regular expression.
- 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 tomatch().
- SUBSEP
- used to build multiple array subscripts, initially = "\034".
8. Built-in functions
String functions
- gsub(r,s,t) gsub(r,s)
- Global substitution, every match of regular expressionrin variable tis replaced by strings.The number of replacements is returned.If tis omitted,$0 is used. An & in the replacement stringsis replaced by the matched substring oft.\& and \\ put literal & and \, respectively,in the replacement string.
- index(s,t)
- If tis a substring ofs,then the position where tstarts is returned, else 0 is returned.The first character ofsis in position 1.
- length(s)
- Returns the length of strings.
- match(s,r)
- Returns the index of the first longest match of regular expressionrin strings.Returns 0 if no match.As a side effect,RSTARTis set to the return value.RLENGTHis set to the length of the match or -1 if no match. If theempty string is matched, RLENGTHis set to 0, and 1 is returned if the match is at the front, andlength(s)+1 is returned if the match is at the back.
- split(s,A,r) split(s,A)
- Stringsis split into fields by regular expressionrand the fields are loaded into arrayA.The number of fieldsis returned. See section 11 below for more detail.Ifris omitted, FSis used.
- sprintf(format,expr-list)
- Returns a string constructed fromexpr-listaccording toformat.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 strings,starting at index i,of lengthn.If nis omitted, the suffix ofs,starting atiis returned.
- tolower(s)
- Returns a copy ofswith all upper case characters converted to lower case.
- toupper(s)
- Returns a copy ofswith all lower case characters converted to upper case.
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 ifexpris omitted, and returns the value of the previous seed.mawkseeds the random number generator from the clock at startupso there is no real need to call srand(). Srand(expr)is useful for repeating pseudo random sequences.
9. Input and output
There are two output statements, printand
printf.
- print
- writes$0 ORSto standard output.
- print expr1, expr2, ..., exprn
- writesexpr1 OFS expr2 OFS ... exprnORSto standard output. Numeric expressions are converted tostring with OFMT.
- printf format, expr-list
- duplicates the printf C library function writing to standard output.The complete ANSI C format specifications are recognized withconversions %c, %d, %e, %E, %f, %g, %G,%i, %o, %s, %u, %x, %X and %%,and conversion qualifiers h and l.
The argument list to print or printf can optionally be enclosed inparentheses.Print formats numbers usingOFMTor "%d" for exact integers."%c" with a numeric argument prints the corresponding 8 bit character, with a string argument it prints the first character ofthe string.The output of print and printf can be redirected to a file orcommand by appending > file,>>fileor|commandto the end of the print statement.Redirection opens fileorcommandonly once, subsequent redirections append to the already open stream.By convention, mawkassociates the filename "/dev/stderr" with stderr which allowsprint and printf to be redirected to stderr.mawkalso associates "-" and "/dev/stdout" with stdin and stdout whichallows these streams to be passed to functions.
The input functiongetlinehas the following variations.
- getline
- reads into$0,updates the fields,NF,NRand FNR.
- getline < file
- reads into$0from file, updates the fields andNF.
- getline var
- reads the next record intovar
,updatesNRandFNR.- getline var < file
- reads the next record offile
intovar.- command | getline
- pipes a record from commandinto$0and updates the fields andNF.
- command | getline var
- pipes a record from command
intovar.
Getline returns 0 on end-of-file, -1 on error, otherwise 1.
Commands on the end of pipes are executed by /bin/sh.
The function close(expr) closes the file or pipeassociated withexpr.Close returns 0 ifexpris an open file,the exit status ifexpris a piped command, and -1 otherwise.Close is used to reread a file or command, make sure the otherend of an output pipe is finished or conserve file resources.
The function fflush(expr) flushes the output file or pipeassociated withexpr.Fflush returns 0 ifexpris an open output stream else -1.Fflush without an argument flushes stdout.
The function system(expr)uses /bin/shto executeexprand returns the exit status of the commandexpr.Changes made to theENVIRONarray are not passed to commands executed withsystemor pipes.
10. User defined functions
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 valueand arrays by reference.Extra arguments serve as local variablesand are initialized to
null.For example, csplit(
s,A) puts each character of
sinto array
Aand returns the length of
s.
function csplit(s, A, n, i) { n = length(s) for( i = 1 ; i <= n ; i++ ) A[i] = substr(s, i, 1) return n }Putting extra space between passed arguments and local variables is conventional.Functions can be referenced before they are defined, but thefunction name and the '(' of the arguments must touch toavoid confusion with concatenation.
11. Splitting strings, records and files
Awk programs use the same algorithm to split strings into arrays with split(), and records into fieldson FS.
mawkuses essentially the same algorithm to split files intorecords on
RS.
Split(expr,A,sep) works as follows:
- (1)
- Ifsepis omitted, it is replaced byFS.Sep can be an expression or regular expression. If it is anexpression of non-string type, it is converted to string.
- (2)
- Ifsep= " " (a single space),then <SPACE> is trimmed from the front and back of expr,andsepbecomes <SPACE>.mawkdefines <SPACE> as the regular expression/[ \t\n]+/. Otherwisesepis treated as a regular expression, except that meta-charactersare ignored for a string of length 1,e.g.,split(x, A, "*") and split(x, A, /\*/) are the same.
- (3)
- If expr is not string, it is converted to string.If expr is then the empty string "", split() returns 0and Ais set empty.Otherwise,all non-overlapping, non-null and longest matches ofsepinexpr,separateexprinto fields which are loaded intoA.The fields are placed inA[1], A[2], ..., A[n] and split() returns n, the numberof fields which is the number of matches plus one.Data placed in Athat looks numeric is typed number and string.
Splitting records into fields works the same except thepieces are loaded into $1,$2,...,$NF.If$0is empty,NFis set to 0 and all$ito "".
mawksplits files into records by the same algorithm, but with the slight difference that RSis really a terminator instead of a separator. (ORS is really a terminator too).
E.g., if FS= ":+" and$0= "a::b:" , thenNF= 3 and$1= "a",$2= "b" and$3= "", butif "a::b:" is the contents of an input file andRS= ":+", thenthere are two records "a" and "b".
RS= " " is not special.
If FS = "", thenmawkbreaks the record into individual characters, and, similarly,split(s,A,"") places the individual characters ofsinto A.
12. Multi-line records
Since mawkinterprets
RSas a regular expression, multi-linerecords are easy. Setting
RS= "\n\n+", makes one or more blanklines separate records. If
FS= " " (the default), then singlenewlines, by the rules for <SPACE> above, become space andsingle newlines are field separators.
For example, if a file is "a b\nc\n\n",RS= "\n\n+" andFS= " ", then there is one record "a b\nc" with threefields "a", "b" and "c". ChangingFS= "\n", gives twofields "a b" and "c"; changingFS= "", gives one fieldidentical to the record.
If you want lines with spaces or tabs to be considered blank,setRS= "\n([ \t]*\n)+".For compatibility with other awks, settingRS= "" has the sameeffect as if blank lines are stripped from thefront and back of files and then records are determined as ifRS= "\n\n+".Posix requires that "\n" always separates records whenRS= "" regardless of the value ofFS.mawk does not support this convention, because defining"\n" as <SPACE> makes it unnecessary.
Most of the time when you changeRSfor multi-line records, youwill also want to change ORSto "\n\n" so the record spacing is preserved on output.
13. Program execution
This section describes the order of program execution.First ARGCis set to the total number of command line arguments passed tothe execution phase of the program.
ARGV[0]is set the name of the AWK interpreter and
ARGV[1] ...
ARGV[ARGC-1]holds the remaining command line arguments exclusive of options and program source.For example with
mawk -f prog v=1 A t=hello B
ARGC= 5 with
ARGV[0]= "mawk",
ARGV[1]= "v=1",
ARGV[2]= "A",
ARGV[3]= "t=hello" and
ARGV[4]= "B".
Next, each BEGINblock is executed in order.If the program consistsentirely of BEGINblocks, then execution terminates, elsean input stream is opened and execution continues.If ARGCequals 1,the input stream is set to stdin,else the command line argumentsARGV[1] ... ARGV[ARGC-1]are examined for a file argument.
The command line arguments divide into three sets: file arguments, assignment arguments and empty strings "".An assignment has the formvar=string.When an ARGV[i]is examined as a possible file argument,if it is empty it is skipped;if it is an assignment argument, the assignment tovartakes place and iskips to the next argument;elseARGV[i] is opened for input.If it fails to open, execution terminates with exit code 2.If no command line argument is a file argument, then inputcomes from stdin.Getline in a BEGINaction opens input. "-" as a file argument denotes stdin.
Once an input stream is open, each input record is tested against each pattern,and if it matches, the associated actionis executed.An expression pattern matches if it is boolean true (seethe end of section 2).A BEGINpattern matches before any input has been read, andanENDpattern matches after all input has been read.A range pattern,expr1,expr2 ,matches every record between the match of expr1and the matchexpr2inclusively.
When end of file occurs on the input stream, the remainingcommand line arguments are examined for a file argument, andif there is one it is opened, else theENDpatternis considered matchedand all ENDactionsare executed.
In the example, the assignmentv=1takes place after theBEGINactionsare executed, andthe data placed invis typed number and string.Input is then read from file A.On end of file A,tis set to the string "hello",and B is opened for input.On end of file B, the ENDactionsare executed.
Program flow at thepattern{action}level can be changed with the
next exit opt_expr
statements.A
nextstatementcauses the next input record to be read and pattern testingto restart with the first
pattern {action}pair in the program.An
exitstatementcauses immediate execution of the
ENDactions or program termination if there are none orif the
exitoccurs in an
ENDaction.The
opt_exprsets the exit value of the program unless overridden bya later
exitor subsequent error.
EXAMPLES
1. emulate cat. { print }2. emulate wc. { chars += length($0) + 1 # add one for the \n words += NF } END{ print NR, words, chars }3. count the number of unique "real words". BEGIN { FS = "[^A-Za-z]+" } { for(i = 1 ; i <= NF ; i++) word[$i] = "" } END { delete word[""] for ( i in word ) cnt++ print cnt }4. sum the second field of every record based on the first field.
$1 ~ /credit|gain/ { sum += $2 } $1 ~ /debit|loss/ { sum -= $2 } END { print sum }5. sort a file, comparing as string { line[NR] = $0 "" } # make sure of comparison type # in case some lines look numeric END { isort(line, NR) for(i = 1 ; i <= NR ; i++) print line[i] } #insertion sort of A[1..n] function isort( A, n, i, j, hold) { for( i = 2 ; i <= n ; i++) { hold = A[j = i] while ( A[j-1] > hold ) { j-- ; A[j+1] = A[j] } A[j] = hold } # sentinel A[0] = "" will be created if needed } COMPATIBILITY ISSUES
The Posix 1003.2(draft 11.3) definition of the AWK languageis AWK as described in the AWK book with a few extensionsthat appeared in SystemVR4 nawk. The extensions are:
- New functions: toupper() and tolower().
New variables: ENVIRON[] and CONVFMT.
ANSI C conversion specifications for printf() and sprintf().
New command options: -v var=value, multiple -f options andimplementation options as arguments to -W.
Posix AWK is oriented to operate on files a line at a time.RScan be changed from "\n" to another single character,but itis hard to find any use for this --- there are no examples in the AWK book.By convention, RS = "", makes one or more blank linesseparate records, allowing multi-line records. WhenRS = "", "\n" is always a field separator regardless of the value inFS.
mawk,on the other hand,allowsRSto be a regular expression.When "\n" appears in records, it is treated as space, andFSalways determines fields.
Removing the line at a time paradigm can make some programssimpler and canoften improve performance. For example,redoing example 3 from above,
BEGIN { RS = "[^A-Za-z]+" } { word[ $0 ] = "" } END { delete word[ "" ] for( i in word ) cnt++ print cnt }counts the number of unique words by making each word a record.On moderate size files,
mawkexecutes twice as fast, because of the simplified inner loop.
The following program replaces each comment by a single space ina C program file,
BEGIN { RS = "/\*([^*]|\*+[^/*])*\*+/" # comment is record separator ORS = " " getline hold } { print hold ; hold = $0 } END { printf "%s" , hold }Buffering one record is needed to avoid terminating the lastrecord with a space.
With mawk,the following are all equivalent,
x ~ /a\+b/ x ~ "a\+b" x ~ "a\\+b"
The strings get scanned twice, once as string and once asregular expression. On the string scan,
mawkignores the escape on non-escape characters while the AWKbook advocates
\cbe recognized as
c which necessitates the double escaping of meta-characters instrings. Posix explicitly declines to define the behavior which passivelyforces programs that must run under a variety of awks to usethe more portable but less readable, double escape.
Posix AWK does not recognize "/dev/std{out,err}" or \x hex escapesequences in strings. Unlike ANSI C,mawklimits the number of digits that follows \x to two as the currentimplementation only supports 8 bit characters.The built-infflushfirst appeared in a recent (1993) AT&T awk released to netlib, and isnot part of the posix standard. Aggregate deletion withdeletearrayis not part of the posix standard.
Posix explicitly leaves the behavior of FS= "" undefined, and mentions splitting the record into characters asa possible interpretation, but currently this use is not portableacross implementations.
Finally, here is how mawkhandles exceptional cases not discussed in theAWK book or the Posix draft. It is unsafe to assume consistency across awks and safe to skip tothe next section.
- substr(s, i, n) returns the characters of s in the intersectionof the closed interval [1, length(s)] and the half-open interval[i, i+n). When this intersection is empty, the empty string isreturned; so substr("ABC", 1, 0) = "" andsubstr("ABC", -4, 6) = "A".
Every string, including the empty string, matches the empty stringat thefront so, s ~ // and s ~ "", are always 1 as is match(s, //) andmatch(s, ""). The last two set RLENGTH to 0.
index(s, t) is always the same as match(s, t1) where t1 is thesame as t with metacharacters escaped. Hence consistencywith match requires thatindex(s, "") always returns 1.Also the condition, index(s,t) != 0 if and only t is a substringof s, requires index("","") = 1.
If getline encounters end of file, getline var, leaves varunchanged. Similarly, on entry to the ENDactions, $0,the fields andNFhave their value unaltered from the last record.
SEE ALSO
egrep(1)
Aho, Kernighan and Weinberger,The AWK Programming Language,Addison-Wesley Publishing, 1988, (the AWK book),defines the language, opening with a tutorialand advancing to many interesting programs that delve intoissues of software design and analysis relevant to programmingin any language.
The GAWK Manual,The Free Software Foundation, 1991, is a tutorialand language referencethat does not attempt the depth of the AWK bookand assumes the reader may be a novice programmer. The section on AWK arrays is excellent. It alsodiscusses Posix requirements for AWK.
BUGS
mawkcannot handle ascii NUL \0 in the source or data files. Youcan output NUL using printf with %c, and any other 8 bitcharacter is acceptable input.
mawkimplements printf() and sprintf() using the C library functions,printf and sprintf, so full ANSI compatibility requires an ANSIC library. In practice this means the h conversion qualifier maynot be available. Also mawkinherits any bugs or limitations of the library functions.
Implementors of the AWK language have shown a consistent lackof imagination when naming their programs.
AUTHOR
Mike Brennan (brennanAATTboeing.com).
Index
- NAME
- SYNOPSIS
- DESCRIPTION
- OPTIONS
- THE AWK LANGUAGE
- 1. Program structure
- 2. Data types, conversion and comparison
- 3. Regular expressions
- 4. Records and fields
- 5. Expressions and operators
- 6. Arrays
- 7. Builtin-variables
- 8. Built-in functions
- 9. Input and output
- 10. User defined functions
- 11. Splitting strings, records and files
- 12. Multi-line records
- 13. Program execution
- EXAMPLES
- COMPATIBILITY ISSUES
- SEE ALSO
- BUGS
- AUTHOR
This document was created byman2html,using the manual pages.