1GAWK(1) Utility Commands GAWK(1)
2
3
4
6 gawk - pattern scanning and processing language
7
9 gawk [ POSIX or GNU style options ] -f program-file [ -- ] file ...
10 gawk [ POSIX or GNU style options ] [ -- ] program-text file ...
11
12 pgawk [ POSIX or GNU style options ] -f program-file [ -- ] file ...
13 pgawk [ POSIX or GNU style options ] [ -- ] program-text file ...
14
16 Gawk is the GNU Project's implementation of the AWK programming lan‐
17 guage. It conforms to the definition of the language in the POSIX
18 1003.2 Command Language And Utilities Standard. This version in turn
19 is based on the description in The AWK Programming Language, by Aho,
20 Kernighan, and Weinberger, with the additional features found in the
21 System V Release 4 version of UNIX awk. Gawk also provides more recent
22 Bell Laboratories awk extensions, and a number of GNU-specific exten‐
23 sions.
24
25 Pgawk is the profiling version of gawk. It is identical in every way
26 to gawk, except that programs run more slowly, and it automatically
27 produces an execution profile in the file awkprof.out when done. See
28 the --profile option, below.
29
30 The command line consists of options to gawk itself, the AWK program
31 text (if not supplied via the -f or --file options), and values to be
32 made available in the ARGC and ARGV pre-defined AWK variables.
33
35 Gawk options may be either traditional POSIX one letter options, or GNU
36 style long options. POSIX options start with a single “-”, while long
37 options start with “--”. Long options are provided for both GNU-spe‐
38 cific features and for POSIX-mandated features.
39
40 Following the POSIX standard, gawk-specific options are supplied via
41 arguments to the -W option. Multiple -W options may be supplied Each
42 -W option has a corresponding long option, as detailed below. Argu‐
43 ments to long options are either joined with the option by an = sign,
44 with no intervening spaces, or they may be provided in the next command
45 line argument. Long options may be abbreviated, as long as the abbre‐
46 viation remains unique.
47
49 Gawk accepts the following options, listed alphabetically.
50
51 -F fs
52 --field-separator fs
53 Use fs for the input field separator (the value of the FS prede‐
54 fined variable).
55
56 -v var=val
57 --assign var=val
58 Assign the value val to the variable var, before execution of
59 the program begins. Such variable values are available to the
60 BEGIN block of an AWK program.
61
62 -f program-file
63 --file program-file
64 Read the AWK program source from the file program-file, instead
65 of from the first command line argument. Multiple -f (or
66 --file) options may be used.
67
68 -mf NNN
69 -mr NNN
70 Set various memory limits to the value NNN. The f flag sets the
71 maximum number of fields, and the r flag sets the maximum record
72 size. These two flags and the -m option are from the Bell Labo‐
73 ratories research version of UNIX awk. They are ignored by
74 gawk, since gawk has no pre-defined limits.
75
76 -W compat
77 -W traditional
78 --compat
79 --traditional
80 Run in compatibility mode. In compatibility mode, gawk behaves
81 identically to UNIX awk; none of the GNU-specific extensions are
82 recognized. The use of --traditional is preferred over the
83 other forms of this option. See GNU EXTENSIONS, below, for more
84 information.
85
86 -W copyleft
87 -W copyright
88 --copyleft
89 --copyright
90 Print the short version of the GNU copyright information message
91 on the standard output and exit successfully.
92
93 -W dump-variables[=file]
94 --dump-variables[=file]
95 Print a sorted list of global variables, their types and final
96 values to file. If no file is provided, gawk uses a file named
97 awkvars.out in the current directory.
98 Having a list of all the global variables is a good way to look
99 for typographical errors in your programs. You would also use
100 this option if you have a large program with a lot of functions,
101 and you want to be sure that your functions don't inadvertently
102 use global variables that you meant to be local. (This is a
103 particularly easy mistake to make with simple variable names
104 like i, j, and so on.)
105
106 -W exec file
107 --exec file
108 Similar to -f, however, this is option is the last one pro‐
109 cessed. This should be used with #! scripts, particularly for
110 CGI applications, to avoid passing in options or source code (!)
111 on the command line from a URL. This option disables command-
112 line variable assignments.
113
114 -W gen-po
115 --gen-po
116 Scan and parse the AWK program, and generate a GNU .po format
117 file on standard output with entries for all localizable strings
118 in the program. The program itself is not executed. See the
119 GNU gettext distribution for more information on .po files.
120
121 -W help
122 -W usage
123 --help
124 --usage
125 Print a relatively short summary of the available options on the
126 standard output. (Per the GNU Coding Standards, these options
127 cause an immediate, successful exit.)
128
129 -W lint[=value]
130 --lint[=value]
131 Provide warnings about constructs that are dubious or non-porta‐
132 ble to other AWK implementations. With an optional argument of
133 fatal, lint warnings become fatal errors. This may be drastic,
134 but its use will certainly encourage the development of cleaner
135 AWK programs. With an optional argument of invalid, only warn‐
136 ings about things that are actually invalid are issued. (This is
137 not fully implemented yet.)
138
139 -W lint-old
140 --lint-old
141 Provide warnings about constructs that are not portable to the
142 original version of Unix awk.
143
144 -W non-decimal-data
145 --non-decimal-data
146 Recognize octal and hexadecimal values in input data. Use this
147 option with great caution!
148
149 -W posix
150 --posix
151 This turns on compatibility mode, with the following additional
152 restrictions:
153
154 · \x escape sequences are not recognized.
155
156 · Only space and tab act as field separators when FS is set to a
157 single space, newline does not.
158
159 · You cannot continue lines after ? and :.
160
161 · The synonym func for the keyword function is not recognized.
162
163 · The operators ** and **= cannot be used in place of ^ and ^=.
164
165 · The fflush() function is not available.
166
167 -W profile[=prof_file]
168 --profile[=prof_file]
169 Send profiling data to prof_file. The default is awkprof.out.
170 When run with gawk, the profile is just a “pretty printed” ver‐
171 sion of the program. When run with pgawk, the profile contains
172 execution counts of each statement in the program in the left
173 margin and function call counts for each user-defined function.
174
175 -W re-interval
176 --re-interval
177 Enable the use of interval expressions in regular expression
178 matching (see Regular Expressions, below). Interval expressions
179 were not traditionally available in the AWK language. The POSIX
180 standard added them, to make awk and egrep consistent with each
181 other. However, their use is likely to break old AWK programs,
182 so gawk only provides them if they are requested with this
183 option, or when --posix is specified.
184
185 -W source program-text
186 --source program-text
187 Use program-text as AWK program source code. This option allows
188 the easy intermixing of library functions (used via the -f and
189 --file options) with source code entered on the command line.
190 It is intended primarily for medium to large AWK programs used
191 in shell scripts.
192
193 -W version
194 --version
195 Print version information for this particular copy of gawk on
196 the standard output. This is useful mainly for knowing if the
197 current copy of gawk on your system is up to date with respect
198 to whatever the Free Software Foundation is distributing. This
199 is also useful when reporting bugs. (Per the GNU Coding Stan‐
200 dards, these options cause an immediate, successful exit.)
201
202 -- Signal the end of options. This is useful to allow further argu‐
203 ments to the AWK program itself to start with a “-”. This is
204 mainly for consistency with the argument parsing convention used
205 by most other POSIX programs.
206 In compatibility mode, any other options are flagged as invalid, but
207 are otherwise ignored. In normal operation, as long as program text
208 has been supplied, unknown options are passed on to the AWK program in
209 the ARGV array for processing. This is particularly useful for running
210 AWK programs via the “#!” executable interpreter mechanism.
212 An AWK program consists of a sequence of pattern-action statements and
213 optional function definitions.
214 pattern { action statements }
215 function name(parameter list) { statements }
216 Gawk first reads the program source from the program-file(s) if speci‐
217 fied, from arguments to --source, or from the first non-option argument
218 on the command line. The -f and --source options may be used multiple
219 times on the command line. Gawk reads the program text as if all the
220 program-files and command line source texts had been concatenated
221 together. This is useful for building libraries of AWK functions,
222 without having to include them in each new AWK program that uses them.
223 It also provides the ability to mix library functions with command line
224 programs.
225 The environment variable AWKPATH specifies a search path to use when
226 finding source files named with the -f option. If this variable does
227 not exist, the default path is ".:/usr/local/share/awk". (The actual
228 directory may vary, depending upon how gawk was built and installed.)
229 If a file name given to the -f option contains a “/” character, no path
230 search is performed.
231 Gawk executes AWK programs in the following order. First, all variable
232 assignments specified via the -v option are performed. Next, gawk com‐
233 piles the program into an internal form. Then, gawk executes the code
234 in the BEGIN block(s) (if any), and then proceeds to read each file
235 named in the ARGV array. If there are no files named on the command
236 line, gawk reads the standard input.
237 If a filename on the command line has the form var=val it is treated as
238 a variable assignment. The variable var will be assigned the value
239 val. (This happens after any BEGIN block(s) have been run.) Command
240 line variable assignment is most useful for dynamically assigning val‐
241 ues to the variables AWK uses to control how input is broken into
242 fields and records. It is also useful for controlling state if multi‐
243 ple passes are needed over a single data file.
244 If the value of a particular element of ARGV is empty (""), gawk skips
245 over it.
246 For each record in the input, gawk tests to see if it matches any pat‐
247 tern in the AWK program. For each pattern that the record matches, the
248 associated action is executed. The patterns are tested in the order
249 they occur in the program.
250 Finally, after all the input is exhausted, gawk executes the code in
251 the END block(s) (if any).
253 AWK variables are dynamic; they come into existence when they are first
254 used. Their values are either floating-point numbers or strings, or
255 both, depending upon how they are used. AWK also has one dimensional
256 arrays; arrays with multiple dimensions may be simulated. Several pre-
257 defined variables are set as a program runs; these will be described as
258 needed and summarized below.
259 Records
260 Normally, records are separated by newline characters. You can control
261 how records are separated by assigning values to the built-in variable
262 RS. If RS is any single character, that character separates records.
263 Otherwise, RS is a regular expression. Text in the input that matches
264 this regular expression separates the record. However, in compatibil‐
265 ity mode, only the first character of its string value is used for sep‐
266 arating records. If RS is set to the null string, then records are
267 separated by blank lines. When RS is set to the null string, the new‐
268 line character always acts as a field separator, in addition to what‐
269 ever value FS may have.
270 Fields
271 As each input record is read, gawk splits the record into fields, using
272 the value of the FS variable as the field separator. If FS is a single
273 character, fields are separated by that character. If FS is the null
274 string, then each individual character becomes a separate field. Oth‐
275 erwise, FS is expected to be a full regular expression. In the special
276 case that FS is a single space, fields are separated by runs of spaces
277 and/or tabs and/or newlines. (But see the discussion of --posix,
278 below). NOTE: The value of IGNORECASE (see below) also affects how
279 fields are split when FS is a regular expression, and how records are
280 separated when RS is a regular expression.
281 If the FIELDWIDTHS variable is set to a space separated list of num‐
282 bers, each field is expected to have fixed width, and gawk splits up
283 the record using the specified widths. The value of FS is ignored.
284 Assigning a new value to FS overrides the use of FIELDWIDTHS, and
285 restores the default behavior.
286 Each field in the input record may be referenced by its position, $1,
287 $2, and so on. $0 is the whole record. Fields need not be referenced
288 by constants:
289 n = 5
290 print $n
291 prints the fifth field in the input record.
292 The variable NF is set to the total number of fields in the input
293 record.
294 References to non-existent fields (i.e. fields after $NF) produce the
295 null-string. However, assigning to a non-existent field (e.g., $(NF+2)
296 = 5) increases the value of NF, creates any intervening fields with the
297 null string as their value, and causes the value of $0 to be recom‐
298 puted, with the fields being separated by the value of OFS. References
299 to negative numbered fields cause a fatal error. Decrementing NF
300 causes the values of fields past the new value to be lost, and the
301 value of $0 to be recomputed, with the fields being separated by the
302 value of OFS.
303 Assigning a value to an existing field causes the whole record to be
304 rebuilt when $0 is referenced. Similarly, assigning a value to $0
305 causes the record to be resplit, creating new values for the fields.
306 Built-in Variables
307 Gawk's built-in variables are:
308 ARGC The number of command line arguments (does not include
309 options to gawk, or the program source).
310 ARGIND The index in ARGV of the current file being processed.
311 ARGV Array of command line arguments. The array is indexed from
312 0 to ARGC - 1. Dynamically changing the contents of ARGV
313 can control the files used for data.
314 BINMODE On non-POSIX systems, specifies use of “binary” mode for
315 all file I/O. Numeric values of 1, 2, or 3, specify that
316 input files, output files, or all files, respectively,
317 should use binary I/O. String values of "r", or "w" spec‐
318 ify that input files, or output files, respectively, should
319 use binary I/O. String values of "rw" or "wr" specify that
320 all files should use binary I/O. Any other string value is
321 treated as "rw", but generates a warning message.
322 CONVFMT The conversion format for numbers, "%.6g", by default.
323 ENVIRON An array containing the values of the current environment.
324 The array is indexed by the environment variables, each
325 element being the value of that variable (e.g., ENVI‐
326 RON["HOME"] might be /home/arnold). Changing this array
327 does not affect the environment seen by programs which gawk
328 spawns via redirection or the system() function.
329 ERRNO If a system error occurs either doing a redirection for
330 getline, during a read for getline, or during a close(),
331 then ERRNO will contain a string describing the error. The
332 value is subject to translation in non-English locales.
333 FIELDWIDTHS A white-space separated list of fieldwidths. When set,
334 gawk parses the input into fields of fixed width, instead
335 of using the value of the FS variable as the field separa‐
336 tor.
337 FILENAME The name of the current input file. If no files are speci‐
338 fied on the command line, the value of FILENAME is “-”.
339 However, FILENAME is undefined inside the BEGIN block
340 (unless set by getline).
341 FNR The input record number in the current input file.
342 FS The input field separator, a space by default. See Fields,
343 above.
344 IGNORECASE Controls the case-sensitivity of all regular expression and
345 string operations. If IGNORECASE has a non-zero value,
346 then string comparisons and pattern matching in rules,
347 field splitting with FS, record separating with RS, regular
348 expression matching with ~ and !~, and the gensub(),
349 gsub(), index(), match(), split(), and sub() built-in func‐
350 tions all ignore case when doing regular expression opera‐
351 tions. NOTE: Array subscripting is not affected. However,
352 the asort() and asorti() functions are affected.
353 Thus, if IGNORECASE is not equal to zero, /aB/ matches all
354 of the strings "ab", "aB", "Ab", and "AB". As with all AWK
355 variables, the initial value of IGNORECASE is zero, so all
356 regular expression and string operations are normally case-
357 sensitive. Under Unix, the full ISO 8859-1 Latin-1 charac‐
358 ter set is used when ignoring case. As of gawk 3.1.4, the
359 case equivalencies are fully locale-aware, based on the C
360 <ctype.h> facilities such as isalpha(), and tolupper().
361 LINT Provides dynamic control of the --lint option from within
362 an AWK program. When true, gawk prints lint warnings. When
363 false, it does not. When assigned the string value
364 "fatal", lint warnings become fatal errors, exactly like
365 --lint=fatal. Any other true value just prints warnings.
366 NF The number of fields in the current input record.
367 NR The total number of input records seen so far.
368 OFMT The output format for numbers, "%.6g", by default.
369 OFS The output field separator, a space by default.
370 ORS The output record separator, by default a newline.
371 PROCINFO The elements of this array provide access to information
372 about the running AWK program. On some systems, there may
373 be elements in the array, "group1" through "groupn" for
374 some n, which is the number of supplementary groups that
375 the process has. Use the in operator to test for these
376 elements. The following elements are guaranteed to be
377 available:
378 PROCINFO["egid"] the value of the getegid(2) system call.
379 PROCINFO["euid"] the value of the geteuid(2) system call.
380 PROCINFO["FS"] "FS" if field splitting with FS is in
381 effect, or "FIELDWIDTHS" if field split‐
382 ting with FIELDWIDTHS is in effect.
383 PROCINFO["gid"] the value of the getgid(2) system call.
384 PROCINFO["pgrpid"] the process group ID of the current
385 process.
386 PROCINFO["pid"] the process ID of the current process.
387 PROCINFO["ppid"] the parent process ID of the current
388 process.
389 PROCINFO["uid"] the value of the getuid(2) system call.
390 PROCINFO["version"]
391 The version of gawk. This is available
392 from version 3.1.4 and later.
393 RS The input record separator, by default a newline.
394 RT The record terminator. Gawk sets RT to the input text that
395 matched the character or regular expression specified by
396 RS.
397 RSTART The index of the first character matched by match(); 0 if
398 no match. (This implies that character indices start at
399 one.)
400 RLENGTH The length of the string matched by match(); -1 if no
401 match.
402 SUBSEP The character used to separate multiple subscripts in array
403 elements, by default "\034".
404 TEXTDOMAIN The text domain of the AWK program; used to find the local‐
405 ized translations for the program's strings.
406 Arrays
407 Arrays are subscripted with an expression between square brackets ([
408 and ]). If the expression is an expression list (expr, expr ...) then
409 the array subscript is a string consisting of the concatenation of the
410 (string) value of each expression, separated by the value of the SUBSEP
411 variable. This facility is used to simulate multiply dimensioned
412 arrays. For example:
413 i = "A"; j = "B"; k = "C"
414 x[i, j, k] = "hello, world\n"
415 assigns the string "hello, world\n" to the element of the array x which
416 is indexed by the string "A\034B\034C". All arrays in AWK are associa‐
417 tive, i.e. indexed by string values.
418 The special operator in may be used in an if or while statement to see
419 if an array has an index consisting of a particular value.
420 if (val in array)
421 print array[val]
422 If the array has multiple subscripts, use (i, j) in array.
423 The in construct may also be used in a for loop to iterate over all the
424 elements of an array.
425 An element may be deleted from an array using the delete statement.
426 The delete statement may also be used to delete the entire contents of
427 an array, just by specifying the array name without a subscript.
428 Variable Typing And Conversion
429 Variables and fields may be (floating point) numbers, or strings, or
430 both. How the value of a variable is interpreted depends upon its con‐
431 text. If used in a numeric expression, it will be treated as a number,
432 if used as a string it will be treated as a string.
433 To force a variable to be treated as a number, add 0 to it; to force it
434 to be treated as a string, concatenate it with the null string.
435 When a string must be converted to a number, the conversion is accom‐
436 plished using strtod(3). A number is converted to a string by using
437 the value of CONVFMT as a format string for sprintf(3), with the
438 numeric value of the variable as the argument. However, even though
439 all numbers in AWK are floating-point, integral values are always con‐
440 verted as integers. Thus, given
441 CONVFMT = "%2.2f"
442 a = 12
443 b = a ""
444 the variable b has a string value of "12" and not "12.00".
445 Gawk performs comparisons as follows: If two variables are numeric,
446 they are compared numerically. If one value is numeric and the other
447 has a string value that is a “numeric string,” then comparisons are
448 also done numerically. Otherwise, the numeric value is converted to a
449 string and a string comparison is performed. Two strings are compared,
450 of course, as strings. Note that the POSIX standard applies the con‐
451 cept of “numeric string” everywhere, even to string constants. How‐
452 ever, this is clearly incorrect, and gawk does not do this. (Fortu‐
453 nately, this is fixed in the next version of the standard.)
454 Note that string constants, such as "57", are not numeric strings, they
455 are string constants. The idea of “numeric string” only applies to
456 fields, getline input, FILENAME, ARGV elements, ENVIRON elements and
457 the elements of an array created by split() that are numeric strings.
458 The basic idea is that user input, and only user input, that looks
459 numeric, should be treated that way.
460 Uninitialized variables have the numeric value 0 and the string value
461 "" (the null, or empty, string).
462 Octal and Hexadecimal Constants
463 Starting with version 3.1 of gawk , you may use C-style octal and hexa‐
464 decimal constants in your AWK program source code. For example, the
465 octal value 011 is equal to decimal 9, and the hexadecimal value 0x11
466 is equal to decimal 17.
467 String Constants
468 String constants in AWK are sequences of characters enclosed between
469 double quotes ("). Within strings, certain escape sequences are recog‐
470 nized, as in C. These are:
471 \\ A literal backslash.
472 \a The “alert” character; usually the ASCII BEL character.
473 \b backspace.
474 \f form-feed.
475 \n newline.
476 \r carriage return.
477 \t horizontal tab.
478 \v vertical tab.
479 \xhex digits
480 The character represented by the string of hexadecimal digits fol‐
481 lowing the \x. As in ANSI C, all following hexadecimal digits are
482 considered part of the escape sequence. (This feature should tell
483 us something about language design by committee.) E.g., "\x1B" is
484 the ASCII ESC (escape) character.
485 \ddd The character represented by the 1-, 2-, or 3-digit sequence of
486 octal digits. E.g., "\033" is the ASCII ESC (escape) character.
487 \c The literal character c.
488 The escape sequences may also be used inside constant regular expres‐
489 sions (e.g., /[ \t\f\n\r\v]/ matches whitespace characters).
490 In compatibility mode, the characters represented by octal and hexadec‐
491 imal escape sequences are treated literally when used in regular
492 expression constants. Thus, /a\52b/ is equivalent to /a\*b/.
494 AWK is a line-oriented language. The pattern comes first, and then the
495 action. Action statements are enclosed in { and }. Either the pattern
496 may be missing, or the action may be missing, but, of course, not both.
497 If the pattern is missing, the action is executed for every single
498 record of input. A missing action is equivalent to
499 { print }
500 which prints the entire record.
501 Comments begin with the “#” character, and continue until the end of
502 the line. Blank lines may be used to separate statements. Normally, a
503 statement ends with a newline, however, this is not the case for lines
504 ending in a “,”, {, ?, :, &&, or ||. Lines ending in do or else also
505 have their statements automatically continued on the following line.
506 In other cases, a line can be continued by ending it with a “\”, in
507 which case the newline will be ignored.
508 Multiple statements may be put on one line by separating them with a
509 “;”. This applies to both the statements within the action part of a
510 pattern-action pair (the usual case), and to the pattern-action state‐
511 ments themselves.
512 Patterns
513 AWK patterns may be one of the following:
514 BEGIN
515 END
516 /regular expression/
517 relational expression
518 pattern && pattern
519 pattern || pattern
520 pattern ? pattern : pattern
521 (pattern)
522 ! pattern
523 pattern1, pattern2
524 BEGIN and END are two special kinds of patterns which are not tested
525 against the input. The action parts of all BEGIN patterns are merged
526 as if all the statements had been written in a single BEGIN block.
527 They are executed before any of the input is read. Similarly, all the
528 END blocks are merged, and executed when all the input is exhausted (or
529 when an exit statement is executed). BEGIN and END patterns cannot be
530 combined with other patterns in pattern expressions. BEGIN and END
531 patterns cannot have missing action parts.
532 For /regular expression/ patterns, the associated statement is executed
533 for each input record that matches the regular expression. Regular
534 expressions are the same as those in egrep(1), and are summarized
535 below.
536 A relational expression may use any of the operators defined below in
537 the section on actions. These generally test whether certain fields
538 match certain regular expressions.
539 The &&, ||, and ! operators are logical AND, logical OR, and logical
540 NOT, respectively, as in C. They do short-circuit evaluation, also as
541 in C, and are used for combining more primitive pattern expressions.
542 As in most languages, parentheses may be used to change the order of
543 evaluation.
544 The ?: operator is like the same operator in C. If the first pattern
545 is true then the pattern used for testing is the second pattern, other‐
546 wise it is the third. Only one of the second and third patterns is
547 evaluated.
548 The pattern1, pattern2 form of an expression is called a range pattern.
549 It matches all input records starting with a record that matches pat‐
550 tern1, and continuing until a record that matches pattern2, inclusive.
551 It does not combine with any other sort of pattern expression.
552 Regular Expressions
553 Regular expressions are the extended kind found in egrep. They are
554 composed of characters as follows:
555 c matches the non-metacharacter c.
556 \c matches the literal character c.
557 . matches any character including newline.
558 ^ matches the beginning of a string.
559 $ matches the end of a string.
560 [abc...] character list, matches any of the characters abc....
561 [^abc...] negated character list, matches any character except abc....
562 r1|r2 alternation: matches either r1 or r2.
563 r1r2 concatenation: matches r1, and then r2.
564 r+ matches one or more r's.
565 r* matches zero or more r's.
566 r? matches zero or one r's.
567 (r) grouping: matches r.
568 r{n}
569 r{n,}
570 r{n,m} One or two numbers inside braces denote an interval expres‐
571 sion. If there is one number in the braces, the preceding
572 regular expression r is repeated n times. If there are two
573 numbers separated by a comma, r is repeated n to m times.
574 If there is one number followed by a comma, then r is
575 repeated at least n times.
576 Interval expressions are only available if either --posix or
577 --re-interval is specified on the command line.
578
579 \y matches the empty string at either the beginning or the end
580 of a word.
581
582 \B matches the empty string within a word.
583
584 \< matches the empty string at the beginning of a word.
585
586 \> matches the empty string at the end of a word.
587
588 \w matches any word-constituent character (letter, digit, or
589 underscore).
590
591 \W matches any character that is not word-constituent.
592
593 \` matches the empty string at the beginning of a buffer
594 (string).
595
596 \' matches the empty string at the end of a buffer.
597
598 The escape sequences that are valid in string constants (see below) are
599 also valid in regular expressions.
600
601 Character classes are a new feature introduced in the POSIX standard.
602 A character class is a special notation for describing lists of charac‐
603 ters that have a specific attribute, but where the actual characters
604 themselves can vary from country to country and/or from character set
605 to character set. For example, the notion of what is an alphabetic
606 character differs in the USA and in France.
607
608 A character class is only valid in a regular expression inside the
609 brackets of a character list. Character classes consist of [:, a key‐
610 word denoting the class, and :]. The character classes defined by the
611 POSIX standard are:
612
613 [:alnum:] Alphanumeric characters.
614
615 [:alpha:] Alphabetic characters.
616
617 [:blank:] Space or tab characters.
618
619 [:cntrl:] Control characters.
620
621 [:digit:] Numeric characters.
622
623 [:graph:] Characters that are both printable and visible. (A space is
624 printable, but not visible, while an a is both.)
625
626 [:lower:] Lower-case alphabetic characters.
627
628 [:print:] Printable characters (characters that are not control char‐
629 acters.)
630
631 [:punct:] Punctuation characters (characters that are not letter, dig‐
632 its, control characters, or space characters).
633
634 [:space:] Space characters (such as space, tab, and formfeed, to name
635 a few).
636
637 [:upper:] Upper-case alphabetic characters.
638
639 [:xdigit:] Characters that are hexadecimal digits.
640
641 For example, before the POSIX standard, to match alphanumeric charac‐
642 ters, you would have had to write /[A-Za-z0-9]/. If your character set
643 had other alphabetic characters in it, this would not match them, and
644 if your character set collated differently from ASCII, this might not
645 even match the ASCII alphanumeric characters. With the POSIX character
646 classes, you can write /[[:alnum:]]/, and this matches the alphabetic
647 and numeric characters in your character set.
648
649 Two additional special sequences can appear in character lists. These
650 apply to non-ASCII character sets, which can have single symbols
651 (called collating elements) that are represented with more than one
652 character, as well as several characters that are equivalent for col‐
653 lating, or sorting, purposes. (E.g., in French, a plain “e” and a
654 grave-accented e` are equivalent.)
655
656 Collating Symbols
657 A collating symbol is a multi-character collating element
658 enclosed in [. and .]. For example, if ch is a collating ele‐
659 ment, then [[.ch.]] is a regular expression that matches this
660 collating element, while [ch] is a regular expression that
661 matches either c or h.
662
663 Equivalence Classes
664 An equivalence class is a locale-specific name for a list of
665 characters that are equivalent. The name is enclosed in [= and
666 =]. For example, the name e might be used to represent all of
667 “e,” “e´,” and “e`.” In this case, [[=e=]] is a regular expres‐
668 sion that matches any of e, e´, or e`.
669
670 These features are very valuable in non-English speaking locales. The
671 library functions that gawk uses for regular expression matching cur‐
672 rently only recognize POSIX character classes; they do not recognize
673 collating symbols or equivalence classes.
674
675 The \y, \B, \<, \>, \w, \W, \`, and \' operators are specific to gawk;
676 they are extensions based on facilities in the GNU regular expression
677 libraries.
678
679 The various command line options control how gawk interprets characters
680 in regular expressions.
681
682 No options
683 In the default case, gawk provide all the facilities of POSIX
684 regular expressions and the GNU regular expression operators
685 described above. However, interval expressions are not sup‐
686 ported.
687
688 --posix
689 Only POSIX regular expressions are supported, the GNU operators
690 are not special. (E.g., \w matches a literal w). Interval
691 expressions are allowed.
692
693 --traditional
694 Traditional Unix awk regular expressions are matched. The GNU
695 operators are not special, interval expressions are not avail‐
696 able, and neither are the POSIX character classes ([[:alnum:]]
697 and so on). Characters described by octal and hexadecimal
698 escape sequences are treated literally, even if they represent
699 regular expression metacharacters.
700
701 --re-interval
702 Allow interval expressions in regular expressions, even if
703 --traditional has been provided.
704
705 Actions
706 Action statements are enclosed in braces, { and }. Action statements
707 consist of the usual assignment, conditional, and looping statements
708 found in most languages. The operators, control statements, and
709 input/output statements available are patterned after those in C.
710
711 Operators
712 The operators in AWK, in order of decreasing precedence, are
713
714 (...) Grouping
715
716 $ Field reference.
717
718 ++ -- Increment and decrement, both prefix and postfix.
719
720 ^ Exponentiation (** may also be used, and **= for the
721 assignment operator).
722
723 + - ! Unary plus, unary minus, and logical negation.
724
725 * / % Multiplication, division, and modulus.
726
727 + - Addition and subtraction.
728
729 space String concatenation.
730
731 < >
732 <= >=
733 != == The regular relational operators.
734
735 ~ !~ Regular expression match, negated match. NOTE: Do not use
736 a constant regular expression (/foo/) on the left-hand side
737 of a ~ or !~. Only use one on the right-hand side. The
738 expression /foo/ ~ exp has the same meaning as (($0 ~
739 /foo/) ~ exp). This is usually not what was intended.
740
741 in Array membership.
742
743 && Logical AND.
744
745 || Logical OR.
746
747 ?: The C conditional expression. This has the form expr1 ?
748 expr2 : expr3. If expr1 is true, the value of the expres‐
749 sion is expr2, otherwise it is expr3. Only one of expr2
750 and expr3 is evaluated.
751
752 = += -=
753 *= /= %= ^= Assignment. Both absolute assignment (var = value) and
754 operator-assignment (the other forms) are supported.
755
756 Control Statements
757 The control statements are as follows:
758
759 if (condition) statement [ else statement ]
760 while (condition) statement
761 do statement while (condition)
762 for (expr1; expr2; expr3) statement
763 for (var in array) statement
764 break
765 continue
766 delete array[index]
767 delete array
768 exit [ expression ]
769 { statements }
770
771 I/O Statements
772 The input/output statements are as follows:
773
774 close(file [, how]) Close file, pipe or co-process. The optional how
775 should only be used when closing one end of a
776 two-way pipe to a co-process. It must be a
777 string value, either "to" or "from".
778
779 getline Set $0 from next input record; set NF, NR, FNR.
780
781 getline <file Set $0 from next record of file; set NF.
782
783 getline var Set var from next input record; set NR, FNR.
784
785 getline var <file Set var from next record of file.
786
787 command | getline [var]
788 Run command piping the output either into $0 or
789 var, as above.
790
791 command |& getline [var]
792 Run command as a co-process piping the output
793 either into $0 or var, as above. Co-processes
794 are a gawk extension.
795
796 next Stop processing the current input record. The
797 next input record is read and processing starts
798 over with the first pattern in the AWK program.
799 If the end of the input data is reached, the END
800 block(s), if any, are executed.
801
802 nextfile Stop processing the current input file. The next
803 input record read comes from the next input file.
804 FILENAME and ARGIND are updated, FNR is reset to
805 1, and processing starts over with the first pat‐
806 tern in the AWK program. If the end of the input
807 data is reached, the END block(s), if any, are
808 executed.
809
810 print Prints the current record. The output record is
811 terminated with the value of the ORS variable.
812
813 print expr-list Prints expressions. Each expression is separated
814 by the value of the OFS variable. The output
815 record is terminated with the value of the ORS
816 variable.
817
818 print expr-list >file Prints expressions on file. Each expression is
819 separated by the value of the OFS variable. The
820 output record is terminated with the value of the
821 ORS variable.
822
823 printf fmt, expr-list Format and print.
824
825 printf fmt, expr-list >file
826 Format and print on file.
827
828 system(cmd-line) Execute the command cmd-line, and return the exit
829 status. (This may not be available on non-POSIX
830 systems.)
831
832 fflush([file]) Flush any buffers associated with the open output
833 file or pipe file. If file is missing, then
834 standard output is flushed. If file is the null
835 string, then all open output files and pipes have
836 their buffers flushed.
837
838 Additional output redirections are allowed for print and printf.
839
840 print ... >> file
841 appends output to the file.
842
843 print ... | command
844 writes on a pipe.
845
846 print ... |& command
847 sends data to a co-process.
848
849 The getline command returns 0 on end of file and -1 on an error. Upon
850 an error, ERRNO contains a string describing the problem.
851
852 NOTE: If using a pipe or co-process to getline, or from print or printf
853 within a loop, you must use close() to create new instances of the com‐
854 mand. AWK does not automatically close pipes or co-processes when they
855 return EOF.
856
857 The printf Statement
858 The AWK versions of the printf statement and sprintf() function (see
859 below) accept the following conversion specification formats:
860
861 %c An ASCII character. If the argument used for %c is numeric, it
862 is treated as a character and printed. Otherwise, the argument
863 is assumed to be a string, and the only first character of that
864 string is printed.
865
866 %d, %i A decimal number (the integer part).
867
868 %e , %E
869 A floating point number of the form [-]d.dddddde[+-]dd. The %E
870 format uses E instead of e.
871
872 %f A floating point number of the form [-]ddd.dddddd.
873
874 %g , %G
875 Use %e or %f conversion, whichever is shorter, with nonsignifi‐
876 cant zeros suppressed. The %G format uses %E instead of %e.
877
878 %o An unsigned octal number (also an integer).
879
880 %u An unsigned decimal number (again, an integer).
881
882 %s A character string.
883
884 %x , %X
885 An unsigned hexadecimal number (an integer). The %X format
886 uses ABCDEF instead of abcdef.
887
888 %% A single % character; no argument is converted.
889
890 NOTE: When using the integer format-control letters for values that are
891 outside the range of a C long integer, gawk switches to the %g format
892 specifier. If --lint is provided on the command line gawk warns about
893 this. Other versions of awk may print invalid values or do something
894 else entirely.
895
896 Optional, additional parameters may lie between the % and the control
897 letter:
898
899 count$ Use the count'th argument at this point in the formatting. This
900 is called a positional specifier and is intended primarily for
901 use in translated versions of format strings, not in the origi‐
902 nal text of an AWK program. It is a gawk extension.
903
904 - The expression should be left-justified within its field.
905
906 space For numeric conversions, prefix positive values with a space,
907 and negative values with a minus sign.
908
909 + The plus sign, used before the width modifier (see below), says
910 to always supply a sign for numeric conversions, even if the
911 data to be formatted is positive. The + overrides the space
912 modifier.
913
914 # Use an “alternate form” for certain control letters. For %o,
915 supply a leading zero. For %x, and %X, supply a leading 0x or
916 0X for a nonzero result. For %e, %E, and %f, the result always
917 contains a decimal point. For %g, and %G, trailing zeros are
918 not removed from the result.
919
920 0 A leading 0 (zero) acts as a flag, that indicates output should
921 be padded with zeroes instead of spaces. This applies even to
922 non-numeric output formats. This flag only has an effect when
923 the field width is wider than the value to be printed.
924
925 width The field should be padded to this width. The field is normally
926 padded with spaces. If the 0 flag has been used, it is padded
927 with zeroes.
928
929 .prec A number that specifies the precision to use when printing. For
930 the %e, %E, and %f formats, this specifies the number of digits
931 you want printed to the right of the decimal point. For the %g,
932 and %G formats, it specifies the maximum number of significant
933 digits. For the %d, %o, %i, %u, %x, and %X formats, it speci‐
934 fies the minimum number of digits to print. For %s, it speci‐
935 fies the maximum number of characters from the string that
936 should be printed.
937
938 The dynamic width and prec capabilities of the ANSI C printf() routines
939 are supported. A * in place of either the width or prec specifications
940 causes their values to be taken from the argument list to printf or
941 sprintf(). To use a positional specifier with a dynamic width or pre‐
942 cision, supply the count$ after the * in the format string. For exam‐
943 ple, "%3$*2$.*1$s".
944
945 Special File Names
946 When doing I/O redirection from either print or printf into a file, or
947 via getline from a file, gawk recognizes certain special filenames
948 internally. These filenames allow access to open file descriptors
949 inherited from gawk's parent process (usually the shell). These file
950 names may also be used on the command line to name data files. The
951 filenames are:
952
953 /dev/stdin The standard input.
954
955 /dev/stdout The standard output.
956
957 /dev/stderr The standard error output.
958
959 /dev/fd/n The file associated with the open file descriptor n.
960
961 These are particularly useful for error messages. For example:
962
963 print "You blew it!" > "/dev/stderr"
964
965 whereas you would otherwise have to use
966
967 print "You blew it!" | "cat 1>&2"
968
969 The following special filenames may be used with the |& co-process
970 operator for creating TCP/IP network connections.
971
972 /inet/tcp/lport/rhost/rport File for TCP/IP connection on local port
973 lport to remote host rhost on remote port
974 rport. Use a port of 0 to have the system
975 pick a port.
976
977 /inet/udp/lport/rhost/rport Similar, but use UDP/IP instead of TCP/IP.
978
979 /inet/raw/lport/rhost/rport Reserved for future use.
980
981 Other special filenames provide access to information about the running
982 gawk process. These filenames are now obsolete. Use the PROCINFO
983 array to obtain the information they provide. The filenames are:
984
985 /dev/pid Reading this file returns the process ID of the current
986 process, in decimal, terminated with a newline.
987
988 /dev/ppid Reading this file returns the parent process ID of the cur‐
989 rent process, in decimal, terminated with a newline.
990
991 /dev/pgrpid Reading this file returns the process group ID of the cur‐
992 rent process, in decimal, terminated with a newline.
993
994 /dev/user Reading this file returns a single record terminated with a
995 newline. The fields are separated with spaces. $1 is the
996 value of the getuid(2) system call, $2 is the value of the
997 geteuid(2) system call, $3 is the value of the getgid(2)
998 system call, and $4 is the value of the getegid(2) system
999 call. If there are any additional fields, they are the
1000 group IDs returned by getgroups(2). Multiple groups may
1001 not be supported on all systems.
1002
1003 Numeric Functions
1004 AWK has the following built-in arithmetic functions:
1005
1006 atan2(y, x) Returns the arctangent of y/x in radians.
1007
1008 cos(expr) Returns the cosine of expr, which is in radians.
1009
1010 exp(expr) The exponential function.
1011
1012 int(expr) Truncates to integer.
1013
1014 log(expr) The natural logarithm function.
1015
1016 rand() Returns a random number N, between 0 and 1, such that 0 ≤
1017 N < 1.
1018
1019 sin(expr) Returns the sine of expr, which is in radians.
1020
1021 sqrt(expr) The square root function.
1022
1023 srand([expr]) Uses expr as a new seed for the random number generator.
1024 If no expr is provided, the time of day is used. The
1025 return value is the previous seed for the random number
1026 generator.
1027
1028 String Functions
1029 Gawk has the following built-in string functions:
1030
1031 asort(s [, d]) Returns the number of elements in the source
1032 array s. The contents of s are sorted using
1033 gawk's normal rules for comparing values, and
1034 the indexes of the sorted values of s are
1035 replaced with sequential integers starting with
1036 1. If the optional destination array d is spec‐
1037 ified, then s is first duplicated into d, and
1038 then d is sorted, leaving the indexes of the
1039 source array s unchanged.
1040
1041 asorti(s [, d]) Returns the number of elements in the source
1042 array s. The behavior is the same as that of
1043 asort(), except that the array indices are used
1044 for sorting, not the array values. When done,
1045 the array is indexed numerically, and the val‐
1046 ues are those of the original indices. The
1047 original values are lost; thus provide a second
1048 array if you wish to preserve the original.
1049
1050 gensub(r, s, h [, t]) Search the target string t for matches of the
1051 regular expression r. If h is a string begin‐
1052 ning with g or G, then replace all matches of r
1053 with s. Otherwise, h is a number indicating
1054 which match of r to replace. If t is not sup‐
1055 plied, $0 is used instead. Within the replace‐
1056 ment text s, the sequence \n, where n is a
1057 digit from 1 to 9, may be used to indicate just
1058 the text that matched the n'th parenthesized
1059 subexpression. The sequence \0 represents the
1060 entire matched text, as does the character &.
1061 Unlike sub() and gsub(), the modified string is
1062 returned as the result of the function, and the
1063 original target string is not changed.
1064
1065 gsub(r, s [, t]) For each substring matching the regular expres‐
1066 sion r in the string t, substitute the string
1067 s, and return the number of substitutions. If
1068 t is not supplied, use $0. An & in the
1069 replacement text is replaced with the text that
1070 was actually matched. Use \& to get a literal
1071 &. (This must be typed as "\\&"; see GAWK:
1072 Effective AWK Programming for a fuller discus‐
1073 sion of the rules for &'s and backslashes in
1074 the replacement text of sub(), gsub(), and gen‐
1075 sub().)
1076
1077 index(s, t) Returns the index of the string t in the string
1078 s, or 0 if t is not present. (This implies
1079 that character indices start at one.)
1080
1081 length([s]) Returns the length of the string s, or the
1082 length of $0 if s is not supplied. Starting
1083 with version 3.1.5, as a non-standard exten‐
1084 sion, with an array argument, length() returns
1085 the number of elements in the array.
1086
1087 match(s, r [, a]) Returns the position in s where the regular
1088 expression r occurs, or 0 if r is not present,
1089 and sets the values of RSTART and RLENGTH.
1090 Note that the argument order is the same as for
1091 the ~ operator: str ~ re. If array a is pro‐
1092 vided, a is cleared and then elements 1 through
1093 n are filled with the portions of s that match
1094 the corresponding parenthesized subexpression
1095 in r. The 0'th element of a contains the por‐
1096 tion of s matched by the entire regular expres‐
1097 sion r. Subscripts a[n, "start"], and a[n,
1098 "length"] provide the starting index in the
1099 string and length respectively, of each match‐
1100 ing substring.
1101
1102 split(s, a [, r]) Splits the string s into the array a on the
1103 regular expression r, and returns the number of
1104 fields. If r is omitted, FS is used instead.
1105 The array a is cleared first. Splitting
1106 behaves identically to field splitting,
1107 described above.
1108
1109 sprintf(fmt, expr-list) Prints expr-list according to fmt, and returns
1110 the resulting string.
1111
1112 strtonum(str) Examines str, and returns its numeric value.
1113 If str begins with a leading 0, strtonum()
1114 assumes that str is an octal number. If str
1115 begins with a leading 0x or 0X, strtonum()
1116 assumes that str is a hexadecimal number.
1117
1118 sub(r, s [, t]) Just like gsub(), but only the first matching
1119 substring is replaced.
1120
1121 substr(s, i [, n]) Returns the at most n-character substring of s
1122 starting at i. If n is omitted, the rest of s
1123 is used.
1124
1125 tolower(str) Returns a copy of the string str, with all the
1126 upper-case characters in str translated to
1127 their corresponding lower-case counterparts.
1128 Non-alphabetic characters are left unchanged.
1129
1130 toupper(str) Returns a copy of the string str, with all the
1131 lower-case characters in str translated to
1132 their corresponding upper-case counterparts.
1133 Non-alphabetic characters are left unchanged.
1134
1135 Time Functions
1136 Since one of the primary uses of AWK programs is processing log files
1137 that contain time stamp information, gawk provides the following func‐
1138 tions for obtaining time stamps and formatting them.
1139
1140 mktime(datespec)
1141 Turns datespec into a time stamp of the same form as returned
1142 by systime(). The datespec is a string of the form YYYY MM
1143 DD HH MM SS[ DST]. The contents of the string are six or
1144 seven numbers representing respectively the full year includ‐
1145 ing century, the month from 1 to 12, the day of the month
1146 from 1 to 31, the hour of the day from 0 to 23, the minute
1147 from 0 to 59, and the second from 0 to 60, and an optional
1148 daylight saving flag. The values of these numbers need not
1149 be within the ranges specified; for example, an hour of -1
1150 means 1 hour before midnight. The origin-zero Gregorian cal‐
1151 endar is assumed, with year 0 preceding year 1 and year -1
1152 preceding year 0. The time is assumed to be in the local
1153 timezone. If the daylight saving flag is positive, the time
1154 is assumed to be daylight saving time; if zero, the time is
1155 assumed to be standard time; and if negative (the default),
1156 mktime() attempts to determine whether daylight saving time
1157 is in effect for the specified time. If datespec does not
1158 contain enough elements or if the resulting time is out of
1159 range, mktime() returns -1.
1160
1161 strftime([format [, timestamp]])
1162 Formats timestamp according to the specification in format.
1163 The timestamp should be of the same form as returned by sys‐
1164 time(). If timestamp is missing, the current time of day is
1165 used. If format is missing, a default format equivalent to
1166 the output of date(1) is used. See the specification for the
1167 strftime() function in ANSI C for the format conversions that
1168 are guaranteed to be available. A public-domain version of
1169 strftime(3) and a man page for it come with gawk; if that
1170 version was used to build gawk, then all of the conversions
1171 described in that man page are available to gawk.
1172
1173 systime() Returns the current time of day as the number of seconds
1174 since the Epoch (1970-01-01 00:00:00 UTC on POSIX systems).
1175
1176 Bit Manipulations Functions
1177 Starting with version 3.1 of gawk, the following bit manipulation func‐
1178 tions are available. They work by converting double-precision floating
1179 point values to unsigned long integers, doing the operation, and then
1180 converting the result back to floating point. The functions are:
1181
1182 and(v1, v2) Return the bitwise AND of the values provided by v1
1183 and v2.
1184
1185 compl(val) Return the bitwise complement of val.
1186
1187 lshift(val, count) Return the value of val, shifted left by count
1188 bits.
1189
1190 or(v1, v2) Return the bitwise OR of the values provided by v1
1191 and v2.
1192
1193 rshift(val, count) Return the value of val, shifted right by count
1194 bits.
1195
1196 xor(v1, v2) Return the bitwise XOR of the values provided by v1
1197 and v2.
1198
1199 Internationalization Functions
1200 Starting with version 3.1 of gawk, the following functions may be used
1201 from within your AWK program for translating strings at run-time. For
1202 full details, see GAWK: Effective AWK Programming.
1203
1204 bindtextdomain(directory [, domain])
1205 Specifies the directory where gawk looks for the .mo files, in
1206 case they will not or cannot be placed in the ``standard'' loca‐
1207 tions (e.g., during testing). It returns the directory where
1208 domain is ``bound.''
1209 The default domain is the value of TEXTDOMAIN. If directory is
1210 the null string (""), then bindtextdomain() returns the current
1211 binding for the given domain.
1212
1213 dcgettext(string [, domain [, category]])
1214 Returns the translation of string in text domain domain for
1215 locale category category. The default value for domain is the
1216 current value of TEXTDOMAIN. The default value for category is
1217 "LC_MESSAGES".
1218 If you supply a value for category, it must be a string equal to
1219 one of the known locale categories described in GAWK: Effective
1220 AWK Programming. You must also supply a text domain. Use
1221 TEXTDOMAIN if you want to use the current domain.
1222
1223 dcngettext(string1 , string2 , number [, domain [, category]])
1224 Returns the plural form used for number of the translation of
1225 string1 and string2 in text domain domain for locale category
1226 category. The default value for domain is the current value of
1227 TEXTDOMAIN. The default value for category is "LC_MESSAGES".
1228 If you supply a value for category, it must be a string equal to
1229 one of the known locale categories described in GAWK: Effective
1230 AWK Programming. You must also supply a text domain. Use
1231 TEXTDOMAIN if you want to use the current domain.
1232
1234 Functions in AWK are defined as follows:
1235
1236 function name(parameter list) { statements }
1237
1238 Functions are executed when they are called from within expressions in
1239 either patterns or actions. Actual parameters supplied in the function
1240 call are used to instantiate the formal parameters declared in the
1241 function. Arrays are passed by reference, other variables are passed
1242 by value.
1243
1244 Since functions were not originally part of the AWK language, the pro‐
1245 vision for local variables is rather clumsy: They are declared as extra
1246 parameters in the parameter list. The convention is to separate local
1247 variables from real parameters by extra spaces in the parameter list.
1248 For example:
1249
1250 function f(p, q, a, b) # a and b are local
1251 {
1252 ...
1253 }
1254
1255 /abc/ { ... ; f(1, 2) ; ... }
1256
1257 The left parenthesis in a function call is required to immediately fol‐
1258 low the function name, without any intervening white space. This is to
1259 avoid a syntactic ambiguity with the concatenation operator. This
1260 restriction does not apply to the built-in functions listed above.
1261
1262 Functions may call each other and may be recursive. Function parame‐
1263 ters used as local variables are initialized to the null string and the
1264 number zero upon function invocation.
1265
1266 Use return expr to return a value from a function. The return value is
1267 undefined if no value is provided, or if the function returns by “fall‐
1268 ing off” the end.
1269
1270 If --lint has been provided, gawk warns about calls to undefined func‐
1271 tions at parse time, instead of at run time. Calling an undefined
1272 function at run time is a fatal error.
1273
1274 The word func may be used in place of function.
1275
1277 Beginning with version 3.1 of gawk, you can dynamically add new built-
1278 in functions to the running gawk interpreter. The full details are
1279 beyond the scope of this manual page; see GAWK: Effective AWK Program‐
1280 ming for the details.
1281
1282 extension(object, function)
1283 Dynamically link the shared object file named by object, and
1284 invoke function in that object, to perform initialization.
1285 These should both be provided as strings. Returns the value
1286 returned by function.
1287
1288 This function is provided and documented in GAWK: Effective AWK Pro‐
1289 gramming, but everything about this feature is likely to change in the
1290 next release. We STRONGLY recommend that you do not use this feature
1291 for anything that you aren't willing to redo.
1292
1294 pgawk accepts two signals. SIGUSR1 causes it to dump a profile and
1295 function call stack to the profile file, which is either awkprof.out,
1296 or whatever file was named with the --profile option. It then contin‐
1297 ues to run. SIGHUP causes it to dump the profile and function call
1298 stack and then exit.
1299
1301 Print and sort the login names of all users:
1302
1303 BEGIN { FS = ":" }
1304 { print $1 | "sort" }
1305
1306 Count lines in a file:
1307
1308 { nlines++ }
1309 END { print nlines }
1310
1311 Precede each line by its number in the file:
1312
1313 { print FNR, $0 }
1314
1315 Concatenate and line number (a variation on a theme):
1316
1317 { print NR, $0 }
1318 Run an external command for particular lines of data:
1319
1320 tail -f access_log |
1321 awk '/myhome.html/ { system("nmap " $1 ">> logdir/myhome.html") }'
1322
1324 String constants are sequences of characters enclosed in double quotes.
1325 In non-English speaking environments, it is possible to mark strings in
1326 the AWK program as requiring translation to the native natural lan‐
1327 guage. Such strings are marked in the AWK program with a leading under‐
1328 score (“_”). For example,
1329
1330 gawk 'BEGIN { print "hello, world" }'
1331
1332 always prints hello, world. But,
1333
1334 gawk 'BEGIN { print _"hello, world" }'
1335
1336 might print bonjour, monde in France.
1337
1338 There are several steps involved in producing and running a localizable
1339 AWK program.
1340
1341 1. Add a BEGIN action to assign a value to the TEXTDOMAIN variable to
1342 set the text domain to a name associated with your program.
1343
1344 BEGIN { TEXTDOMAIN = "myprog" }
1345
1346 This allows gawk to find the .mo file associated with your program.
1347 Without this step, gawk uses the messages text domain, which likely
1348 does not contain translations for your program.
1349
1350 2. Mark all strings that should be translated with leading under‐
1351 scores.
1352
1353 3. If necessary, use the dcgettext() and/or bindtextdomain() functions
1354 in your program, as appropriate.
1355
1356 4. Run gawk --gen-po -f myprog.awk > myprog.po to generate a .po file
1357 for your program.
1358
1359 5. Provide appropriate translations, and build and install a corre‐
1360 sponding .mo file.
1361
1362 The internationalization features are described in full detail in GAWK:
1363 Effective AWK Programming.
1364
1366 A primary goal for gawk is compatibility with the POSIX standard, as
1367 well as with the latest version of UNIX awk. To this end, gawk incor‐
1368 porates the following user visible features which are not described in
1369 the AWK book, but are part of the Bell Laboratories version of awk, and
1370 are in the POSIX standard.
1371
1372 The book indicates that command line variable assignment happens when
1373 awk would otherwise open the argument as a file, which is after the
1374 BEGIN block is executed. However, in earlier implementations, when
1375 such an assignment appeared before any file names, the assignment would
1376 happen before the BEGIN block was run. Applications came to depend on
1377 this “feature.” When awk was changed to match its documentation, the
1378 -v option for assigning variables before program execution was added to
1379 accommodate applications that depended upon the old behavior. (This
1380 feature was agreed upon by both the Bell Laboratories and the GNU
1381 developers.)
1382
1383 The -W option for implementation specific features is from the POSIX
1384 standard.
1385
1386 When processing arguments, gawk uses the special option “--” to signal
1387 the end of arguments. In compatibility mode, it warns about but other‐
1388 wise ignores undefined options. In normal operation, such arguments
1389 are passed on to the AWK program for it to process.
1390
1391 The AWK book does not define the return value of srand(). The POSIX
1392 standard has it return the seed it was using, to allow keeping track of
1393 random number sequences. Therefore srand() in gawk also returns its
1394 current seed.
1395
1396 Other new features are: The use of multiple -f options (from MKS awk);
1397 the ENVIRON array; the \a, and \v escape sequences (done originally in
1398 gawk and fed back into the Bell Laboratories version); the tolower()
1399 and toupper() built-in functions (from the Bell Laboratories version);
1400 and the ANSI C conversion specifications in printf (done first in the
1401 Bell Laboratories version).
1402
1404 There are two features of historical AWK implementations that gawk sup‐
1405 ports. First, it is possible to call the length() built-in function
1406 not only with no argument, but even without parentheses! Thus,
1407
1408 a = length # Holy Algol 60, Batman!
1409
1410 is the same as either of
1411
1412 a = length()
1413 a = length($0)
1414
1415 This feature is marked as “deprecated” in the POSIX standard, and gawk
1416 issues a warning about its use if --lint is specified on the command
1417 line.
1418
1419 The other feature is the use of either the continue or the break state‐
1420 ments outside the body of a while, for, or do loop. Traditional AWK
1421 implementations have treated such usage as equivalent to the next
1422 statement. Gawk supports this usage if --traditional has been speci‐
1423 fied.
1424
1426 Gawk has a number of extensions to POSIX awk. They are described in
1427 this section. All the extensions described here can be disabled by
1428 invoking gawk with the --traditional option.
1429
1430 The following features of gawk are not available in POSIX awk.
1431
1432 · No path search is performed for files named via the -f option.
1433 Therefore the AWKPATH environment variable is not special.
1434
1435 · The \x escape sequence. (Disabled with --posix.)
1436
1437 · The fflush() function. (Disabled with --posix.)
1438
1439 · The ability to continue lines after ? and :. (Disabled with
1440 --posix.)
1441
1442 · Octal and hexadecimal constants in AWK programs.
1443
1444 · The ARGIND, BINMODE, ERRNO, LINT, RT and TEXTDOMAIN variables are not
1445 special.
1446
1447 · The IGNORECASE variable and its side-effects are not available.
1448
1449 · The FIELDWIDTHS variable and fixed-width field splitting.
1450
1451 · The PROCINFO array is not available.
1452
1453 · The use of RS as a regular expression.
1454
1455 · The special file names available for I/O redirection are not recog‐
1456 nized.
1457
1458 · The |& operator for creating co-processes.
1459
1460 · The ability to split out individual characters using the null string
1461 as the value of FS, and as the third argument to split().
1462
1463 · The optional second argument to the close() function.
1464
1465 · The optional third argument to the match() function.
1466
1467 · The ability to use positional specifiers with printf and sprintf().
1468
1469 · The use of delete array to delete the entire contents of an array.
1470
1471 · The use of nextfile to abandon processing of the current input file.
1472
1473 · The and(), asort(), asorti(), bindtextdomain(), compl(), dcgettext(),
1474 dcngettext(), gensub(), lshift(), mktime(), or(), rshift(), strf‐
1475 time(), strtonum(), systime() and xor() functions.
1476
1477 · Localizable strings.
1478
1479 · Adding new built-in functions dynamically with the extension() func‐
1480 tion.
1481
1482 The AWK book does not define the return value of the close() function.
1483 Gawk's close() returns the value from fclose(3), or pclose(3), when
1484 closing an output file or pipe, respectively. It returns the process's
1485 exit status when closing an input pipe. The return value is -1 if the
1486 named file, pipe or co-process was not opened with a redirection.
1487
1488 When gawk is invoked with the --traditional option, if the fs argument
1489 to the -F option is “t”, then FS is set to the tab character. Note
1490 that typing gawk -F\t ... simply causes the shell to quote the “t,”,
1491 and does not pass “\t” to the -F option. Since this is a rather ugly
1492 special case, it is not the default behavior. This behavior also does
1493 not occur if --posix has been specified. To really get a tab character
1494 as the field separator, it is best to use single quotes: gawk -F'\t'
1495 ....
1496
1497 If gawk is configured with the --enable-switch option to the configure
1498 command, then it accepts an additional control-flow statement:
1499 switch (expression) {
1500 case value|regex : statement
1501 ...
1502 [ default: statement ]
1503 }
1504
1506 The AWKPATH environment variable can be used to provide a list of
1507 directories that gawk searches when looking for files named via the -f
1508 and --file options.
1509
1510 If POSIXLY_CORRECT exists in the environment, then gawk behaves exactly
1511 as if --posix had been specified on the command line. If --lint has
1512 been specified, gawk issues a warning message to this effect.
1513
1515 egrep(1), getpid(2), getppid(2), getpgrp(2), getuid(2), geteuid(2),
1516 getgid(2), getegid(2), getgroups(2)
1517
1518 The AWK Programming Language, Alfred V. Aho, Brian W. Kernighan, Peter
1519 J. Weinberger, Addison-Wesley, 1988. ISBN 0-201-07981-X.
1520
1521 GAWK: Effective AWK Programming, Edition 3.0, published by the Free
1522 Software Foundation, 2001.
1523
1525 The -F option is not necessary given the command line variable assign‐
1526 ment feature; it remains only for backwards compatibility.
1527
1528 Syntactically invalid single character programs tend to overflow the
1529 parse stack, generating a rather unhelpful message. Such programs are
1530 surprisingly difficult to diagnose in the completely general case, and
1531 the effort to do so really is not worth it.
1532
1534 The original version of UNIX awk was designed and implemented by Alfred
1535 Aho, Peter Weinberger, and Brian Kernighan of Bell Laboratories. Brian
1536 Kernighan continues to maintain and enhance it.
1537
1538 Paul Rubin and Jay Fenlason, of the Free Software Foundation, wrote
1539 gawk, to be compatible with the original version of awk distributed in
1540 Seventh Edition UNIX. John Woods contributed a number of bug fixes.
1541 David Trueman, with contributions from Arnold Robbins, made gawk com‐
1542 patible with the new version of UNIX awk. Arnold Robbins is the cur‐
1543 rent maintainer.
1544
1545 The initial DOS port was done by Conrad Kwok and Scott Garfinkle.
1546 Scott Deifik is the current DOS maintainer. Pat Rankin did the port to
1547 VMS, and Michal Jaegermann did the port to the Atari ST. The port to
1548 OS/2 was done by Kai Uwe Rommel, with contributions and help from Dar‐
1549 rel Hankerson. Fred Fish supplied support for the Amiga, Stephen
1550 Davies provided the Tandem port, and Martin Brown provided the BeOS
1551 port.
1552
1554 This man page documents gawk, version 3.1.5.
1555
1557 If you find a bug in gawk, please send electronic mail to bug-
1558 gawk@gnu.org. Please include your operating system and its revision,
1559 the version of gawk (from gawk --version), what C compiler you used to
1560 compile it, and a test program and data that are as small as possible
1561 for reproducing the problem.
1562
1563 Before sending a bug report, please do two things. First, verify that
1564 you have the latest version of gawk. Many bugs (usually subtle ones)
1565 are fixed at each release, and if yours is out of date, the problem may
1566 already have been solved. Second, please read this man page and the
1567 reference manual carefully to be sure that what you think is a bug
1568 really is, instead of just a quirk in the language.
1569
1570 Whatever you do, do NOT post a bug report in comp.lang.awk. While the
1571 gawk developers occasionally read this newsgroup, posting bug reports
1572 there is an unreliable way to report bugs. Instead, please use the
1573 electronic mail addresses given above.
1574
1575 If you're using a GNU/Linux system or BSD-based system, you may wish to
1576 submit a bug report to the vendor of your distribution. That's fine,
1577 but please send a copy to the official email address as well, since
1578 there's no guarantee that the bug will be forwarded to the gawk main‐
1579 tainer.
1580
1582 Brian Kernighan of Bell Laboratories provided valuable assistance dur‐
1583 ing testing and debugging. We thank him.
1584
1586 Copyright © 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
1587 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
1588
1589 Permission is granted to make and distribute verbatim copies of this
1590 manual page provided the copyright notice and this permission notice
1591 are preserved on all copies.
1592
1593 Permission is granted to copy and distribute modified versions of this
1594 manual page under the conditions for verbatim copying, provided that
1595 the entire resulting derived work is distributed under the terms of a
1596 permission notice identical to this one.
1597
1598 Permission is granted to copy and distribute translations of this man‐
1599 ual page into another language, under the above conditions for modified
1600 versions, except that this permission notice may be stated in a trans‐
1601 lation approved by the Foundation.
1602
1603
1604
1605Free Software Foundation June 26 2005 GAWK(1)