You are on page 1of 15

pecially when they are databases.

The new version of awk, called nawk, provides additional


capabilities.[1] Every modern Unix system comes with a version of new awk, and its use is
recommended over old awk.
[1] It really isnt so new. The additional features were added in 1!"#, and it was first shipped
with $ystem % &elease '.1 in 1!"(. )evertheless, the name was never chan*ed on most systems.
+ifferent systems vary in what the two versions are called. $ome have oawk and awk, for the old
and new versions, respectively. ,thers have awk and nawk. $till others only have awk, which is
the new version. This example shows what happens if your awk is the old one-
$ awk 1 /dev/null
awk: syntax error near line 1
awk: bailing out near line 1
awk exits silently if it is the new version.
$ource code for the latest version of awk, from .ell /abs, can be downloaded startin* at .rian
0erni*hans home pa*e- http://cm.bell-labs.com/~bwk. 1ichael .rennans mawk is available via
anonymous 2T3 from ftp://ftp.whidbey.net/pub/brennan/mawk1.3.3.tar.gz. 2inally, the 2ree
$oftware 2oundation has a version of awk called gawk, available from
ftp://gnudist.gnu.org/gnu/gawk/gawk-3.0.4.tar.gz. 4ll three pro*rams implement 5new5 awk.
Thus, references below such as 5nawk only,5 apply to all three. gawk has additional features.
6ith ori*inal awk, you can-
Thin7 of a text file as made up of records and fields in a textual database.
3erform arithmetic and strin* operations.
Use pro*rammin* constructs such as loops and conditionals.
3roduce formatted reports.
6ith nawk, you can also-
+efine your own functions.
Execute Unix commands from a script.
3rocess the results of Unix commands.
3rocess command8line ar*uments more *racefully.
6or7 more easily with multiple input streams.
2lush open output files and pipes 9latest .ell /abs awk:.
In addition, with ;)U awk 9gawk:, you can-
Use re*ular expressions to separate records, as well as fields.
$7ip to the start of the next file, not <ust the next record.
3erform more powerful strin* substitutions.
&etrieve and format system time values.
11.2 Command-Line Syntax
The syntax for invo7in* awk has two forms-
awk [options] 'script' var=value file(s)
awk [options] -f scriptfile var=value file(s)
=ou can specify a script directly on the command line, or you can store a script in a scriptfile and
specify it with -f. nawk allows multiple -f scripts. %ariables can be assi*ned a value on the
command line. The value can be a literal, a shell variable 9$name:, or a command substitution
9`cmd`:, but the value is available only after the BEG! statement is executed.
awk operates on one or more files. If none are specified 9or if - is specified:, awk reads from the
standard input.
The reco*ni>ed options are-
-fs
$et the field separator to fs. This is the same as settin* the system variable "#. ,ri*inal awk
allows the field separator to be only a sin*le character. nawk allows fs to be a re*ular expression.
Each input line, or record, is divided into fields by whitespace 9blan7s or tabs: or by some other
user8definable record separator. 2ields are referred to by the variables $1, $$,..., $n. $% refers to
the entire record.
-! var=value
4ssi*n a !alue to variable !ar. This allows assi*nment before the script be*ins execution
9available in nawk only:.
To print the first three 9colon8separated: fields of each record on separate lines-
awk -F: '{ print $1; print $2; print $3 }' /etc/passwd
1ore examples are shown in the section 5$imple 3attern83rocedure Examples.5
11.3 Patterns and Procedures
awk scripts consist of patterns and procedures-
pattern & procedure '
.oth are optional. If pattern is missin*, & procedure ' is applied to all lines? if & procedure ' is
missin*, the matched line is printed.
11.3.1 Patterns
4 pattern can be any of the followin*-
(regular expression(
relational expression
pattern-matching expression
BEG!
E!)
Expressions can be composed of @uoted strin*s, numbers, operators, functions, defined
variables, or any of the predefined variables described later in the section 5.uilt8in %ariables.5
&e*ular expressions use the extended set of metacharacters and are described in Ahapter
B, "attern $atching.
* and $ refer to the be*innin* and end of a strin* 9such as the fields:, respectively, rather
than the be*innin* and end of a line. In particular, these metacharacters will not match at a
newline embedded in the middle of a strin*.
&elational expressions use the relational operators listed in the section 5,perators5 later in this
chapter. 2or example, $$ + $1 selects lin Chapter 11 The awk
Programming Language
Contents:
Aonceptual ,verview
Aommand8/ine $yntax
3atterns and 3rocedures
.uilt8in %ariables
,perators
%ariables and 4rray 4ssi*nments
User8+efined 2unctions
;roup /istin* of aw7 2unctions and Aommands
Implementation /imits
4lphabetical $ummary of 2unctions and Aommands
11.1 Conceptua !"er"iew
awk is a pattern8matchin* pro*ram for processin* files, especially when they are databases. The
new version of awk, called nawk, provides additional capabilities.[1] Every modern Unix system
comes with a version of new awk, and its use is recommended over old awk.
[1] It really isnt so new. The additional features were added in 1!"#, and it was first shipped
with $ystem % &elease '.1 in 1!"(. )evertheless, the name was never chan*ed on most systems.
+ifferent systems vary in what the two versions are called. $ome have oawk and awk, for the old
and new versions, respectively. ,thers have awk and nawk. $till others only have awk, which is
the new version. This example shows what happens if your awk is the old one-
$ awk 1 /dev/null
awk: syntax error near line 1
awk: bailing out near line 1
awk exits silently if it is the new version.
$ource code for the latest version of awk, from .ell /abs, can be downloaded startin* at .rian
0erni*hans home pa*e- http://cm.bell-labs.com/~bwk. 1ichael .rennans mawk is available via
anonymous 2T3 from ftp://ftp.whidbey.net/pub/brennan/mawk1.3.3.tar.gz. 2inally, the 2ree
$oftware 2oundation has a version of awk called gawk, available from
ftp://gnudist.gnu.org/gnu/gawk/gawk-3.0.4.tar.gz. 4ll three pro*rams implement 5new5 awk.
Thus, references below such as 5nawk only,5 apply to all three. gawk has additional features.
6ith ori*inal awk, you can-
Thin7 of a text file as made up of records and fields in a textual database.
3erform arithmetic and strin* operations.
Use pro*rammin* constructs such as loops and conditionals.
3roduce formatted reports.
6ith nawk, you can also-
+efine your own functions.
Execute Unix commands from a script.
3rocess the results of Unix commands.
3rocess command8line ar*uments more *racefully.
6or7 more easily with multiple input streams.
2lush open output files and pipes 9latest .ell /abs awk:.
In addition, with ;)U awk 9gawk:, you can-
Use re*ular expressions to separate records, as well as fields.
$7ip to the start of the next file, not <ust the next record.
3erform more powerful strin* substitutions.
&etrieve and format system time values.
11.2 Command-Line Syntax
The syntax for invo7in* awk has two forms-
awk [options] 'script' var=value file(s)
awk [options] -f scriptfile var=value file(s)
es for which the second field is *reater than the first. Aomparisons can be either strin* or
numeric. Thus, dependin* on the types of data in $1 and $$, awk does either a numeric or a strin*
comparison. This can chan*e from one record to the next.
3attern8matchin* expressions use the operators , 9match: and -, 9dont match:. $ee the
section 5,perators5 later in this chapter.
The BEG! pattern lets you specify procedures that ta7e place before the first input line is
processed. 9;enerally, you set *lobal variables here.:
The E!) pattern lets you specify procedures that ta7e place after the last input record is
read.
In nawk, BEG! and E!) patterns may appear multiple times. The procedures are mer*ed
as if there had been one lar*e procedure.
Except for BEG! and E!), patterns can be combined with the .oolean operators .. 9or:, //
9and:, and - 9not:. 4 ran*e of lines can also be specified usin* comma8separated patterns-
pattern0pattern
11.3.2 Procedures
3rocedures consist of one or more commands, functions, or variable assi*nments, separated by
newlines or semicolons, and contained within curly braces. Aommands fall into five *roups-
%ariable or array assi*nments
3rintin* commands
.uilt8in functions
Aontrol8flow commands
User8defined functions 9nawk only:
11.3.3 Simpe Pattern-Procedure #xampes
3rint first field of each line-
& 1rint $1 '
3rint all lines that contain pattern-
(pattern(
3rint first field of lines that contain pattern-
(pattern( & 1rint $1 '
$elect records containin* more than two fields-
!" + $
Interpret input records as a *roup of lines up to a blan7 line. Each line is a sin*le field-
BEG! & "# = 23n24 5# = 22 '
3rint fields C and ' in switched order, but only on lines whose first field matches the
strin* 5U&;E)T5-
$1 , (65GE!7( & 1rint $80 $$ '
Aount and print the number of pattern found-
(pattern( & 99x '
E!) & 1rint x '
4dd numbers in second column and print total-
& total 9= $$ '
E!) & 1rint 2:olumn total is20 total'
3rint lines that contain less than CD characters-
lengt;<$%= > $%
3rint each line that be*ins with %ame: and that contains exactly seven fields-
!" == ? // (*!ame:(
3rint the fields of each input record in reverse order, one per line-
&
for <i = !"4 i += 14 i--=
1rint $i
'
11.$ %uit-i
=ou can also delete individual elements of the array usin* the @elete statement 9nawk only:.
11.&.1 #scape Se'uences
6ithin strin* and re*ular expression constants, the followin* escape se@uences may be used.
)ote- The 3x escape se@uence is a common extension? it is not part of 3,$IE awk.
Se'uence (eaning Se'uence (eaning
3a
4lert 9bell:
3A
%ertical tab
3b
.ac7space
33
/iteral bac7slash
3f
2orm feed
3nnn
,ctal value nnn
3n
)ewline
3xnn
Fexadecimal value nn
3r
Aarria*e return
32
/iteral double @uote 9in strin*s:
3t
Tab
3(
/iteral slash 9in re*ular expressions:
11.) *ser-+e,ined -unctions
nawk allows you to define your own functions. This ma7es it easy to encapsulate se@uences of
steps that need to be repeated into a sin*le place, and reuse the code from anywhere in your
pro*ram. )ote- for user8defined functions, no space is allowed between the function name and
the left parenthesis when the function is called.
The followin* function capitali>es each word in a strin*. It has one parameter, named in1ut, and
five local variables, which are written as extra parameters.
B :a1italiCe ea:; wor@ in a string
fun:tion :a1italiCe<in1ut0 result0 wor@s0 n0 i0 w=
&
result = 22
n = s1lit<in1ut0 wor@s0 2 2=
for <i = 14 i >= n4 i99= &
w = wor@s[i]
w = tou11er<substr<w0 10 1== substr<w0 $=
if <i + 1=
result = result 2 2
result = result w
'
return result
'
B main 1rogram0 for testing
& 1rint :a1italiCe<$%= '
6ith this input data-
D test line wit; wor@s an@ numbers like 1$ on itE
This pro*ram produces-
D 7est Fine Git; Gor@s Dn@ !umbers Fike 1$ Hn tE
11.. /roup Listing o, awk -unctions and Commands
The followin* table classifies awk functions and commands.
Arithmetic String Control Flow I/O Time Program-
Functions Functions Statements Processing Functions ming
atan$['] gensub[#]
break
:lose['] strftime[#] @elete[']
Arithmetic String Control Flow I/O Time Program-
Functions Functions Statements Processing Functions ming
:os['] gsub[']
:ontinue
fflus;[G] systime[#] fun:tion[']
ex1 in@ex
@oHw;ile['] getline['] system[']
int lengt; exit next

log
mat:;[']
for
nextfile[G]
ran@[']
s1lit if 1rint

sin[']
s1rintf
return[']
1rintf

sIrt
sub[']
w;ile

sran@[']
substr

tolower[']
tou11er[']
['] 4vailable in nawk.
[#] 4vailable in gawk.
[G] 4vailable in .ell /abs awk and gawk.
11.0 1mpementation Limits
1any versions of awk have various implementation limits, on thin*s such as-
)umber of fields per record
)umber of characters per input record
)umber of characters per output record
)umber of characters per field
)umber of characters per 1rintf strin*
)umber of characters in literal strin*
)umber of characters in character class
)umber of files open
)umber of pipes open
The ability to handle "8bit characters and characters that are all >ero 94$AII )U/:
gawk does not have limits on any of these items, other than those imposed by the machine
architecture andHor the operatin* system.
11.12 3pha4etica Summary o, -unctions and Commands
The followin* alphabetical list of 7eywords and functions includes all that are available in awk,
nawk, and gawk. nawk includes all old awk functions and 7eywords, plus some additional ones
9mar7ed as 567:. gawk includes all nawk functions and 7eywords, plus some additional ones
9mar7ed as 5/7:. Items mar7ed with 5%7 are available in the .ell /abs awk. Items that arent
mar7ed with a symbol are available in all versions.
atan2
atan$<y0 x=
&eturn the arctan*ent of yH& in radians. I)J
4reak
break
Exit from a w;ile, for, or @o loop.
cose
:lose<filename-expr=
:lose<command-expr=
In most implementations of awk, you can have only 1D files open simultaneously and one pipe.
Therefore, nawk provides a :lose function that allows you to close a file or a pipe. It ta7es as an
ar*ument the same expression that opened the pipe or file. This expression must be identical,
character by character, to the one that opened the file or pipe? even whitespace is si*nificant. I)J
continue
:ontinue
.e*in next iteration of w;ile, for, or @o loop.
cos
:os<x=
&eturn the cosine of &, an an*le in radians. I)J
deete
@elete array[element]
@elete array
+elete element from array. The brac7ets are typed literally. The second form is a common
extension, which deletes all elements of the array at one shot. I)J
do
@o
statement
w;ile <expr=
/oopin* statement. Execute statement, then evaluate e&pr and, if true, execute statement a*ain. 4
series of statements must be put within braces. I)J
exit
exit [expr]
Exit from script, readin* no new input. The E!) procedure, if it exists, will be executed. 4n
optional e&pr becomes awks return value.
exp
ex1<x=
&eturn exponential of & 9e
&
:.
,,ush
fflus;<[output-expr]=
2lush any buffers associated with open output file or pipe output-e&pr. I.J
gawk extends this function. If no output-e&pr is supplied, it flushes standard output. If output-
e&pr is the null strin* 922:, it flushes all open files and pipes. I;J
,or
for <init-expr4 test-expr4 incr-expr=
statement
A8style loopin* construct. init-e&pr assi*ns the initial value of a counter variable. test-e&pr is a
relational expression that is evaluated each time before executin* the statement. 6hen test-e&pr
is false, the loop is exited. incr-e&pr increments the counter variable after each pass. 4ll the
expressions are optional. 4 missin* test-e&pr is considered to be true. 4 series of statements must
be put within braces.
,or
for <item in array=
statement
$pecial loop desi*ned for readin* associative arrays. 2or each element of the array, the statement
is executed? the element can be referenced by array[item]. 4 series of statements must be put
within braces.
,unction
fun:tion name<parameter-list= &
statements
'
Areate name as a user8defined function consistin* of awk statements that apply to the specified
list of parameters. )o space is allowed between name and the left paren when the function is
called. I)J
getine
getline [var] [> file]
or
command . getline [var]
&ead next line of input. ,ri*inal awk doesnt support the syntax to open multiple input streams.
The first form reads input from file? the second form reads the output of command. .oth forms
read one record at a time, and each time the statement is executed, it *ets the next record of
input. The record is assi*ned to $% and is parsed into fields, settin* !", !5 and "!5. If !ar is
specified, the result is assi*ned to !ar, and $% and !" arent chan*ed. Thus, if the result is
assi*ned to a variable, the current record doesnt chan*e. getline is actually a function and
returns 1 if it reads a record successfully, D if end8of8file is encountered, and 81 if its otherwise
unsuccessful. I)J
gensu4
gensub<r0 s0 h [0 t]=
;eneral substitution function. $ubstitute s for matches of the re*ular expression r in the strin* t.
If h is a number, replace the hth match. If it is 2g2 or 2G2, substitute *lobally. If t is not supplied,
$% is used. &eturn the new strin* value. The ori*inal t is not modified. 9Aompare gsu4 and su4.:
I;J
gsu4
gsub<r0 s [0 t]=
;lobally substitute s for each match of the re*ular expression r in the strin* t. If t is not supplied,
defaults to $%. &eturn the number of substitutions. I)J
i,
if <condition=
statement
[else
statement]
If condition is true, do statement's(? otherwise do statement in the optional else clause. The
condition can be an expression usin* any of the relational operators >, >=, ==, -=, +=, or +, as
well as the array membership operator in, and the pattern8matchin* operators , and -, 9e.*., if
<$1 , ([Da]EJ(=:. 4 series of statements must be put within braces. 4nother if can directly
follow an else in order to produce a chain of tests or decisions.
index
in@ex<str0 substr=
&eturn the position 9startin* at 1: of substr in str, or >ero if substr is not present in str.
int
int<x=
&eturn inte*er value of & by truncatin* any fractional part.
ength
lengt;<[arg]=
&eturn len*th of arg, or the len*th of $% if no ar*ument.
og
log<x=
&eturn the natural lo*arithm 9base e: of &.
match
mat:;<s0 r=
2unction that matches the pattern, specified by the re*ular expression r, in the strin* s, and
returns either the position in s, where the match be*ins, or D if no occurrences are found. $ets the
values of 5#7D57 and 5FE!G7K to the start and len*th of the match, respectively. I)J
next
next
&ead next input line and start new cycle throu*h patternHprocedures statements.
next,ie
nextfile
$top processin* the current input file and start new cycle throu*h patternHprocedures statements,
be*innin* with the first record of the next file. I.J I;J
print
1rint [ output-expr[0 EEE]] [ dest-expr ]
Evaluate the output-e&pr and direct it to standard output, followed by the value of H5#. Each
comma8separated output-e&pr is separated in the output by the value of H"#. 6ith no output-
e&pr, print $%.
!utput 8edirections
dest-e&pr is an optional expression that directs the output to a file or pipe.
+ file
+irects the output to a file, overwritin* its previous contents.
++ file
4ppends the output to a file, preservin* its previous contents. In both cases, the file is created if
it does not already exist.
. command
+irects the output as the input to a Unix command.
.e careful not to mix + and ++ for the same file. ,nce a file has been opened with +, subse@uent
output statements continue to append to the file until it is closed.
&emember to call :lose<= when you have finished with a file or pipe. If you dont, eventually
you will hit the system limit on the number of simultaneously open files.
print,
1rintf<format [0 expr-list ]= [ dest-expr ]
4n alternative output statement borrowed from the A lan*ua*e. It can produce formatted output
and also output data without automatically producin* a newline. format is a strin* of format
specifications and constants. e&pr-list is a list of ar*uments correspondin* to format specifiers.
$ee print for a description of dest-e&pr.
format follows the conventions of the A8lan*ua*e printf9'$: library function. Fere are a few of
the most common formats-
Ls
4 strin*.
L@
4 decimal number.
LnEmf
4 floatin*8point number? n K total number of di*its. m K number of di*its after decimal
point.
L[-]nc
n specifies minimum field len*th for format type c, while - left8<ustifies value in field?
otherwise, value is ri*ht8<ustified.
/i7e any strin*, format can also contain embedded escape se@uences- 3n 9newline: or 3t 9tab:
bein* the most common. $paces and lite n 9aria4es
Version Variable Description
awk "FE!DME
Aurrent filename

"#
2ield separator 9a space:

!"
)umber of fields in current record

!5
)umber of the current record

