summaryrefslogtreecommitdiff
path: root/usr.bin/awk/awk.1
blob: 0ece207fcf268bf121fcce0c5cb1f25dab5df38a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
.\"	$OpenBSD: awk.1,v 1.33 2009/02/08 17:15:09 jmc Exp $
.\" EX/EE is a Bd
.\"
.\" Copyright (C) Lucent Technologies 1997
.\" All Rights Reserved
.\"
.\" Permission to use, copy, modify, and distribute this software and
.\" its documentation for any purpose and without fee is hereby
.\" granted, provided that the above copyright notice appear in all
.\" copies and that both that the copyright notice and this
.\" permission notice and warranty disclaimer appear in supporting
.\" documentation, and that the name Lucent Technologies or any of
.\" its entities not be used in advertising or publicity pertaining
.\" to distribution of the software without specific, written prior
.\" permission.
.\"
.\" LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
.\" INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
.\" IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY
.\" SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
.\" WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
.\" IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
.\" ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
.\" THIS SOFTWARE.
.\"
.Dd $Mdocdate: February 8 2009 $
.Dt AWK 1
.Os
.Sh NAME
.Nm awk
.Nd pattern-directed scanning and processing language
.Sh SYNOPSIS
.Nm awk
.Op Fl safe
.Op Fl V
.Op Fl d Ns Op Ar n
.Op Fl F Ar fs
.Oo Fl v Ar var Ns =
.Ns Ar value Oc
.Op Ar prog | Fl f Ar progfile
.Ar
.Nm nawk
.Ar ...
.Sh DESCRIPTION
.Nm
scans each input
.Ar file
for lines that match any of a set of patterns specified literally in
.Ar prog
or in one or more files specified as
.Fl f Ar progfile .
With each pattern there can be an associated action that will be performed
when a line of a
.Ar file
matches the pattern.
Each line is matched against the
pattern portion of every pattern-action statement;
the associated action is performed for each matched pattern.
The file name
.Sq -
means the standard input.
Any
.Ar file
of the form
.Ar var Ns = Ns Ar value
is treated as an assignment, not a filename,
and is executed at the time it would have been opened if it were a filename.
.Pp
The options are as follows:
.Bl -tag -width "-safe "
.It Fl d Ns Op Ar n
Debug mode.
Set debug level to
.Ar n ,
or 1 if
.Ar n
is not specified.
A value greater than 1 causes
.Nm
to dump core on fatal errors.
.It Fl F Ar fs
Define the input field separator to be the regular expression
.Ar fs .
.It Fl f Ar progfile
Read program code from the specified file
.Ar progfile
instead of from the command line.
.It Fl safe
Disable file output
.Pf ( Ic print No > ,
.Ic print No >> ) ,
process creation
.Po
.Ar cmd | Ic getline ,
.Ic print No \&| ,
.Ic system
.Pc
and access to the environment
.Pf ( Va ENVIRON ;
see the section on variables below).
This is a first
.Pq and not very reliable
approximation to a
.Dq safe
version of
.Nm .
.It Fl V
Print the version number of
.Nm
to standard output and exit.
.It Fl v Ar var Ns = Ns Ar value
Assign
.Ar value
to variable
.Ar var
before
.Ar prog
is executed;
any number of
.Fl v
options may be present.
.El
.Pp
The input is normally made up of input lines
.Pq records
separated by newlines, or by the value of
.Va RS .
If
.Va RS
is null, then any number of blank lines are used as the record separator,
and newlines are used as field separators
(in addition to the value of
.Va FS ) .
This is convenient when working with multi-line records.
.Pp
An input line is normally made up of fields separated by whitespace,
or by the regular expression
.Va FS .
The fields are denoted
.Va $1 , $2 , ... ,
while
.Va $0
refers to the entire line.
If
.Va FS
is null, the input line is split into one field per character.
.Pp
Normally, any number of blanks separate fields.
In order to set the field separator to a single blank, use the
.Fl F
option with a value of
.Sq [\ \&] .
If a field separator of
.Sq t
is specified,
.Nm
treats it as if
.Sq \et
had been specified and uses
.Aq TAB
as the field separator.
In order to use a literal
.Sq t
as the field separator, use the
.Fl F
option with a value of
.Sq [t] .
.Pp
A pattern-action statement has the form
.Pp
.D1 Ar pattern Ic \&{ Ar action Ic \&}
.Pp
A missing
.Ic \&{ Ar action Ic \&}
means print the line;
a missing pattern always matches.
Pattern-action statements are separated by newlines or semicolons.
.Pp
Newlines are permitted after a terminating statement or following a comma
.Pq Sq ,\& ,
an open brace
.Pq Sq { ,
a logical AND
.Pq Sq && ,
a logical OR
.Pq Sq || ,
after the
.Sq do
or
.Sq else
keywords,
or after the closing parenthesis of an
.Sq if ,
.Sq for ,
or
.Sq while
statement.
Additionally, a backslash
.Pq Sq \e
can be used to escape a newline between tokens.
.Pp
An action is a sequence of statements.
A statement can be one of the following:
.Bd -unfilled -offset indent
.Ic if ( Xo
.Ar expression ) statement \&
.Op Ic else Ar statement
.Xc
.Ic while ( Ar expression ) statement
.Ic for ( Xo
.Ar expression ; expression ; expression ) statement
.Xc
.Ic for ( Xo
.Ar var Ic in Ar array ) statement
.Xc
.Ic do Ar statement Ic while ( Ar expression )
.Ic break
.Ic continue
.Ic { Oo Ar statement ... Oc Ic \& }
.Ar expression Xo
.No "# commonly" \&
.Ar var Ic = Ar expression
.Xc
.Ic print Xo
.Op Ar expression-list
.Op > Ns Ar expression
.Xc
.Ic printf Ar format Xo
.Op Ar ... , expression-list
.Op > Ns Ar expression
.Xc
.Ic return Op Ar expression
.Ic next Xo
.No "# skip remaining patterns on this input line"
.Xc
.Ic nextfile Xo
.No "# skip rest of this file, open next, start at top"
.Xc
.Ic delete Ar array Ns Xo
.Ic \&[ Ns Ar expression Ns Ic \&]
.No \& "# delete an array element"
.Xc
.Ic delete Ar array Xo
.No "# delete all elements of array"
.Xc
.Ic exit Xo
.Op Ar expression
.No \& "# exit immediately; status is" Ar expression
.Xc
.Ed
.Pp
Statements are terminated by
semicolons, newlines or right braces.
An empty
.Ar expression-list
stands for
.Ar $0 .
String constants are quoted
.Li \&"" ,
with the usual C escapes recognized within
(see
.Xr printf 1
for a complete list of these).
Expressions take on string or numeric values as appropriate,
and are built using the operators
.Ic + \- * / % ^
.Pq exponentiation ,
and concatenation
.Pq indicated by whitespace .
The operators
.Ic \&! ++ \-\- += \-= *= /= %= ^=
.Ic > >= < <= == != ?:
are also available in expressions.
Variables may be scalars, array elements
(denoted
.Li x[i] )
or fields.
Variables are initialized to the null string.
Array subscripts may be any string,
not necessarily numeric;
this allows for a form of associative memory.
Multiple subscripts such as
.Li [i,j,k]
are permitted; the constituents are concatenated,
separated by the value of
.Va SUBSEP
.Pq see the section on variables below .
.Pp
The
.Ic print
statement prints its arguments on the standard output
(or on a file if
.Pf > Ns Ar file
or
.Pf >> Ns Ar file
is present or on a pipe if
.Pf |\ \& Ar cmd
is present), separated by the current output field separator,
and terminated by the output record separator.
.Ar file
and
.Ar cmd
may be literal names or parenthesized expressions;
identical string values in different statements denote
the same open file.
The
.Ic printf
statement formats its expression list according to the format
(see
.Xr printf 1 ) .
.Pp
Patterns are arbitrary Boolean combinations
(with
.Ic "\&! || &&" )
of regular expressions and
relational expressions.
.Nm
supports extended regular expressions
.Pq EREs .
See
.Xr re_format 7
for more information on regular expressions.
Isolated regular expressions
in a pattern apply to the entire line.
Regular expressions may also occur in
relational expressions, using the operators
.Ic ~
and
.Ic !~ .
.Pf / Ns Ar re Ns /
is a constant regular expression;
any string (constant or variable) may be used
as a regular expression, except in the position of an isolated regular expression
in a pattern.
.Pp
A pattern may consist of two patterns separated by a comma;
in this case, the action is performed for all lines
from an occurrence of the first pattern
through an occurrence of the second.
.Pp
A relational expression is one of the following:
.Bd -unfilled -offset indent
.Ar expression matchop regular-expression
.Ar expression relop expression
.Ar expression Ic in Ar array-name
.Ic \&( Ns Xo
.Ar expr , expr , \&... Ns Ic \&) in
.Ar \& array-name
.Xc
.Ed
.Pp
where a
.Ar relop
is any of the six relational operators in C, and a
.Ar matchop
is either
.Ic ~
(matches)
or
.Ic !~
(does not match).
A conditional is an arithmetic expression,
a relational expression,
or a Boolean combination
of these.
.Pp
The special patterns
.Ic BEGIN
and
.Ic END
may be used to capture control before the first input line is read
and after the last.
.Ic BEGIN
and
.Ic END
do not combine with other patterns.
.Pp
Variable names with special meanings:
.Pp
.Bl -tag -width "FILENAME " -compact
.It Va ARGC
Argument count, assignable.
.It Va ARGV
Argument array, assignable;
non-null members are taken as filenames.
.It Va CONVFMT
Conversion format when converting numbers
(default
.Qq Li %.6g ) .
.It Va ENVIRON
Array of environment variables; subscripts are names.
.It Va FILENAME
The name of the current input file.
.It Va FNR
Ordinal number of the current record in the current file.
.It Va FS
Regular expression used to separate fields; also settable
by option
.Fl F Ar fs .
.It Va NF
Number of fields in the current record.
.Va $NF
can be used to obtain the value of the last field in the current record.
.It Va NR
Ordinal number of the current record.
.It Va OFMT
Output format for numbers (default
.Qq Li %.6g ) .
.It Va OFS
Output field separator (default blank).
.It Va ORS
Output record separator (default newline).
.It Va RLENGTH
The length of the string matched by the
.Fn match
function.
.It Va RS
Input record separator (default newline).
.It Va RSTART
The starting position of the string matched by the
.Fn match
function.
.It Va SUBSEP
Separates multiple subscripts (default 034).
.El
.Sh FUNCTIONS
The awk language has a variety of built-in functions:
arithmetic, string, input/output, general, and bit-operation.
.Pp
Functions may be defined (at the position of a pattern-action statement)
thusly:
.Pp
.Dl function foo(a, b, c) { ...; return x }
.Pp
Parameters are passed by value if scalar, and by reference if array name;
functions may be called recursively.
Parameters are local to the function; all other variables are global.
Thus local variables may be created by providing excess parameters in
the function definition.
.Ss Arithmetic Functions
.Bl -tag -width "atan2(y, x)"
.It Fn atan2 y x
Return the arctangent of
.Fa y Ns / Ns Fa x
in radians.
.It Fn cos x
Return the cosine of
.Fa x ,
where
.Fa x
is in radians.
.It Fn exp x
Return the exponential of
.Fa x .
.It Fn int x
Return
.Fa x
truncated to an integer value.
.It Fn log x
Return the natural logarithm of
.Fa x .
.It Fn rand
Return a random number,
.Fa n ,
such that
.Sm off
.Pf 0 \*(Le Fa n No \*(Lt 1 .
.Sm on
.It Fn sin x
Return the sine of
.Fa x ,
where
.Fa x
is in radians.
.It Fn sqrt x
Return the square root of
.Fa x .
.It Fn srand expr
Sets seed for
.Fn rand
to
.Fa expr
and returns the previous seed.
If
.Fa expr
is omitted, the time of day is used instead.
.El
.Ss String Functions
.Bl -tag -width "split(s, a, fs)"
.It Fn gsub r t s
The same as
.Fn sub
except that all occurrences of the regular expression are replaced.
.Fn gsub
returns the number of replacements.
.It Fn index s t
The position in
.Fa s
where the string
.Fa t
occurs, or 0 if it does not.
.It Fn length s
The length of
.Fa s
taken as a string,
or of
.Va $0
if no argument is given.
.It Fn match s r
The position in
.Fa s
where the regular expression
.Fa r
occurs, or 0 if it does not.
The variable
.Va RSTART
is set to the starting position of the matched string
.Pq which is the same as the returned value
or zero if no match is found.
The variable
.Va RLENGTH
is set to the length of the matched string,
or \-1 if no match is found.
.It Fn split s a fs
Splits the string
.Fa s
into array elements
.Va a[1] , a[2] , ... , a[n]
and returns
.Va n .
The separation is done with the regular expression
.Ar fs
or with the field separator
.Va FS
if
.Ar fs
is not given.
An empty string as field separator splits the string
into one array element per character.
.It Fn sprintf fmt expr ...
The string resulting from formatting
.Fa expr , ...
according to the
.Xr printf 1
format
.Fa fmt .
.It Fn sub r t s
Substitutes
.Fa t
for the first occurrence of the regular expression
.Fa r
in the string
.Fa s .
If
.Fa s
is not given,
.Va $0
is used.
An ampersand
.Pq Sq &
in
.Fa t
is replaced in string
.Fa s
with regular expression
.Fa r .
A literal ampersand can be specified by preceding it with two backslashes
.Pq Sq \e\e .
A literal backslash can be specified by preceding it with another backslash
.Pq Sq \e\e .
.Fn sub
returns the number of replacements.
.It Fn substr s m n
Return at most the
.Fa n Ns -character
substring of
.Fa s
that begins at position
.Fa m
counted from 1.
If
.Fa n
is omitted, or if
.Fa n
specifies more characters than are left in the string,
the length of the substring is limited by the length of
.Fa s .
.It Fn tolower str
Returns a copy of
.Fa str
with all upper-case characters translated to their
corresponding lower-case equivalents.
.It Fn toupper str
Returns a copy of
.Fa str
with all lower-case characters translated to their
corresponding upper-case equivalents.
.El
.Ss Input/Output and General Functions
.Bl -tag -width "getline [var] < file"
.It Fn close expr
Closes the file or pipe
.Fa expr .
.Fa expr
should match the string that was used to open the file or pipe.
.It Ar cmd | Ic getline Op Va var
Read a record of input from a stream piped from the output of
.Ar cmd .
If
.Va var
is omitted, the variables
.Va $0
and
.Va NF
are set.
Otherwise
.Va var
is set.
If the stream is not open, it is opened.
As long as the stream remains open, subsequent calls
will read subsequent records from the stream.
The stream remains open until explicitly closed with a call to
.Fn close .
.Ic getline
returns 1 for a successful input, 0 for end of file, and \-1 for an error.
.It Fn fflush [expr]
Flushes any buffered output for the file, pipe
.Fa expr ,
or all open files or pipes if
.Fa expr
is omitted.
.Fa expr
should match the string that was used to open the file or pipe.
.It Ic getline
Sets
.Va $0
to the next input record from the current input file.
This form of
.Ic getline
sets the variables
.Va NF ,
.Va NR ,
and
.Va FNR .
.Ic getline
returns 1 for a successful input, 0 for end of file, and \-1 for an error.
.It Ic getline Va var
Sets
.Va $0
to variable
.Va var .
This form of
.Ic getline
sets the variables
.Va NR
and
.Va FNR .
.Ic getline
returns 1 for a successful input, 0 for end of file, and \-1 for an error.
.It Xo
.Ic getline Op Va var
.Pf \ \&< Ar file
.Xc
Sets
.Va $0
to the next record from
.Ar file .
If
.Va var
is omitted, the variables
.Va $0
and
.Va NF
are set.
Otherwise
.Va var
is set.
If
.Ar file
is not open, it is opened.
As long as the stream remains open, subsequent calls will read subsequent
records from
.Ar file .
.Ar file
remains open until explicitly closed with a call to
.Fn close .
.It Fn system cmd
Executes
.Fa cmd
and returns its exit status.
.El
.Ss Bit-Operation Functions
.Bl -tag -width "lshift(a, b)"
.It Fn compl x
Returns the bitwise complement of integer argument x.
.It Fn and x y
Performs a bitwise AND on integer arguments x and y.
.It Fn or x y
Performs a bitwise OR on integer arguments x and y.
.It Fn xor x y
Performs a bitwise Exclusive-OR on integer arguments x and y.
.It Fn lshift x n
Returns x shifted by n bits to the left.
.It Fn rshift x n
Returns y shifted by n bits to the right.
.El
.Sh EXAMPLES
Print lines longer than 72 characters:
.Pp
.Dl length($0) > 72
.Pp
Print first two fields in opposite order:
.Pp
.Dl { print $2, $1 }
.Pp
Same, with input fields separated by comma and/or blanks and tabs:
.Bd -literal -offset indent
BEGIN { FS = ",[ \et]*|[ \et]+" }
      { print $2, $1 }
.Ed
.Pp
Add up first column, print sum and average:
.Bd -literal -offset indent
{ s += $1 }
END { print "sum is", s, " average is", s/NR }
.Ed
.Pp
Print all lines between start/stop pairs:
.Pp
.Dl /start/, /stop/
.Pp
Simulate echo(1):
.Bd -literal -offset indent
BEGIN { # Simulate echo(1)
        for (i = 1; i < ARGC; i++) printf "%s ", ARGV[i]
        printf "\en"
        exit }
.Ed
.Pp
Print an error message to standard error:
.Bd -literal -offset indent
{ print "error!" > "/dev/stderr" }
.Ed
.Sh SEE ALSO
.Xr lex 1 ,
.Xr printf 1 ,
.Xr sed 1 ,
.Xr re_format 7 ,
.Xr script 7
.Pp
"Awk \(em A Pattern Scanning and Processing Language",
.Pa /usr/share/doc/usd/16.awk/ .
.Rs
.%A A. V. Aho
.%A B. W. Kernighan
.%A P. J. Weinberger
.%T The AWK Programming Language
.%I Addison-Wesley
.%D 1988
.%O ISBN 0-201-07981-X
.Re
.Sh STANDARDS
The
.Nm
utility is compliant with the
.St -p1003.1-2008
specification.
.Pp
The flags
.Op Fl \&dV
and
.Op Fl safe ,
as well as the commands
.Cm fflush , compl , and , or ,
.Cm xor , lshift , rshift ,
are extensions to that specification.
.Pp
.Nm
does not support {n,m} pattern matching.
.Sh HISTORY
An
.Nm
utility appeared in
.At v7 .
.Sh BUGS
There are no explicit conversions between numbers and strings.
To force an expression to be treated as a number add 0 to it;
to force it to be treated as a string concatenate
.Li \&""
to it.
.Pp
The scope rules for variables in functions are a botch;
the syntax is worse.