]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/one-true-awk/awk.1
Add UPDATING entries and bump version.
[FreeBSD/FreeBSD.git] / contrib / one-true-awk / awk.1
1 .de EX
2 .nf
3 .ft CW
4 ..
5 .de EE
6 .br
7 .fi
8 .ft 1
9 ..
10 .de TF
11 .IP "" "\w'\fB\\$1\ \ \fP'u"
12 .PD 0
13 ..
14 .TH AWK 1
15 .CT 1 files prog_other
16 .SH NAME
17 awk \- pattern-directed scanning and processing language
18 .SH SYNOPSIS
19 .B awk
20 [
21 .BI \-F
22 .I fs
23 ]
24 [
25 .BI \-v
26 .I var=value
27 ]
28 [
29 .I 'prog'
30 |
31 .BI \-f
32 .I progfile
33 ]
34 [
35 .I file ...
36 ]
37 .SH DESCRIPTION
38 .I Awk
39 scans each input
40 .I file
41 for lines that match any of a set of patterns specified literally in
42 .I prog
43 or in one or more files
44 specified as
45 .B \-f
46 .IR progfile .
47 With each pattern
48 there can be an associated action that will be performed
49 when a line of a
50 .I file
51 matches the pattern.
52 Each line is matched against the
53 pattern portion of every pattern-action statement;
54 the associated action is performed for each matched pattern.
55 The file name
56 .B \-
57 means the standard input.
58 Any
59 .I file
60 of the form
61 .I var=value
62 is treated as an assignment, not a filename,
63 and is executed at the time it would have been opened if it were a filename.
64 The option
65 .B \-v
66 followed by
67 .I var=value
68 is an assignment to be done before
69 .I prog
70 is executed;
71 any number of
72 .B \-v
73 options may be present.
74 The
75 .B \-F
76 .I fs
77 option defines the input field separator to be the regular expression
78 .IR fs .
79 .PP
80 An input line is normally made up of fields separated by white space,
81 or by the regular expression
82 .BR FS .
83 The fields are denoted
84 .BR $1 ,
85 .BR $2 ,
86 \&..., while
87 .B $0
88 refers to the entire line.
89 If
90 .BR FS
91 is null, the input line is split into one field per character.
92 .PP
93 A pattern-action statement has the form:
94 .IP
95 .IB pattern " { " action " }
96 .PP
97 A missing
98 .BI { " action " }
99 means print the line;
100 a missing pattern always matches.
101 Pattern-action statements are separated by newlines or semicolons.
102 .PP
103 An action is a sequence of statements.
104 A statement can be one of the following:
105 .PP
106 .EX
107 .ta \w'\f(CWdelete array[expression]\fR'u
108 .RS
109 .nf
110 .ft CW
111 if(\fI expression \fP)\fI statement \fP\fR[ \fPelse\fI statement \fP\fR]\fP
112 while(\fI expression \fP)\fI statement\fP
113 for(\fI expression \fP;\fI expression \fP;\fI expression \fP)\fI statement\fP
114 for(\fI var \fPin\fI array \fP)\fI statement\fP
115 do\fI statement \fPwhile(\fI expression \fP)
116 break
117 continue
118 {\fR [\fP\fI statement ... \fP\fR] \fP}
119 \fIexpression\fP        #\fR commonly\fP\fI var = expression\fP
120 print\fR [ \fP\fIexpression-list \fP\fR] \fP\fR[ \fP>\fI expression \fP\fR]\fP
121 printf\fI format \fP\fR[ \fP,\fI expression-list \fP\fR] \fP\fR[ \fP>\fI expression \fP\fR]\fP
122 return\fR [ \fP\fIexpression \fP\fR]\fP
123 next    #\fR skip remaining patterns on this input line\fP
124 nextfile        #\fR skip rest of this file, open next, start at top\fP
125 delete\fI array\fP[\fI expression \fP]  #\fR delete an array element\fP
126 delete\fI array\fP      #\fR delete all elements of array\fP
127 exit\fR [ \fP\fIexpression \fP\fR]\fP   #\fR exit immediately; status is \fP\fIexpression\fP
128 .fi
129 .RE
130 .EE
131 .DT
132 .PP
133 Statements are terminated by
134 semicolons, newlines or right braces.
135 An empty
136 .I expression-list
137 stands for
138 .BR $0 .
139 String constants are quoted \&\f(CW"\ "\fR,
140 with the usual C escapes recognized within.
141 Expressions take on string or numeric values as appropriate,
142 and are built using the operators
143 .B + \- * / % ^
144 (exponentiation), and concatenation (indicated by white space).
145 The operators
146 .B
147 ! ++ \-\- += \-= *= /= %= ^= > >= < <= == != ?:
148 are also available in expressions.
149 Variables may be scalars, array elements
150 (denoted
151 .IB x  [ i ] \fR)
152 or fields.
153 Variables are initialized to the null string.
154 Array subscripts may be any string,
155 not necessarily numeric;
156 this allows for a form of associative memory.
157 Multiple subscripts such as
158 .B [i,j,k]
159 are permitted; the constituents are concatenated,
160 separated by the value of
161 .BR SUBSEP .
162 .PP
163 The
164 .B print
165 statement prints its arguments on the standard output
166 (or on a file if
167 .BI > " file
168 or
169 .BI >> " file
170 is present or on a pipe if
171 .BI | " cmd
172 is present), separated by the current output field separator,
173 and terminated by the output record separator.
174 .I file
175 and
176 .I cmd
177 may be literal names or parenthesized expressions;
178 identical string values in different statements denote
179 the same open file.
180 The
181 .B printf
182 statement formats its expression list according to the
183 .I format
184 (see
185 .IR printf (3)).
186 The built-in function
187 .BI close( expr )
188 closes the file or pipe
189 .IR expr .
190 The built-in function
191 .BI fflush( expr )
192 flushes any buffered output for the file or pipe
193 .IR expr .
194 .PP
195 The mathematical functions
196 .BR atan2 ,
197 .BR cos ,
198 .BR exp ,
199 .BR log ,
200 .BR sin ,
201 and
202 .B sqrt
203 are built in.
204 Other built-in functions:
205 .TF length
206 .TP
207 .B length
208 the length of its argument
209 taken as a string,
210 number of elements in an array for an array argument,
211 or length of
212 .B $0
213 if no argument.
214 .TP
215 .B rand
216 random number on [0,1).
217 .TP
218 .B srand
219 sets seed for
220 .B rand
221 and returns the previous seed.
222 .TP
223 .B int
224 truncates to an integer value.
225 .TP
226 \fBsubstr(\fIs\fB, \fIm\fR [\fB, \fIn\^\fR]\fB)\fR
227 the
228 .IR n -character
229 substring of
230 .I s
231 that begins at position
232 .I m
233 counted from 1.
234 If no
235 .IR n ,
236 use the rest of the string.
237 .TP
238 .BI index( s , " t" )
239 the position in
240 .I s
241 where the string
242 .I t
243 occurs, or 0 if it does not.
244 .TP
245 .BI match( s , " r" )
246 the position in
247 .I s
248 where the regular expression
249 .I r
250 occurs, or 0 if it does not.
251 The variables
252 .B RSTART
253 and
254 .B RLENGTH
255 are set to the position and length of the matched string.
256 .TP
257 \fBsplit(\fIs\fB, \fIa \fR[\fB, \fIfs\^\fR]\fB)\fR
258 splits the string
259 .I s
260 into array elements
261 .IB a [1] \fR,
262 .IB a [2] \fR,
263 \&...,
264 .IB a [ n ] \fR,
265 and returns
266 .IR n .
267 The separation is done with the regular expression
268 .I fs
269 or with the field separator
270 .B FS
271 if
272 .I fs
273 is not given.
274 An empty string as field separator splits the string
275 into one array element per character.
276 .TP
277 \fBsub(\fIr\fB, \fIt \fR[, \fIs\^\fR]\fB)
278 substitutes
279 .I t
280 for the first occurrence of the regular expression
281 .I r
282 in the string
283 .IR s .
284 If
285 .I s
286 is not given,
287 .B $0
288 is used.
289 .TP
290 \fBgsub(\fIr\fB, \fIt \fR[, \fIs\^\fR]\fB)
291 same as
292 .B sub
293 except that all occurrences of the regular expression
294 are replaced;
295 .B sub
296 and
297 .B gsub
298 return the number of replacements.
299 .TP
300 \fBgensub(\fIpat\fB, \fIrepl\fB, \fIhow\fR [\fB, \fItarget\fR]\fB)\fR
301 replaces instances of
302 .I pat
303 in
304 .I target
305 with
306 .IR repl .
307 If
308 .I how
309 is \fB"g"\fR or \fB"G"\fR, do so globally. Otherwise,
310 .I how
311 is a number indicating which occurrence to replace.  If no
312 .IR target ,
313 use
314 .BR $0 .
315 Return the resulting string;
316 .I target
317 is not modified.
318 .TP
319 .BI sprintf( fmt , " expr" , " ...\fB)
320 the string resulting from formatting
321 .I expr ...
322 according to the
323 .IR printf (3)
324 format
325 .IR fmt .
326 .TP
327 .B systime()
328 returns the current date and time as a standard
329 ``seconds since the epoch'' value.
330 .TP
331 .BI strftime( fmt ", " timestamp\^ )
332 formats
333 .I timestamp
334 (a value in seconds since the epoch)
335 according to
336 .IR fmt ,
337 which is a format string as supported by
338 .IR strftime (3).
339 Both
340 .I timestamp
341 and
342 .I fmt
343 may be omitted; if no
344 .IR timestamp ,
345 the current time of day is used, and if no
346 .IR fmt ,
347 a default format of \fB"%a %b %e %H:%M:%S %Z %Y"\fR is used.
348 .TP
349 .BI system( cmd )
350 executes
351 .I cmd
352 and returns its exit status. This will be \-1 upon error,
353 .IR cmd 's
354 exit status upon a normal exit,
355 256 +
356 .I sig
357 upon death-by-signal, where
358 .I sig
359 is the number of the murdering signal,
360 or 512 +
361 .I sig
362 if there was a core dump.
363 .TP
364 .BI tolower( str )
365 returns a copy of
366 .I str
367 with all upper-case characters translated to their
368 corresponding lower-case equivalents.
369 .TP
370 .BI toupper( str )
371 returns a copy of
372 .I str
373 with all lower-case characters translated to their
374 corresponding upper-case equivalents.
375 .PD
376 .PP
377 The ``function''
378 .B getline
379 sets
380 .B $0
381 to the next input record from the current input file;
382 .B getline
383 .BI < " file
384 sets
385 .B $0
386 to the next record from
387 .IR file .
388 .B getline
389 .I x
390 sets variable
391 .I x
392 instead.
393 Finally,
394 .IB cmd " | getline
395 pipes the output of
396 .I cmd
397 into
398 .BR getline ;
399 each call of
400 .B getline
401 returns the next line of output from
402 .IR cmd .
403 In all cases,
404 .B getline
405 returns 1 for a successful input,
406 0 for end of file, and \-1 for an error.
407 .PP
408 The functions
409 .BR compl ,
410 .BR and ,
411 .BR or ,
412 .BR xor ,
413 .BR lshift ,
414 and
415 .B rshift
416 peform the corresponding bitwise operations on their
417 operands, which are first truncated to integer.
418 .PP
419 Patterns are arbitrary Boolean combinations
420 (with
421 .BR "! || &&" )
422 of regular expressions and
423 relational expressions.
424 Regular expressions are as in
425 .IR egrep ;
426 see
427 .IR grep (1).
428 Isolated regular expressions
429 in a pattern apply to the entire line.
430 Regular expressions may also occur in
431 relational expressions, using the operators
432 .B ~
433 and
434 .BR !~ .
435 .BI / re /
436 is a constant regular expression;
437 any string (constant or variable) may be used
438 as a regular expression, except in the position of an isolated regular expression
439 in a pattern.
440 .PP
441 A pattern may consist of two patterns separated by a comma;
442 in this case, the action is performed for all lines
443 from an occurrence of the first pattern
444 though an occurrence of the second.
445 .PP
446 A relational expression is one of the following:
447 .IP
448 .I expression matchop regular-expression
449 .br
450 .I expression relop expression
451 .br
452 .IB expression " in " array-name
453 .br
454 .BI ( expr , expr,... ") in " array-name
455 .PP
456 where a
457 .I relop
458 is any of the six relational operators in C,
459 and a
460 .I matchop
461 is either
462 .B ~
463 (matches)
464 or
465 .B !~
466 (does not match).
467 A conditional is an arithmetic expression,
468 a relational expression,
469 or a Boolean combination
470 of these.
471 .PP
472 The special patterns
473 .B BEGIN
474 and
475 .B END
476 may be used to capture control before the first input line is read
477 and after the last.
478 .B BEGIN
479 and
480 .B END
481 do not combine with other patterns.
482 They may appear multiple times in a program and execute
483 in the order they are read by
484 .IR awk .
485 .PP
486 Variable names with special meanings:
487 .TF FILENAME
488 .TP
489 .B ARGC
490 argument count, assignable.
491 .TP
492 .B ARGV
493 argument array, assignable;
494 non-null members are taken as filenames.
495 .TP
496 .B CONVFMT
497 conversion format used when converting numbers
498 (default
499 .BR "%.6g" ).
500 .TP
501 .B ENVIRON
502 array of environment variables; subscripts are names.
503 .TP
504 .B FILENAME
505 the name of the current input file.
506 .TP
507 .B FNR
508 ordinal number of the current record in the current file.
509 .TP
510 .B FS
511 regular expression used to separate fields; also settable
512 by option
513 .BI \-F fs\fR.
514 .TP
515 .BR NF
516 number of fields in the current record.
517 .TP
518 .B NR
519 ordinal number of the current record.
520 .TP
521 .B OFMT
522 output format for numbers (default
523 .BR "%.6g" ).
524 .TP
525 .B OFS
526 output field separator (default space).
527 .TP
528 .B ORS
529 output record separator (default newline).
530 .TP
531 .B RLENGTH
532 the length of a string matched by
533 .BR match .
534 .TP
535 .B RS
536 input record separator (default newline).
537 If empty, blank lines separate records.
538 If more than one character long,
539 .B RS
540 is treated as a regular expression, and records are
541 separated by text matching the expression.
542 .TP
543 .B RSTART
544 the start position of a string matched by
545 .BR match .
546 .TP
547 .B SUBSEP
548 separates multiple subscripts (default 034).
549 .PD
550 .PP
551 Functions may be defined (at the position of a pattern-action statement) thus:
552 .IP
553 .B
554 function foo(a, b, c) { ...; return x }
555 .PP
556 Parameters are passed by value if scalar and by reference if array name;
557 functions may be called recursively.
558 Parameters are local to the function; all other variables are global.
559 Thus local variables may be created by providing excess parameters in
560 the function definition.
561 .SH ENVIRONMENT VARIABLES
562 If
563 .B POSIXLY_CORRECT
564 is set in the environment, then
565 .I awk
566 follows the POSIX rules for
567 .B sub
568 and
569 .B gsub
570 with respect to consecutive backslashes and ampersands.
571 .SH EXAMPLES
572 .TP
573 .EX
574 length($0) > 72
575 .EE
576 Print lines longer than 72 characters.
577 .TP
578 .EX
579 { print $2, $1 }
580 .EE
581 Print first two fields in opposite order.
582 .PP
583 .EX
584 BEGIN { FS = ",[ \et]*|[ \et]+" }
585       { print $2, $1 }
586 .EE
587 .ns
588 .IP
589 Same, with input fields separated by comma and/or spaces and tabs.
590 .PP
591 .EX
592 .nf
593         { s += $1 }
594 END     { print "sum is", s, " average is", s/NR }
595 .fi
596 .EE
597 .ns
598 .IP
599 Add up first column, print sum and average.
600 .TP
601 .EX
602 /start/, /stop/
603 .EE
604 Print all lines between start/stop pairs.
605 .PP
606 .EX
607 .nf
608 BEGIN   {       # Simulate echo(1)
609         for (i = 1; i < ARGC; i++) printf "%s ", ARGV[i]
610         printf "\en"
611         exit }
612 .fi
613 .EE
614 .SH SEE ALSO
615 .IR grep (1),
616 .IR lex (1),
617 .IR sed (1)
618 .br
619 A. V. Aho, B. W. Kernighan, P. J. Weinberger,
620 .IR "The AWK Programming Language" ,
621 Addison-Wesley, 1988.  ISBN 0-201-07981-X.
622 .SH BUGS
623 There are no explicit conversions between numbers and strings.
624 To force an expression to be treated as a number add 0 to it;
625 to force it to be treated as a string concatenate
626 \&\f(CW""\fP to it.
627 .PP
628 The scope rules for variables in functions are a botch;
629 the syntax is worse.
630 .PP
631 Only eight-bit characters sets are handled correctly.
632 .SH UNUSUAL FLOATING-POINT VALUES
633 .I Awk
634 was designed before IEEE 754 arithmetic defined Not-A-Number (NaN)
635 and Infinity values, which are supported by all modern floating-point
636 hardware.
637 .PP
638 Because
639 .I awk
640 uses
641 .IR strtod (3)
642 and
643 .IR atof (3)
644 to convert string values to double-precision floating-point values,
645 modern C libraries also convert strings starting with
646 .B inf
647 and
648 .B nan
649 into infinity and NaN values respectively.  This led to strange results,
650 with something like this:
651 .PP
652 .EX
653 .nf
654 echo nancy | awk '{ print $1 + 0 }'
655 .fi
656 .EE
657 .PP
658 printing
659 .B nan
660 instead of zero.
661 .PP
662 .I Awk
663 now follows GNU AWK, and prefilters string values before attempting
664 to convert them to numbers, as follows:
665 .TP
666 .I "Hexadecimal values"
667 Hexadecimal values (allowed since C99) convert to zero, as they did
668 prior to C99.
669 .TP
670 .I "NaN values"
671 The two strings
672 .B +nan
673 and
674 .B \-nan
675 (case independent) convert to NaN. No others do.
676 (NaNs can have signs.)
677 .TP
678 .I "Infinity values"
679 The two strings
680 .B +inf
681 and
682 .B \-inf
683 (case independent) convert to positive and negative infinity, respectively.
684 No others do.