H"M7
,utput format for numbers 92LENg2: and for conversion to strin*

H"#
,utput field separator 9a space:

H5#
,utput record separator 9a newline:

5#
&ecord separator 9a newline:

$%
Entire input record

$n
nth field in current record? fields are separated by "#
nawk D5GO
)umber of ar*uments on command line

D5GP
4n array containin* the command8line ar*uments, indexed from D to
D5GO - 1

OH!P"M7
$trin* conversion format for numbers 92LENg2: 93,$IE:

E!P5H!
4n associative array of environment variables

"!5
/i7e !5, but relative to the current file

5FE!G7K
/en*th of the strin* matched by mat:;<= function

5#7D57
2irst position in the strin* matched by mat:;<= function

#6B#EQ
$eparator character for array subscripts 923%8R2:
gawk D5G!)
Index in D5GP of current input file

E55!H
4 strin* indicatin* the error when a redirection fails for getline or if
:lose<= fails
Version Variable Description

"EF)G)7K#
4 space8separated list of field widths to use for splittin* up the record,
instead of "#

G!H5EOD#E
6hen true, all re*ular expression matches, strin* comparisons, and calls
to in@ex<=s i*nore case

57
The text matched by 5#, which can be a re*ular expression in gawk
11.: !perators
The followin* table lists the operators, in order of increasin* precedence, that are available in
awk. )ote- while JJ and JJ= are common extensions, they are not part of 3,$IE awk.
Symbol eaning
= 9= -= J= (= L= *= JJ=
4ssi*nment
S:
A conditional expression 9nawk only:
..
/o*ical ,& 9short8circuit:
//
/o*ical 4)+ 9short8circuit:
in
4rray membership 9nawk only:
, -,
1atch re*ular expression and ne*ation
> >= + += -= ==
&elational operators
9blan7: Aoncatenation
9 -
4ddition, subtraction
J ( L
1ultiplication, division, and modulus 9remainder:
9 - -
Unary plus and minus, and lo*ical ne*ation
* JJ
Exponentiation
99 --
Increment and decrement, either prefix or postfix
$
2ield reference
11.& 9aria4es and 3rray 3ssignments
%ariables can be assi*ned a value with an K si*n. 2or example-
"# = 202
Expressions usin* the operators 9, -, (, and L 9modulo: can be assi*ned to variables.
4rrays can be created with the s1lit<= function 9see below:, or they can simply be named in an
assi*nment statement. 4rray elements can be subscripted with numbers 9array[1], ..., array[n]:
or with strin*s. 4rrays subscripted by strin*s are called associati!e arrays.[C] 2or example, to
count the number of wid*ets you have, you could use the followin* script-
[C] In fact, all arrays in awk are associative? numeric subscripts are converted to strin*s before
usin* them as array subscripts. 4ssociative arrays are one of awks most powerful features.
(wi@get( & :ount[2wi@get2]99 ' Count widgets
E!) & 1rint :ount[2wi@get2] ' Print the count
=ou can use the special for loop to read all the elements of an associative array-
for <item in array=
process array[item]
The index of the array is available as item, while the value of an element of the array can be
referenced as array[item].
=ou can use the operator in to see if an element exists by testin* to see if its index exists 9nawk
only:-
if <in@ex in array=
EEE
This se@uence tests that array[in@ex] exists, but you cannot use it to test the value of the
element referenced by array[in@ex].
ral text can be placed in the format ar*ument by @uotin* the entire ar*ument. If there are multiple
expressions to be printed, there should be multiple formats specified.
#xampe
Usin* the script-
& 1rintf<27;e sum on line L@ is LE%fE3n20 !50 $19$$= '
The followin* input line-
T T
produces this output, followed by a newline-
7;e sum on line 1 is 1%E
rand
ran@<=
;enerate a random number between D and 1. This function returns the same series of numbers
each time the script is executed, unless the random number *enerator is seeded usin* sran@<=.
I)J
return
return [expr]
Used within a user8defined function to exit the function, returnin* value of e&pr. The return value
of a function is undefined if e&pr is not provided. I)J
sin
sin<x=
&eturn the sine of &, an an*le in radians. I)J
spit
s1lit<string0 array [0 sep]=
$plit string into elements of array array[1],...,array[n]. The strin* is split at each occurrence of
separator sep. If sep is not specified, "# is used. The number of array elements created is
returned.
sprint,
s1rintf<format [0 expressions]=
&eturn the formatted value of one or more e&pressions, usin* the specified format 9see print,:.
+ata is formatted but not printed. I)J
s'rt
sIrt<arg=
&eturn s@uare root of arg.
srand
sran@<[expr]=
Use optional e&pr to set a new seed for the random number *enerator. +efault is the time of day.
&eturn value is the old seed. I)J
str,time
strftime<[format [0timestamp]]=
2ormat timestamp accordin* to format. &eturn the formatted strin*. The timestamp is a time8of8
day value in seconds since midni*ht, Lanuary 1, 1!(D, UTA. The format strin* is similar to that
of s1rintf. 9$ee the Example for systime.: If timestamp is omitted, it defaults to the current
time. If format is omitted, it defaults to a value that produces output similar to that of @ate. I;J
su4
sub<r0 s [0 t]=
$ubstitute s for first match of the re*ular expression r in the strin* t. If t is not supplied, defaults
to $%. &eturn 1 if successful? D otherwise. I)J
su4str
substr<string0 beg [0 len]=
&eturn substrin* of string at be*innin* position beg and the characters that follow to maximum
specified len*th len. If no len*th is *iven, use the rest of the strin*.
system
system<command=
2unction that executes the specified command and returns its status. The status of the executed
command typically indicates success or failure. 4 value of D means that the command executed
successfully. 4 non>ero value indicates a failure of some sort. The documentation for the
command youre runnin* will *ive you the details.
The output of the command is not available for processin* within the awk script. Use command .
getline to read the output of a command into the script. I)J
systime
systime<=
&eturn a time8of8day value in seconds since midni*ht, Lanuary 1, 1!(D, UTA. I;J
#xampe
/o* the start and end times of a data8processin* pro*ram-
BEG! &
now = systime<=
mesg = strftime<2#tarte@ at Lm(L@(LU LK:LM:L#20 now=
1rint mesg
'
process data ...
E!) &
now = systime<=
mesg = strftime<2En@e@ at Lm(L@(LU LK:LM:L#20 now=
1rint mesg
'
toower
tolower<str=
Translate all uppercase characters in str to lowercase and return the new strin*.[B] I)J
[B] %ery early versions of nawk dont support tolower<= and tou11er<=. Fowever, they are now
part of the 3,$IE specification for awk, and are included in the $%&# nawk.
toupper
tou11er<str=
Translate all lowercase characters in str to uppercase and return the new strin*. I)J
whie
w;ile <condition=
statement
+o statement while condition is true 9see if for a description of allowable conditions:. 4 series
of statements must be put within braces.
11.12.1 print, -ormats
2ormat specifiers for 1rintf and s1rintf have the followin* form-
L[flag][width][Eprecision]letter
The control letter is re@uired. The format conversion control letters are as follows.
Character Description
:
4$AII character
@
+ecimal inte*er
i
+ecimal inte*er 9added in 3,$IE:
e
2loatin*8point format 9[8]d.precisione[M8]dd:
E
2loatin*8point format 9[8]d.precisionE[M8]dd:
f
2loatin*8point format 9[8]ddd.precision:
g
e or f conversion, whichever is shortest, with trailin* >eros removed
G
E or f conversion, whichever is shortest, with trailin* >eros removed
o
Unsi*ned octal value
s
$trin*
x
Unsi*ned hexadecimal number? uses a8f for 1D to 1G
V
Unsi*ned hexadecimal number? uses D8" for 1D to 1G
L
/iteral L
The optional flag is one of the followin*.
Character Description
-
/eft8<ustify the formatted value within the field.
space 3refix positive values with a space and ne*ative values with a minus.
9
4lways prefix numeric values with a si*n, even if the value is positive.
B
Use an alternate form- Lo has a precedin* %? Lx and LV are prefixed with %x and %V,
respectively? Le, LE, and Lf always have a decimal point in the result? and Lg and LG
do not have trailin* >eros removed.
%
3ad output with >eros, not spaces. This happens only when the field width is wider
than the converted result.
The optional width is the minimum number of characters to output. The result will be padded to
this si>e if it is smaller. The % fla* causes paddin* with >eros? otherwise, paddin* is with spaces.
The precision is optional. Its meanin* varies by control letter, as shown in this table.
Con!ersion Precision eans
L@, Li, Lo The minimum number of di*its to print
Lu, Lx, LV
Le, LE, Lf The number of di*its to the ri*ht of the decimal point
Lg, LG The maximum number of si*nificant di*its
Ls
The maximum number of characters to print

You might also like