| 1 |
! Gawk.Hlp |
| 2 |
! Pat Rankin, Jun'90 |
| 3 |
! revised, Jun'91 |
| 4 |
! revised, Jul'92 |
| 5 |
! revised, Jan'95 |
| 6 |
! revised, Apr'97 |
| 7 |
! revised, Jan'03 |
| 8 |
! revised, May'11 |
| 9 |
! Online help for GAWK. |
| 10 |
! |
| 11 |
1 GAWK |
| 12 |
GAWK is GNU awk, the Free Software Foundation's implementation of |
| 13 |
the awk programming language. awk is an interpretive language which |
| 14 |
can handle many data-reformatting jobs with just a few lines of code. |
| 15 |
It has powerful string manipulation and pattern matching capabilities |
| 16 |
built in. This version is compatible with POSIX 1003.2 awk. |
| 17 |
|
| 18 |
The VMS version of GAWK supports both the original UN*X-style command |
| 19 |
interface and a DCL interface. The only setup requirement for GAWK |
| 20 |
is to define it as a 'foreign' command: a DCL symbol with a value |
| 21 |
which begins with '$'. |
| 22 |
$ GAWK :== $disk:[directory]GAWK |
| 23 |
2 GNU_syntax |
| 24 |
GAWK's UN*X-style interface uses the 'dash' convention for specifying |
| 25 |
options and uses spaces to separate multiple arguments. |
| 26 |
|
| 27 |
There are two main alternatives, depending on how the awk program is |
| 28 |
to be passed to GAWK. Both alternatives share most options. |
| 29 |
|
| 30 |
Usage: $ gawk [-Wopts] [-F fs] [-v var=val] -f progfile [--] file ... |
| 31 |
or $ gawk [-Wopts] [-F fs] [-v var=val] [--] "program" file ... |
| 32 |
|
| 33 |
The options are case-sensitive. On VMS, the DCL command interpreter |
| 34 |
converts unquoted text into uppercase before passing it to the running |
| 35 |
program. However, GAWK is written in 'C' and the C Run-Time Library |
| 36 |
(VAXCRTL or DECC$SHR) converts unquoted text into *lowercase*. |
| 37 |
Therefore, the -Fval and -W options must be enclosed in quotes. |
| 38 |
3 options |
| 39 |
-d[file] dump variable values into file (default is awkvars.out |
| 40 |
if not specified) upon program completion |
| 41 |
-e program_text additional program text, as a quoted string, for use |
| 42 |
in combination with -f |
| 43 |
-f file use the specified file as the awk program source; if |
| 44 |
more than one instance of -f is used, each file will |
| 45 |
be read in succession |
| 46 |
-Fstring define a value for the FS variable (field separator) |
| 47 |
-O optimize; of limited use |
| 48 |
-p[file] write program execution profiling into file (default |
| 49 |
is awkprof.out if not specified) |
| 50 |
-v var=val assign a value of 'val' to the variable 'var' |
| 51 |
-W'options' additional gawk-specific options; multiple values may |
| 52 |
be separated by commas, or by spaces if they're quoted, |
| 53 |
or mulitple occurrences of -W may be used. |
| 54 |
-Wcopyright display an abbreviated version of the GNU copyright |
| 55 |
information |
| 56 |
-Whelp list command line options (supersedes -Wusage) |
| 57 |
-Wlint warn about suspect or non-portable awk program code |
| 58 |
-Wlint=fatal treat lint warnings as errors |
| 59 |
-Wlint-old warn about constructs not available in original awk |
| 60 |
-Wposix traditional mode with additional restrictions |
| 61 |
-Wre-interval evaluate '{' and '}' as intervals in regular expressions |
| 62 |
-Wtraditional use awk compatibility mode to disable GAWK extensions |
| 63 |
and get the behavior of UN*X awk. |
| 64 |
-Wversion display program version number |
| 65 |
-- don't check further arguments for leading dash |
| 66 |
3 program_text |
| 67 |
If the '-f file' option is not used on the command line, then the |
| 68 |
first "non-dash" argument is assumed to be a string of text containing |
| 69 |
the awk source program. Here is a complete sample program: |
| 70 |
$ gawk -- "BEGIN {print ""\nHello, World!\n""}" |
| 71 |
This program would print a blank line (based on first "\n"), followed |
| 72 |
by a line reading "Hello, World!", followed by another blank line |
| 73 |
(since awk's 'print' statement includes the trailing 'newline'). |
| 74 |
|
| 75 |
On VMS, to include a quote character inside of a quoted string, two |
| 76 |
successive quotes ("") must be used. |
| 77 |
3 data_files |
| 78 |
After all dash-options are examined, and after the program text if |
| 79 |
there were no occurrences of the -f option, remaining (space separated) |
| 80 |
command line arguments are considered to be data files for the awk |
| 81 |
program to process. If any of these actually contains an equals sign |
| 82 |
(=), then it is interpreted as a variable assignment instead of a data |
| 83 |
file. The syntax is 'variable_name=value'. For example, the command |
| 84 |
$ gawk -f myprog.awk infile.one flag=2 start=0 infile.two |
| 85 |
would read file 'infile.one' for the program in 'myprog.awk', then it |
| 86 |
would set 'flag' to 2 and 'start' to 0, and finally it would read file |
| 87 |
'infile.two' for the program. Note that in a case like this, the two |
| 88 |
assignments actually occur after the first file has been processed, |
| 89 |
not at program startup when the command line is first scanned. |
| 90 |
3 IO_redirection |
| 91 |
The command parsing in the VMS implementation of GAWK does some |
| 92 |
emulation of a UN*X-style shell, where certain characters on the |
| 93 |
command line have special meaning. In particular, the symbols '<', |
| 94 |
'>', '|', '*', and '?' receive special handling before the main part |
| 95 |
of the program has a chance to see them. The symbols '<' and '>' |
| 96 |
perform some file manipulation from the command line: |
| 97 |
|
| 98 |
<ifile open file 'ifile' (readonly) as 'stdin' [SYS$INPUT] |
| 99 |
>nfile create 'nfile' as 'stdout' [SYS$OUTPUT], in stream-lf format |
| 100 |
>>ofile append to 'ofile' for 'stdout'; create it if necessary |
| 101 |
>&efile point 'stderr' [SYS$ERROR] at 'efile', but don't open it yet |
| 102 |
>$vfile create 'vfile' as 'stdout', using RMS attributes appropriate |
| 103 |
for a standard text file (variable length records with |
| 104 |
implied carriage control) |
| 105 |
>+bfile create 'bfile' as 'stdout' using binary mode |
| 106 |
2>&1 route error messages into the regular output stream |
| 107 |
1>&2 send output data to the error destination |
| 108 |
<<sentinel error; reading stdin until 'sentinel' not supported |
| 109 |
<-, >- error; closure of stdin or stdout from cmd line not supported |
| 110 |
>>$vfile incorrect; would be interpreted as file "$vfile" in stream-lf |
| 111 |
format rather than as file "vfile" in RMS 'text' format |
| 112 |
| error; command line pipes not supported |
| 113 |
3 wildcard_expansion |
| 114 |
The command parsing in the VMS implementation of GAWK does some |
| 115 |
emulation of a UN*X-style shell, where certain characters on the |
| 116 |
command line have special meaning. In particular, the symbols '<', |
| 117 |
'>', '*', '%', and '?' receive special handling before the main part |
| 118 |
of the program has a chance to see them. The symbols '*', '%' and '?' |
| 119 |
are used as wildcards in filenames. '*' and '%' have their usual VMS |
| 120 |
meanings of multiple character and single character wildcards, |
| 121 |
respectively, and '?' is also treated as a single character wildcard. |
| 122 |
Wildcard expansion only works for filenames specified in native VMS |
| 123 |
filename syntax (eg, "[-.sibling]*"), not for ones specified pseudo- |
| 124 |
Unix syntax (eg, "../sibling/*"). |
| 125 |
|
| 126 |
When a command line argument that should be a filename contains any |
| 127 |
of the wildcard characters, a directory lookup is attempted for files |
| 128 |
which match the specified pattern. If one or more matching files are |
| 129 |
found, those filenames are put into the command line in place of the |
| 130 |
original pattern. If no matching files are found, the original |
| 131 |
pattern is left in place. |
| 132 |
2 DCL_syntax |
| 133 |
GAWK's DCL-style interface is more or less a standard DCL command, with |
| 134 |
one required parameter. Multiple values--when present--are separated |
| 135 |
by commas. |
| 136 |
|
| 137 |
There are two main alternatives, depending on how the awk program is |
| 138 |
to be passed to GAWK. Both alternatives share most options. |
| 139 |
|
| 140 |
Usage: GAWK /COMMANDS="awk program text" data_file[,data_file,...] |
| 141 |
or GAWK /INPUT=awk_file data_file[,"Var=value",data_file,...] |
| 142 |
( or GAWK /INPUT=(awk_file1,awk_file2,...) data_file[,...] ) |
| 143 |
3 Parameter |
| 144 |
data_file[,datafile,...] (data_file data_file ...) |
| 145 |
data_file[,"Var=value",...,data_file,...] (data_file Var=value &c) |
| 146 |
|
| 147 |
Data file(s) for the awk program to process. If any of these |
| 148 |
actually contains an equals sign (=), then it is interpreted as |
| 149 |
a variable assignment instead of a data file. The syntax is |
| 150 |
"variable_name=value". Quotes are required for non-file parameters. |
| 151 |
|
| 152 |
For example, the command |
| 153 |
$ gawk/input=myprog.awk infile.one,"flag=2","start=0",infile.two |
| 154 |
would read file 'infile.one' for the program in 'myprog.awk', then it |
| 155 |
would set 'flag' to 2 and 'start' to 0, and finally it would read file |
| 156 |
'infile.two' for the program. Note that in a case like this, the two |
| 157 |
assignments actually occur after the first file has been processed, |
| 158 |
not at program startup when the command line is first scanned. |
| 159 |
|
| 160 |
Wildcard file lookups are attempted on data file specifications. See |
| 161 |
subtopic 'GAWK GNU_syntax wildcard_expansion' for details. |
| 162 |
|
| 163 |
At least one data_file parameter value is required. An exception is |
| 164 |
made if /usage, /version, or /copyright is specified *and* if GAWK is |
| 165 |
defined as a 'foreign' command rather than a 'native' DCL command. |
| 166 |
3 Qualifiers |
| 167 |
/COMMANDS |
| 168 |
/COMMANDS="awk program text" (-- "awk program text") |
| 169 |
|
| 170 |
For short programs, it is possible to include the complete program |
| 171 |
on the command line. The quotes are required. Here is a complete |
| 172 |
sample program: |
| 173 |
$ gawk/commands="BEGIN {print ""\nHello, World!\n""}" NL: |
| 174 |
This program would print a blank line (based on first "\n"), followed |
| 175 |
by a line reading "Hello, World!", followed by another blank line |
| 176 |
(since awk's 'print' statement includes the trailing 'newline'). |
| 177 |
|
| 178 |
To include a quote character inside of a quoted string, two |
| 179 |
successive quotes ("") must be used. |
| 180 |
|
| 181 |
Either /COMMANDS or /INPUT (but not both) must be supplied. |
| 182 |
/INPUT |
| 183 |
/INPUT=(awk_file1,awk_file2) (-f awk_file1 -f awk_file2) |
| 184 |
|
| 185 |
Used to specify one or more files containing the source code of |
| 186 |
the awk program. If more than one file is used, separate them |
| 187 |
with commas and enclose the list in parentheses. |
| 188 |
|
| 189 |
Multiple source files are processed in order as if they had been |
| 190 |
concatenated together. |
| 191 |
|
| 192 |
Either /INPUT or /COMMANDS (but not both) must be supplied unless |
| 193 |
one of /VERSION, /COPYRIGHT, and /USAGE is used. |
| 194 |
/EXTRA_COMMANDS |
| 195 |
/EXTRA_COMMANDS="awk program text" (-E "awk program text") |
| 196 |
|
| 197 |
Add more program text, for use in combination with /INPUT. Unlike |
| 198 |
Un*x or GNU syntax processing of VMS GAWK where multiple instances of |
| 199 |
-f file and -e text can be interspersed, DCL command processing of |
| 200 |
VMS GAWK allows only one /EXTRA_COMMANDS="text" qualifier and handles |
| 201 |
it before /INPUT=(file,...). |
| 202 |
/FIELD_SEPARATOR |
| 203 |
/FIELD_SEPARATOR="FS_value" (-F"FS_value") |
| 204 |
|
| 205 |
Assign a value to the built in variable FS (field separator). |
| 206 |
/VARIABLES |
| 207 |
/VARIABLES=("Var1=val1","Var2=val2",...) (-v Var1=val1 -v Var2=val2) |
| 208 |
|
| 209 |
Assign value(s) to the specified variable(s). |
| 210 |
/OPTIMIZE |
| 211 |
/[NO]OPTIMIZE (-"O" option) |
| 212 |
|
| 213 |
Perform some relatively minor optimizations on the source code as it |
| 214 |
is read in; primarily constant folding. Default is /NOOPTIMIZE but |
| 215 |
presently optimization is always enabled and explicitly negating it |
| 216 |
has no effect. This may change when/if more elaborate optimizations |
| 217 |
are implemented. |
| 218 |
/PROFILE |
| 219 |
/PROFILE[=file] (-p[file]) |
| 220 |
|
| 221 |
Write profiling feedback into the specified file. If no file name is |
| 222 |
specified, awkprof.out in the current directory is used. |
| 223 |
/DUMP_VARIABLES |
| 224 |
/DUMP_VARIABLES[=file] (-d[file]) |
| 225 |
|
| 226 |
Print a sorted list of global variables, their types, and final values |
| 227 |
to the specified file. If no file name is specified, awkvars.out in |
| 228 |
the current directory is used. |
| 229 |
!-/REG_EXPR |
| 230 |
!- /REG_EXPR={AWK | EGREP | POSIX} (-a vs -e options [obsolete]) |
| 231 |
!- |
| 232 |
!- This qualifier is obsolete and has no effect. |
| 233 |
/POSIX |
| 234 |
/[NO]POSIX (-"Wposix" option) |
| 235 |
|
| 236 |
Use POSIX compatibility mode (/posix) and suppress GAWK extensions. |
| 237 |
The default is /NOPOSIX. Slightly more restrictive than /strict. |
| 238 |
/TRADITIONAL |
| 239 |
/[NO]TRADITIONAL (-"Wtraditional" option) |
| 240 |
|
| 241 |
Use strict awk compatibility mode (/traditional) and suppress GAWK |
| 242 |
extensions. Supersedes /STRICT. The default is /NOTRADITIONAL. |
| 243 |
/STRICT |
| 244 |
/[NO]STRICT (-"Wtraditional" option) |
| 245 |
|
| 246 |
Use strict awk compatibility mode (/strict) and suppress GAWK |
| 247 |
extensions. Superseded by /TRADITIONAL. The default is /NOSTRICT. |
| 248 |
/RE_INTERVAL |
| 249 |
/RE_INTERVAL (-"Wre-interval" option) |
| 250 |
|
| 251 |
Allow interval expressions in regexps (regular expressions). GAWK |
| 252 |
always accepts intervals in normal mode; /RE_INTERVAL can be used to |
| 253 |
enable them in strict (/TRADITIONAL) compatability mode. |
| 254 |
/SANDBOX |
| 255 |
/SANDBOX (-"Wsandbox" option) |
| 256 |
|
| 257 |
Disables the system() function, input redirections with getline, |
| 258 |
output redirections with print and printf, and dynamic extensions. |
| 259 |
/NON_DECIMAL_DATA |
| 260 |
/NON_DECIMAL_DATA (-"Wnon-decimal-data" option) |
| 261 |
|
| 262 |
Enable automatic interpretation of octal and hexadecimal values in |
| 263 |
input data. Use with care. |
| 264 |
/LINT |
| 265 |
/[NO]LINT[=(WARN,OLD,FATAL)] (-"Wlint" and -"Wlint-old" options) |
| 266 |
|
| 267 |
Check the awk program cafefully for potential problems that might |
| 268 |
be encountered if it were to be used with other awk implementations, |
| 269 |
and print warnings for anything found. The default in /NOLINT. |
| 270 |
|
| 271 |
/LINT without a value is equivalent to /LINE=WARN. /LINT=OLD warns |
| 272 |
about constructs which wouldn't work with /TRADITIONAL. /LINT=FATAL |
| 273 |
turns lint warnings into errors which cause GAWK to terminate. |
| 274 |
!- /LINT=INVALID is accepted but isn't documented here. |
| 275 |
!three undocumented qualifiers; judged not useful for VMS |
| 276 |
!- /CHARACTERS_AS_BYTES |
| 277 |
!- /CHARACTERS_AS_BYTES (-"Wcharacters-as-bytes" option) |
| 278 |
!- /USE_LC_NUMERIC |
| 279 |
!- /USE_LC_NUMERIC (-"Wuse-lc-numeric" option) |
| 280 |
!- /GEN_POT |
| 281 |
!- /GEN_POT (-"Wgen-pot" option) |
| 282 |
/VERSION |
| 283 |
/VERSION (-"Wversion" option) |
| 284 |
|
| 285 |
Print GAWK's version number and then terminate. Includes copyright |
| 286 |
notice. |
| 287 |
/COPYRIGHT |
| 288 |
/COPYRIGHT (-"Wcopyright" option) |
| 289 |
|
| 290 |
Print a brief version of GAWK's copyright notice and then terminate. |
| 291 |
/USAGE |
| 292 |
/USAGE (comparable to -"Whelp" option) |
| 293 |
|
| 294 |
Print a compact summary of the command line options. |
| 295 |
|
| 296 |
After the 'usage' message is printed, GAWK terminates regardless |
| 297 |
of any other command line options. |
| 298 |
/OUTPUT |
| 299 |
/OUTPUT=out_file (>$out_file) |
| 300 |
|
| 301 |
Write program output into 'out_file'. The default is SYS$OUTPUT. |
| 302 |
2 awk_language |
| 303 |
An awk program consists of one or more pattern-action pairs, sometimes |
| 304 |
referred to as "rules". For each record of an input (data) file, the |
| 305 |
rules are checked sequentially. Any pattern which matches the input |
| 306 |
record triggers that rule's action. Actions are instructions which |
| 307 |
resemble statements in the 'C' programming language. Patterns come |
| 308 |
in several varieties, including field comparisons, regular expression |
| 309 |
matching, and special cases defined by reserved keywords. |
| 310 |
|
| 311 |
All awk keywords and variables are case-sensitive. Text matching is |
| 312 |
also sensitive to character case unless the builtin variable IGNORECASE |
| 313 |
is set to a non-zero value. |
| 314 |
3 rules |
| 315 |
The syntax for a pattern-action 'rule' is simply |
| 316 |
PATTERN { ACTION } |
| 317 |
where the braces ({}) are required punctuation for the action. |
| 318 |
Semicolons (;) or 'newlines' (ie, having the text on a separate line) |
| 319 |
delimit multiple rules and also multiple actions within a given rule. |
| 320 |
Either the pattern or the action may be omitted; an empty pattern |
| 321 |
matches every record of the input file; a missing action (not an empty |
| 322 |
action inside of braces), is an implicit request to print the current |
| 323 |
record; an empty action (ie, {}) is legal but not very useful. |
| 324 |
3 patterns |
| 325 |
There are several types of patterns available for awk rules. |
| 326 |
|
| 327 |
expression an 'expression' is something to be evaluated (perhaps |
| 328 |
a comparison or function call) which will |
| 329 |
be considered true if non-zero (for numeric |
| 330 |
results) or if non-null (for strings) |
| 331 |
/regular_expression/ slashes (/) delimit a regular expression |
| 332 |
which is used as a pattern |
| 333 |
pattern1, pattern2 a pair of patterns separated by a comma (,), |
| 334 |
which causes a range of records to trigger |
| 335 |
the associated action; the records which |
| 336 |
match the patterns are included in the range |
| 337 |
<null> an omitted pattern (in this text, the string '<null>' |
| 338 |
is displayed, but in an awk program, it |
| 339 |
would really be blank) matches every record |
| 340 |
BEGIN keyword for specifying a rule to be executed prior to |
| 341 |
reading the 1st record of the 1st input file |
| 342 |
END keyword for specifying a rule to be executed after |
| 343 |
handling the last input record of last file |
| 344 |
BEGINFILE gawk-specific keyword for specifying a rule to be |
| 345 |
executed when a file from the command line |
| 346 |
has just been opened, before attempting to |
| 347 |
read its first record |
| 348 |
ENDFILE gawk-specific keyword for specifying a rule to be |
| 349 |
executed after the last record of a file |
| 350 |
from the command has been processed by any |
| 351 |
other patterns and actions |
| 352 |
4 BEGINFILE |
| 353 |
Normally a file open attempt which fails will generate an error |
| 354 |
and cause GAWK to terminate. However, if your program has a |
| 355 |
BEGINFILE rule, failed open attempts will set ERRNO to a non-null |
| 356 |
value and execute the BEGINFILE rule's actions. You can check |
| 357 |
for that condition and use the 'nextfile' statement to skip files |
| 358 |
which couldn't be opened. Note that when executing the BEGINFILE |
| 359 |
rule for a failed open attempt, allowing the actions to finish |
| 360 |
without using 'nextfile' will result in an error just like for a |
| 361 |
program which has no BEGINFILE rule. |
| 362 |
4 examples |
| 363 |
Some example patterns (mostly with the corresponding actions omitted) |
| 364 |
|
| 365 |
NF > 0 # comparison expression: matches non-null records |
| 366 |
$0 # implied comparison: also matches non-null records |
| 367 |
$2 > 1000 && sum <= 999999 # slightly more elaborate expression |
| 368 |
/x/ # regular expression matching any record with an 'x' in it |
| 369 |
/^ / # reg-expr matching records beginning with a space |
| 370 |
$1 == "start", $NF == "stop" # range pattern for input in which |
| 371 |
some data lines begin with 'start' and/or end with |
| 372 |
'stop' in order to collect groups of records |
| 373 |
{ sum += $1 } # null pattern: it's action (add field #1 to |
| 374 |
variable 'sum') would be executed for every record |
| 375 |
BEGIN { sum = 0 } # keyword 'BEGIN': perform this action before |
| 376 |
reading the input file (note: initialization to 0 is |
| 377 |
unnecessary in awk) |
| 378 |
END { print "total =", sum } # keyword 'END': perform this |
| 379 |
action after the last input record has been processed |
| 380 |
# two different ways to handle the start of an input file: |
| 381 |
FNR == 1 { print FILENAME } # print name after reading first record |
| 382 |
BEGINFILE { print FILENAME } # print name before reading first record |
| 383 |
3 actions |
| 384 |
An 'action' is something to do when a given record has matched the |
| 385 |
corresponding pattern in a rule. In general, actions resemble 'C' |
| 386 |
statements and expressions. The action in a rule must be enclosed |
| 387 |
in braces ({}). |
| 388 |
|
| 389 |
Each action can contain more than one statement or expression to be |
| 390 |
executed, provided that they're separated by semicolons (;) and/or |
| 391 |
on separate lines. |
| 392 |
|
| 393 |
An omitted action is equivalent to |
| 394 |
{ print $0 } |
| 395 |
which prints the current record. |
| 396 |
3 operators |
| 397 |
Relational operators |
| 398 |
== compare for equality |
| 399 |
!= compare for inequality |
| 400 |
<, <=, >, >= numerical or lexical comparison (less than, less or |
| 401 |
equal, greater than, greater or equal, respectively) |
| 402 |
~ match against a regular expression |
| 403 |
!~ match against a regular expression, but accept failed matches |
| 404 |
instead of successful ones |
| 405 |
Arithmetic operators |
| 406 |
+ addition |
| 407 |
- subtraction |
| 408 |
* multiplication |
| 409 |
/ division |
| 410 |
% remainder |
| 411 |
^, ** exponentiation ('**' is a synonym for '^', unless POSIX |
| 412 |
compatibility is specified, in which case it's invalid) |
| 413 |
Boolean operators (aka Logical operators) |
| 414 |
a value is considered false if it's 0 or a null string, |
| 415 |
it is true otherwise; the result of a boolean operation |
| 416 |
(and also of a comparison operation) will be 0 when false |
| 417 |
or 1 when true |
| 418 |
|| or [expression (a || b) is true if either a is true or b |
| 419 |
is true or both a and b are true; it is false otherwise; |
| 420 |
b is not evaluated unless a is false (ie, short-circuit)] |
| 421 |
&& and [expression (a && b) is true if both a and b are true; |
| 422 |
it is false otherwise; b is only evaluated if a is true] |
| 423 |
! not [expression (!a) is true if a is false, false otherwise] |
| 424 |
in array membership; the keyword 'in' tests whether the value |
| 425 |
on the left represents a current subscript in the array |
| 426 |
named on the right |
| 427 |
Conditional operator |
| 428 |
? : the conditional operator takes three operands; the first is |
| 429 |
an expression to evaluate, the second is the expression to |
| 430 |
use if the first was true, the third is the expression to |
| 431 |
use if it was false [simple example (a < b ? b : a) gives |
| 432 |
the maximum of a and b] |
| 433 |
Assignment operators |
| 434 |
= store the value on the right into the variable or array slot |
| 435 |
on the left [expression (a = b) stores the value of b in a] |
| 436 |
+=, -=, *=, /=, %=, ^=, **= perform the indicated arithmetic |
| 437 |
operation using the current value of the variable or array |
| 438 |
element of the left side and the expression on the right |
| 439 |
side, then store the result in the left side |
| 440 |
++ increment by 1 [expression (++a) gets the current value of |
| 441 |
a and adds 1 to it, stores that back in a, and returns the |
| 442 |
new value; expression (a++) gets the current value of a, |
| 443 |
adds 1 to it, stores that back in a, but returns the |
| 444 |
original value of a] |
| 445 |
-- decrement by 1 (analogous to increment) |
| 446 |
String operators |
| 447 |
there is no explicit operator for string concatenation; |
| 448 |
two values and/or variables side-by-side are implicitly |
| 449 |
concatenated into a string (numeric values are first |
| 450 |
converted into their string equivalents) |
| 451 |
Conversion between numeric and string values |
| 452 |
there is no explicit operator for conversion; adding 0 |
| 453 |
to a string with force it to be converted to a number |
| 454 |
(the numeric value will be 0 if the string does not |
| 455 |
represent an integer or floating point number); the |
| 456 |
reverse, converting a number into a string, is done by |
| 457 |
concatenating a null string ("") to it [the expression |
| 458 |
(5.75 "") evaluates to "5.75"] |
| 459 |
Field 'operator' |
| 460 |
$ prefixing a number or variable with a dollar sign ($) |
| 461 |
causes the appropriate record field to be returned [($2) |
| 462 |
gives the second field of the record, ($NF) gives the |
| 463 |
last field (since the builtin variable NF is set to the |
| 464 |
number of fields in the current record)] |
| 465 |
Array subscript operator |
| 466 |
, multi-dimensional arrays are simulated by using comma (,) |
| 467 |
separated array indices; the actual index is generated |
| 468 |
by replacing commas with the value of builtin SUBSEP, |
| 469 |
then concatenating the expression into a string index |
| 470 |
[comma is also used to separate arguments in function |
| 471 |
calls and user-defined function definitions] |
| 472 |
[comma is *also* used to indicate a range pattern in an |
| 473 |
awk rule] |
| 474 |
Escape 'operator' |
| 475 |
\ In quoted character strings, the backslash (\) character |
| 476 |
causes the following character to be interpreted in a |
| 477 |
special manner [string "one\ntwo" has an embedded newline |
| 478 |
character (linefeed on VMS, but treated as if it were both |
| 479 |
carriage-return and linefeed); string "\033[" has an ASCII |
| 480 |
'escape' character (which has octal value 033) followed by |
| 481 |
a 'right-bracket' character] |
| 482 |
Backslash is also used in regular expressions |
| 483 |
Redirection operators |
| 484 |
< Read-from -- valid with 'getline' |
| 485 |
> Write-to (create new file) -- valid with 'print' and 'printf' |
| 486 |
>> Append-to (create file if it doesn't already exist) |
| 487 |
| Pipe-from/to -- valid with 'getline', 'print', and 'printf' |
| 488 |
4 precedence |
| 489 |
Operator precedence, listed from highest to lowest. Assignment, |
| 490 |
conditional, and exponentiation operators group from right to left; |
| 491 |
all others group from left to right. Parentheses may be used to |
| 492 |
override the normal order. |
| 493 |
|
| 494 |
field ($) |
| 495 |
increment (++), decrement (--) |
| 496 |
exponentiation (^, **) |
| 497 |
unary plus (+), unary minus (-), boolean not (!) |
| 498 |
multiplication (*), division (/), remainder (%) |
| 499 |
addition (+), subtraction (-) |
| 500 |
concatenation (no special symbol; implied by context) |
| 501 |
relational (==, !=, <, >=, etc), and redirection (<, >, >>, |) |
| 502 |
Relational and redirection operators have the same precedence |
| 503 |
and use similar symbols; context distinguishes between them |
| 504 |
matching (~, !~) |
| 505 |
array membership ('in') |
| 506 |
boolean and (&&) |
| 507 |
boolean or (||) |
| 508 |
conditional (? :) |
| 509 |
assignment (=, +=, etc) |
| 510 |
4 escaped_characters |
| 511 |
Inside of a quoted string or constant regular expression, the |
| 512 |
backslash (\) character gives special meaning to the character(s) |
| 513 |
after it. Special character letters are case sensitive. |
| 514 |
\\ results in one backslash in the string |
| 515 |
\a is an 'alert' (<ctrl/G>. the ASCII <bell> character) |
| 516 |
\b is a backspace (BS, <ctrl/H>) |
| 517 |
\f is a form feed (FF, <ctrl/L>) |
| 518 |
\n 'newline' (<ctrl/J> [line feed treated as CR+LF] |
| 519 |
\r carriage return (CR, <ctrl/M> [re-positions at the |
| 520 |
beginning of the current line] |
| 521 |
\t tab (HT, <ctrl/I>) |
| 522 |
\v vertical tab (VT, <ctrl/K>) |
| 523 |
\### is an arbitrary character, where '###' represents 1 to 3 |
| 524 |
octal (ie, 0 thru 7) digits |
| 525 |
\x## is an alternate arbitrary character, where '##' represents |
| 526 |
1 or more hexadecimal (ie, 0 thru 9 and/or A through E |
| 527 |
and/or a through e) digits; if more than two digits |
| 528 |
follow, the result is undefined; not recognized if POSIX |
| 529 |
compatibility mode is specified. |
| 530 |
|
| 531 |
When a regular expression is represented in string form ("regex" |
| 532 |
as opposed to /regex/), backslashes need to be paired. The first |
| 533 |
one quotes the second during string processing, and the second one |
| 534 |
remains to be used to quote whatever follows in regular expression |
| 535 |
processing. For example, to match variable `xxx' against a period |
| 536 |
character, use (xxx ~ "\\.") or (xxx ~ /\./); if you tried to use |
| 537 |
(xxx ~ "\."), after string processing it would operate as (xxx ~ /./) |
| 538 |
and end up matching any single character rather than just a period. |
| 539 |
3 statements |
| 540 |
A statement refers to a unit of instruction found in the action |
| 541 |
part of an awk rule, and also found in the definition of a function. |
| 542 |
The distinction between action, statement, and expression usually |
| 543 |
won't matter to an awk programmer. |
| 544 |
|
| 545 |
Compound statements consist of multiple statements separated by |
| 546 |
semicolons or newlines and enclosed within braces ({}). They are |
| 547 |
sometimes referred to as 'blocks'. |
| 548 |
4 expressions |
| 549 |
An expression such as 'a = 10' or 'n += i++' is a valid statement. |
| 550 |
|
| 551 |
Function invocations such as 'reformat_field($3)' are also valid |
| 552 |
statements. |
| 553 |
4 if-then-else |
| 554 |
A conditional statement in awk uses the same syntax as for the 'C' |
| 555 |
programming language: the 'if' keyword, followed by an expression |
| 556 |
in parentheses, followed by a statement--or block of statements |
| 557 |
enclosed within braces ({})--which will be executed if the expression |
| 558 |
is true but skipped if it's false. This can optionally be followed |
| 559 |
by the 'else' keyword and another statement--or block of statements-- |
| 560 |
which will be executed if (and only if) the expression was false. |
| 561 |
5 examples |
| 562 |
Simple example showing a statement used to control how many numbers |
| 563 |
are printed on a given line. |
| 564 |
if ( ++i <= 10 ) #check whether this would be the 11th |
| 565 |
printf(" %5d", k) #print on current line if not |
| 566 |
else { |
| 567 |
printf("\n %5d", k) #print on next line if so |
| 568 |
i = 1 #and reset the counter |
| 569 |
} |
| 570 |
Another example ('next' is described under 'action-controls') |
| 571 |
if ($1 > $2) { print "rejected"; next } else diff = $2 - $1 |
| 572 |
4 switch-case |
| 573 |
A gawk extension provides an alternative for conditional execution |
| 574 |
to the if-then-else construct. The switch statement takes a value |
| 575 |
to use to decide which of one or more case clauses to execute, |
| 576 |
similar to the same construct in C and C++. The main difference |
| 577 |
is that in those languages, the case values must be constant |
| 578 |
integers, whereas in awk they can by numbers, strings, or regular |
| 579 |
expressions. Like in C/C++, an optional 'default' clause can be |
| 580 |
specified to serve as a catch-all for values which don't match |
| 581 |
any of the cases. |
| 582 |
|
| 583 |
The first case which matches the switch value is the one which |
| 584 |
will be executed. If it doesn't use one of 'break', 'continue', |
| 585 |
'next', 'nextfile', 'return', or 'exit', then execution will |
| 586 |
continue into the body of the next case. (Note that 'continue' |
| 587 |
doesn't operate as an explicit request to do such; rather, it |
| 588 |
causes execution of an enclosing for, while, or do-while |
| 589 |
statement to jump to the end of its loop.) |
| 590 |
5 example |
| 591 |
In this example, the value of variable 'x' is examined. It |
| 592 |
contains a mistake that someone coming from a background of |
| 593 |
programming in Pascal might accidentally make. |
| 594 |
|
| 595 |
switch (x) { |
| 596 |
case 1: print "x is 1"; break; |
| 597 |
case 2: print "x is 2" |
| 598 |
case "two": print "x is \"two\""; break; |
| 599 |
default: print "x is neither 1 nor 2"; break |
| 600 |
} |
| 601 |
|
| 602 |
Note that if the value is '2', after printing "x is 2" it will |
| 603 |
continue into the next case and also print "x is \"two\"", which |
| 604 |
was probably not intended. The 'break' statement is needed to |
| 605 |
jump out of the switch statement instead of falling through |
| 606 |
into the subsequent clause. For the very last one, 'default' |
| 607 |
in this example, 'break' is optional; reaching the closing |
| 608 |
bracket of a switch statement also breaks out of the statement. |
| 609 |
4 loops |
| 610 |
Three types of loop statements are available in awk. Each uses |
| 611 |
the same syntax as 'C'. The simplest of the three is the 'while' |
| 612 |
statement. It consists of the 'while' keyword, followed by an |
| 613 |
expression enclosed within parentheses, followed by a statement--or |
| 614 |
block of statements in braces ({})--which will be executed if the |
| 615 |
expression evaluates to true. The expression is evaluated before |
| 616 |
attempting to execute the statement; if it's true, the statement is |
| 617 |
executed (the entire block of statements if there is a block) and |
| 618 |
then the expression is re-evaluated. |
| 619 |
|
| 620 |
The second type of loop is the do-while loop. It consists of the |
| 621 |
'do' keyword, followed by a statement (usually a block of statements |
| 622 |
enclosed within braces), followed by the 'while' keyword, followed |
| 623 |
by a test expression enclosed within parentheses. The statement--or |
| 624 |
block--is always executed at least once. Then the test expression |
| 625 |
is evaluated, and the statement(s) re-executed if the result was |
| 626 |
true (followed by re-evaluation of the test, and so on). |
| 627 |
|
| 628 |
The most complex of the three loops is the 'for' statement, and it |
| 629 |
has a second variant that is not found in 'C'. The ordinary for-loop |
| 630 |
consists of the 'for' keyword, followed by three semicolon-separated |
| 631 |
expressions enclosed within parentheses, followed by a statement or |
| 632 |
brace-enclosed block of statements. The first of the three |
| 633 |
expressions is an initialization clause; it is done before starting |
| 634 |
the loop. The second expression is used as a test, just like the |
| 635 |
expression in a while-loop. It is checked before attempting to |
| 636 |
execute the statement block, and then re-checked after each execution |
| 637 |
(if any) of the block. The third expression is an 'increment' clause; |
| 638 |
it is evaluated after an execution of the statement block and before |
| 639 |
re-evaluation of the test (2nd) expression. Normally, the increment |
| 640 |
clause will change a variable used in the test clause, in such a |
| 641 |
fashion that the test clause will eventually evaluate to false and |
| 642 |
cause the loop to finish. |
| 643 |
|
| 644 |
Note to 'C' programmers: the comma (,) operator commonly used in |
| 645 |
'C' for-loop expressions is not valid in awk. |
| 646 |
|
| 647 |
The awk-specific variant of the for-loop is used for processing |
| 648 |
arrays. Its syntax is 'for' keyword, followed by variable_name 'in' |
| 649 |
array_name (where 'var in array' is enclosed in parentheses), |
| 650 |
followed by a statement (or block). Each valid subscript value for |
| 651 |
the array in question is successively placed--in no particular |
| 652 |
order--into the specified 'index' variable. Order can optionally |
| 653 |
be controlled by assigning a sort mode to PROCINFO["sorted_in"]. |
| 654 |
5 while_example |
| 655 |
# strip fields from the input record until there's nothing left |
| 656 |
while (NF > 0) { |
| 657 |
$1 = "" #this will affect the value of $0 |
| 658 |
$0 = $0 #this causes $0 and NF to be re-evaluated |
| 659 |
print |
| 660 |
} |
| 661 |
5 do_while_example |
| 662 |
# This is a variation of the while_example; it gives a slightly |
| 663 |
# different display due to the order of operation. |
| 664 |
# echo input record until all fields have been stripped |
| 665 |
do { |
| 666 |
print #output $0 |
| 667 |
$1 = "" #this will affect the value of $0 |
| 668 |
$0 = $0 #this causes $0 and NF to be re-evaluated |
| 669 |
} while (NF > 0) |
| 670 |
5 for_example |
| 671 |
# echo command line arguments (won't include option switches) |
| 672 |
for ( i = 0; i < ARGC; i++ ) print ARGV[i] |
| 673 |
|
| 674 |
# display contents of builtin environment array |
| 675 |
for (itm in ENVIRON) |
| 676 |
print itm, ENVIRON[itm] |
| 677 |
5 for_index_in_array_sorting |
| 678 |
Normally indices in an array are processed in an arbitrary |
| 679 |
order when using the 'for (index in array)' statement, |
| 680 |
but a gawk-extension allows you to control that order. |
| 681 |
Assign a value to the "sorted_in" element of the PROCINFO[] |
| 682 |
array to accomplish this. The value may be a comparison |
| 683 |
function which accepts four arguments (index and value of one |
| 684 |
element, then index and value of another), or a special value |
| 685 |
which specifies one of several built-in comparison functions. |
| 686 |
These functions are used to compare pairs of array elements |
| 687 |
and their result controls which of each pair comes before the |
| 688 |
other. |
| 689 |
6 comparison_function |
| 690 |
A function assigned to PROCINFO["sorted_in"] should be |
| 691 |
prepared to accept four arguments and to return a numeric |
| 692 |
value, negative if the element specified by the first two |
| 693 |
arguments (its index and its value, respectively) is less |
| 694 |
than the element specified the second pair of arguments, |
| 695 |
zero if they compare equal, and positive of the first |
| 696 |
element is greater than the second. Here's an example: |
| 697 |
|
| 698 |
function my_compare(idx1, val1, idx2, val2) |
| 699 |
{ |
| 700 |
if (val1 < val2) return -1 |
| 701 |
if (val2 > val2) return 1 |
| 702 |
# the two values are equal |
| 703 |
return (idx1 < idx2) ? -1 : (idx1 > idx2) |
| 704 |
} |
| 705 |
|
| 706 |
This compares the two values and returns either negative |
| 707 |
or positive if they're different. If they're the same, |
| 708 |
it compares the two indices as a tie-breaker instead of |
| 709 |
simply returning zero. |
| 710 |
|
| 711 |
You can force values to be numeric or to be string, as |
| 712 |
needed, and use more elaborate ordering criteria. Just |
| 713 |
be sure that the results are consistent; returning a |
| 714 |
positive value when idx1,val1 is compared to idx2,val2 |
| 715 |
and then also returning a positive value if idx2,val2 |
| 716 |
gets compared to idx1,idx2 will likely confuse the sort |
| 717 |
routine and produce strange results. |
| 718 |
|
| 719 |
If you plan to sort arrays which contain sub-arrays (array |
| 720 |
elements which contain their own arrays) and you're sorting |
| 721 |
by value rather than by index, your compare routine should |
| 722 |
use the isarray() function to check for them (test second |
| 723 |
and fourth arguments to see whether they're arrays) and |
| 724 |
handle them appropriately. The basic comparison operators |
| 725 |
like '<' will produce an error if used on arrays. |
| 726 |
6 built-in_comparisons |
| 727 |
Here is a list of built-in compare routines that can be |
| 728 |
assigned to PROCINFO["sorted_in"]. They are strings |
| 729 |
and start with '@' so that these names can't be confused |
| 730 |
with actual functions. |
| 731 |
|
| 732 |
"@ind_str_asc" order by indices compared as strings |
| 733 |
(all array indices are strings internally, |
| 734 |
even when they were assigned as numbers) |
| 735 |
"@ind_num_asc" order by indices compared as numbers |
| 736 |
(non-numeric ones end up with value 0) |
| 737 |
"@val_type_asc" order by values using assigned type |
| 738 |
(if a mixture of strings and numbers is |
| 739 |
present, numbers come first, then strings) |
| 740 |
"@val_str_asc" order by values compared as strings |
| 741 |
"@val_num_asc" order by values compared as numbers |
| 742 |
"@ind_str_desc" \ |
| 743 |
"@ind_num_desc" \ |
| 744 |
"@val_type_desc" descending versions of the above |
| 745 |
"@val_str_desc" / |
| 746 |
"@val_num_desc" / |
| 747 |
"@unsorted" explicitly specify arbitrary order |
| 748 |
(same as deleting the "sorted_in" element |
| 749 |
from the PROCINFO[] array, or never having |
| 750 |
assigned it a value in the first place) |
| 751 |
|
| 752 |
All the ascending sorts put sub-arrays--if any--last, and |
| 753 |
descending ones place them first. When multiple sub-arrays |
| 754 |
are present, they tie with each other without regard to |
| 755 |
their contents; such ties are then disambiguated by |
| 756 |
comparing their indices. |
| 757 |
6 processing_order |
| 758 |
Sorting of the array takes place as the 'for (index in array)' |
| 759 |
statement is about to start executing. Changing the value of |
| 760 |
PROCINFO["sorted_in"] during the course of the loop will not |
| 761 |
affect traversal order, and could be used to control ordering |
| 762 |
of sub-arrays using different criteria. |
| 763 |
|
| 764 |
After the loop finishes, any ordering imposed on the indices |
| 765 |
is forgotten. A subsequent 'for (index in array)' traversal |
| 766 |
of the same array will yield whatever order is specified by |
| 767 |
PROCINFO["sorted_in"] at that time, including reverting to |
| 768 |
arbitrary if it no longer has a value. |
| 769 |
4 loop-controls |
| 770 |
There are two special statements--both from 'C'--for changing the |
| 771 |
behavior of loop execution. The 'continue' statement is useful in |
| 772 |
a compound (block) statement; when executed, it effectively skips |
| 773 |
the rest of the block so that the increment-expression (only for |
| 774 |
for-loops) and loop-termination expression can be re-evaluated. |
| 775 |
|
| 776 |
The 'break' statement, when executed, effectively skips the rest |
| 777 |
of the block and also treats the test expression as if it were |
| 778 |
false (instead of actually re-evaluating it). In this case, the |
| 779 |
increment-expression of a for-loop is also skipped. |
| 780 |
|
| 781 |
Inside nested loops, both 'break' and 'continue' only apply to the |
| 782 |
innermost loop. When in compatibility mode, 'break' or 'continue' |
| 783 |
may be used outside of a loop; either will be treated like 'next' |
| 784 |
(see action-controls). |
| 785 |
4 action-controls |
| 786 |
There are two special statements for controlling statement execution. |
| 787 |
The 'next' statement, when executed, causes the rest of the current |
| 788 |
action and all further pattern-action rules to be skipped, so that |
| 789 |
the next input record will be immediately processed. This is useful |
| 790 |
if any early action knows that the current record will fail all the |
| 791 |
remaining patterns; skipping those rules will reduce processing time. |
| 792 |
|
| 793 |
A GAWK extension, 'nextfile', is also available. It causes the |
| 794 |
remainder of the current file to be skipped, the ENDFILE action, if |
| 795 |
applicable, to be performed, and then the next input file will be |
| 796 |
processed. If there is no next input file, the END action will be |
| 797 |
performed. 'nextfile' is not available in traditional awk. |
| 798 |
|
| 799 |
The 'exit' statement causes GAWK execution to terminate. All open |
| 800 |
files are closed, and no further processing is done. The END rule, |
| 801 |
if any, is executed. 'exit' takes an optional numeric value as a |
| 802 |
argument which is used as an exit status value, so that some sort |
| 803 |
of indication of why execution has stopped can be passed on to the |
| 804 |
user's environment. |
| 805 |
4 other_statements |
| 806 |
The delete statement is used to remove an element from an array. |
| 807 |
The syntax is 'delete' keyword followed by array name, followed |
| 808 |
by index value enclosed in square brackets ([]). As a gawk |
| 809 |
extension, 'delete' may also used on an array name without any |
| 810 |
index specified, to delete all its elements in a single operation. |
| 811 |
(The array itself will continue to exist as an array, even though |
| 812 |
it no longer contains any elements.) |
| 813 |
|
| 814 |
The return statement is used in user-defined functions. The syntax |
| 815 |
is the keyword 'return' optionally followed by a string or numeric |
| 816 |
expression. |
| 817 |
|
| 818 |
See also subtopic 'functions IO_functions' for a description of |
| 819 |
'print', 'printf', and 'getline'. |
| 820 |
3 fields |
| 821 |
When an input record is read, it is automatically split into fields |
| 822 |
based on the current values of FS (builtin variable defining field |
| 823 |
separator expression) and RS (builtin variable defining record |
| 824 |
separator character). The default value of FS is an expression |
| 825 |
which matches one or more spaces and tabs; the default for RS is |
| 826 |
newline. If the FIELDWIDTHS variable is set to a space separated |
| 827 |
list of numbers (as in ``FIELDWIDTHS = "2 3 2"'') then the input |
| 828 |
is treated as if it had fixed-width fields of the indicated sizes |
| 829 |
and the FS value will be ignored. |
| 830 |
|
| 831 |
The field prefix operator ($), is used to reference a particular |
| 832 |
field. For example, $3 designates the third field of the current |
| 833 |
record. The entire record can be referenced via $0 (and it holds |
| 834 |
the actual input record, not the values of $1, $2, ... concatenated |
| 835 |
together, so multiple spaces--when present--remain intact, unless |
| 836 |
a new value gets assigned). |
| 837 |
|
| 838 |
The builtin variable NF holds the number of fields in the current |
| 839 |
record. $NF is therefore the value of the last field. Attempts to |
| 840 |
access fields beyond NF result in null values (if a record contained |
| 841 |
3 fields, the value of $5 would be ""). |
| 842 |
|
| 843 |
Assigning a new value to $0 causes all the other field values (and NF) |
| 844 |
to be re-evaluated. Changing a specific field will cause $0 to receive |
| 845 |
a new value once it's re-evaluated, but until then the other existing |
| 846 |
fields remain unchanged. |
| 847 |
4 field_separation |
| 848 |
Three built in variables control separating input lines into fields, |
| 849 |
and the most recently assigned of those three is the one which has |
| 850 |
effect. PROCINFO["FS"] can be used to determine which one that is. |
| 851 |
|
| 852 |
FS is a character, string, or regular expression specifying what |
| 853 |
separates fields. It is available in all implementations of awk so |
| 854 |
is the most widely used. The default value is an explicit space and |
| 855 |
behaves as if the value was /[ \t\n]+/ to treat any number of spaces |
| 856 |
and tabs (and newlines, if RS isn't using them as record separators) |
| 857 |
as the separator. (Explicitly using that regular expression |
| 858 |
actually produces different results if the input happens to have |
| 859 |
leading and/or trailing whitespace. The default skips such space; |
| 860 |
the regexp increases NF by 1 and produces an empty $1 if there is |
| 861 |
leading whitespace and it increases NF by 1 and produces an empty $NF |
| 862 |
if there is trailing whitespace. To actually force the separator to |
| 863 |
be a single space, use the regular expression / /.) |
| 864 |
|
| 865 |
FIELDWIDTHS is a string containing a space-separated list of numbers |
| 866 |
which indicate how wide each field is. It is a gawk-extension and |
| 867 |
used to be considered experimental, but it has been in place for many |
| 868 |
years without significant changes. There is no default value, nor is |
| 869 |
there any way to specify a repeat count the way a Fortran FORMAT |
| 870 |
statment could. |
| 871 |
|
| 872 |
FPAT is a regular expression which specifies field values rather than |
| 873 |
the separation between fields. It is also a gawk-extension and is |
| 874 |
new with version 4.0.0. |
| 875 |
|
| 876 |
A gawk-extension makes setting FS to "" force each input character |
| 877 |
to be a separate field, similar to FIELDWIDTHS="1 1 1 1 1 1"(...) if |
| 878 |
you were able to supply an unlimited number of 1's. |
| 879 |
3 variables |
| 880 |
Variables in awk can hold both numeric and string values and do not |
| 881 |
have to be pre-declared. In fact, there is no way to explicitly |
| 882 |
declare them at all. Variable names consist of a leading letter |
| 883 |
(either upper or lower case, which are distinct from each other) |
| 884 |
or underscore (_) character followed by any number of letters, |
| 885 |
digits, or underscores. |
| 886 |
|
| 887 |
When a variable that didn't previously exist is referenced, it is |
| 888 |
created and given a null value. A null value is treated as 0 when |
| 889 |
used as a number, and is a string of zero characters in length if |
| 890 |
used as a string. |
| 891 |
4 builtin_variables |
| 892 |
GAWK maintains several 'built-in' variables. All have default values; |
| 893 |
some are updated automatically. All the builtins have uppercase-only |
| 894 |
names. |
| 895 |
|
| 896 |
These builtin variables control how awk behaves |
| 897 |
FS input field separator; default is a single space, which is |
| 898 |
treated as if it were a regular expression for matching |
| 899 |
one or more spaces and/or tabs and/or newlines; a value |
| 900 |
of " " also has a second special-case side-effect of |
| 901 |
causing leading and/or trailing blanks to be ignored |
| 902 |
instead of producing a null first and/or last field; |
| 903 |
initial value can be specified on the command line with |
| 904 |
the -F option (or /field_separator); the value can be a |
| 905 |
regular expression; as a gawk extension, if the value is |
| 906 |
an empty string (""), every character becomes a separate |
| 907 |
field |
| 908 |
RS input record separator; default value is a newline ("\n"); |
| 909 |
the value can be multiple characters or a regular expression |
| 910 |
OFS output field separator; value to place between variables in |
| 911 |
a 'print' statement; default is one space; can be arbitrary |
| 912 |
string |
| 913 |
ORS output record separator; value to implicitly terminate 'print' |
| 914 |
statement with; default is newline ("\n"); can be arbitrary |
| 915 |
string |
| 916 |
OFMT default output format used for printing numbers; default |
| 917 |
value is "%.6g" |
| 918 |
CONVFMT conversion format used for number-to-string conversions; |
| 919 |
default value is also "%.6g", like OFMT; not used when the |
| 920 |
number has a value which may be represented internally as |
| 921 |
an exact integer (typically within -2147483648 to 2147483647) |
| 922 |
SUBSEP subscript separator for array indices; used when an array |
| 923 |
subscript is specified as a comma separated list of values: |
| 924 |
the comma is replaced by SUBSEP and the resulting index |
| 925 |
is a concatenation of the values and SUBSEP(s); default |
| 926 |
value is "\034"; value may be arbitrary string |
| 927 |
IGNORECASE string and regular expression matching flag; if true |
| 928 |
(non-zero) matching ignores differences between upper and |
| 929 |
lower case letters; affects the '~' and '!~' operators, |
| 930 |
the 'index', 'match', 'split', 'sub', and 'gsub' functions, |
| 931 |
and field splitting based on FS; default value is false (0); |
| 932 |
has no effect if GAWK is in strict compatibility mode |
| 933 |
FIELDWIDTHS space or tab separated list of width sizes; takes |
| 934 |
precedence over FS when set, but is cleared if FS has a |
| 935 |
value assigned to it; [note: the current implementation |
| 936 |
of fixed-field input is considered experimental and is |
| 937 |
expected to evolve over time] |
| 938 |
FPAT an alternate way to specify fields, with a regexp pattern |
| 939 |
which defines field values rather than field separator |
| 940 |
[assigning a value to any of FS, FIELDWIDTHS, or FPAT |
| 941 |
causes the other two to be deactivated; the value of |
| 942 |
PROCINFO["FS"] can be used to determine which one is |
| 943 |
currently in use] |
| 944 |
BINMODE can be used force input and/or output files to be processed |
| 945 |
using binary I/O; a value of 1 or "r" forces binary mode when |
| 946 |
reading input, a value of 2 or "w" forces binary mode when |
| 947 |
writing output, and a value of 3 or "rw" causes GAWK to use |
| 948 |
binary mode for both input and output; BINMODE has no effect |
| 949 |
on reading from stdin or writing to stdout; they'll have |
| 950 |
already been opened in text mode before you assign a value |
| 951 |
LINT setting or unsetting this can dynamically toggle the --lint |
| 952 |
command line option on or off |
| 953 |
|
| 954 |
These builtin variables provide useful information |
| 955 |
NF number of fields in the current record |
| 956 |
NR record number (accumulated over all files when more than one |
| 957 |
input file is processed by the same program) |
| 958 |
FNR current record number of the current input file; reset to 0 |
| 959 |
each time an input file is completed |
| 960 |
RT record terminator, the input text which matched RS; not |
| 961 |
available when the `-Wtraditional' option is used |
| 962 |
RSTART starting position of substring matched by last invocation |
| 963 |
of the 'match' function; set to 0 if a match fails and at |
| 964 |
the start of each input record |
| 965 |
RLENGTH length of substring matched by the last invocation of the |
| 966 |
'match' function; set to -1 if a match fails |
| 967 |
FILENAME name of the input file currently being processed; the |
| 968 |
special name "-" is used to represent the standard input |
| 969 |
ENVIRON array of miscellaneous user environment values; the VMS |
| 970 |
implementation of GAWK provides values for ["USER"] (the |
| 971 |
username), ["PATH"] (current default directory), ["HOME"] |
| 972 |
(the user's login directory), and "[TERM]" (terminal type |
| 973 |
if available) [all info provided by C RTL's environ] |
| 974 |
PROCINFO miscellaneous process information and assorted GAWK |
| 975 |
extensions which don't fit in elsewhere |
| 976 |
ERRNO information about the cause of failure for 'getline' or |
| 977 |
'close' or for file open during a BEGINFILE rule; it is |
| 978 |
only set if an error has occurred, it isn't reset when |
| 979 |
any subsequent operation succeeds; the only exception is |
| 980 |
that it is reset prior to attempting to open a file so |
| 981 |
that BEGINFILE rule actions can distinguish between |
| 982 |
success and failure |
| 983 |
ARGC number of elements in the ARGV array, counting [0] which is |
| 984 |
the program name (ie, "gawk") |
| 985 |
ARGV array of command-line arguments (in [0] to [ARGC-1]); the |
| 986 |
program name (ie, "gawk") in held in ARGV[0]; command line |
| 987 |
parameters (data files and "var=value" expressions, but not |
| 988 |
program options or the awk program text string if present) |
| 989 |
are stored in ARGV[1] through ARGV[ARGC-1]; the awk program |
| 990 |
can change values of ARGC and ARGV[] during execution in |
| 991 |
order to alter which files are processed or which between- |
| 992 |
file assignments are made |
| 993 |
ARGIND current index into ARGV[] |
| 994 |
4 arrays |
| 995 |
awk supports associative arrays to collect data into tables. Array |
| 996 |
elements can be either numeric or string, as can the indices used to |
| 997 |
access them. Each array must have a unique name, but a given array |
| 998 |
can hold both string and numeric elements at the same time. Arrays |
| 999 |
are one-dimensional only, but multi-dimensional arrays can be |
| 1000 |
simulated using comma (,) separated indices, whereby a single index |
| 1001 |
value gets created by replacing commas with SUBSEP and concatenating |
| 1002 |
the resulting expression into a single string. |
| 1003 |
|
| 1004 |
Referencing an array element is done with the expression |
| 1005 |
Array[Index] |
| 1006 |
where 'Array' represents the array's name and 'Index' represents a |
| 1007 |
value or expression used for a subscript. If the requested array |
| 1008 |
element did not exist, it will be created and assigned an initial |
| 1009 |
null value. To check whether an element exists without creating it, |
| 1010 |
use the 'in' boolean operator. |
| 1011 |
Index in Array |
| 1012 |
would check 'Array' for element 'Index' and return 1 if it existed |
| 1013 |
or 0 otherwise. To remove an element from an array, use the 'delete' |
| 1014 |
statement |
| 1015 |
delete Array[Index] |
| 1016 |
To remove all array elements at once, use |
| 1017 |
delete Array |
| 1018 |
Note: the latter is a gawk extension; also, there is no way to |
| 1019 |
delete an ordinary variable or an entire array; 'delete' only works |
| 1020 |
on array elements. |
| 1021 |
|
| 1022 |
To process all elements of an array (in succession) when their |
| 1023 |
subscripts might be unknown, use the 'in' variant of the for-loop |
| 1024 |
for (Index in Array) { ... } |
| 1025 |
(See the "awk_language statements loops" entry for a way to control |
| 1026 |
the order of traversal with this construct.) |
| 1027 |
|
| 1028 |
Starting with version 4.0.0 array values can contain arrays, sometimes |
| 1029 |
referred to as sub-arrays. They're created by assigning a value using |
| 1030 |
multiple instances of subscripting: 'a[1][2] = 3' would create array |
| 1031 |
a if it didn't already exist, create array element a[1] if it didn't |
| 1032 |
already exist, create sub-array element a[1][2] if it didn't exist, |
| 1033 |
then assign that the value 3. You can't directly assign an existing |
| 1034 |
array to be a subarray: 'a[1] = 2; a[3] = 4; b["a"] = a' would get |
| 1035 |
rejected. But you can produce the same effect by traversing the array |
| 1036 |
and assigning it element by element: |
| 1037 |
'a[1] = 2; a[3] = 4; for (i in a) b["a"][i] = a[i]'. |
| 1038 |
3 functions |
| 1039 |
awk supports both built-in and user-defined functions. A function |
| 1040 |
may be considered a 'black-box' which accepts zero or more input |
| 1041 |
parameters, performs some calculations or other manipulations based |
| 1042 |
on them, and returns a single result. |
| 1043 |
|
| 1044 |
The syntax for calling a function consists of the function name |
| 1045 |
immediately followed by an open parenthesis (left parenthesis '('), |
| 1046 |
followed by an argument list, followed by a closing parenthesis |
| 1047 |
(right parenthesis ')'). The argument list is a sequence of values |
| 1048 |
(numbers, strings, variables, array references, or expressions |
| 1049 |
involving the above and/or nested function calls), separated by |
| 1050 |
commas and optional white space. |
| 1051 |
|
| 1052 |
The parentheses are required punctuation, except for the 'print' and |
| 1053 |
'printf' builtin IO functions, where they're optional, and for the |
| 1054 |
builtin IO function 'getline', where they're not allowed. Some |
| 1055 |
functions support optional [trailing] arguments which can be simply |
| 1056 |
omitted (along with the corresponding comma if applicable). |
| 1057 |
4 numeric_functions |
| 1058 |
Builtin numeric functions |
| 1059 |
int(n) returns the value of 'n' with any fraction truncated |
| 1060 |
[truncation of negative values is towards 0] |
| 1061 |
sqrt(n) the square root of n |
| 1062 |
exp(n) the exponential of n ('e' raised to the 'n'th power) |
| 1063 |
log(n) natural logarithm of n |
| 1064 |
sin(n) sine of n (in radians) |
| 1065 |
cos(n) cosine of n (radians) |
| 1066 |
atan2(m,n) arctangent of m/n (radians) |
| 1067 |
rand() random number in the range 0 to 1 (exclusive) |
| 1068 |
srand(s) sets the random number 'seed' to s, so that a sequence |
| 1069 |
of 'random' numbers can be repeated; returns the |
| 1070 |
previous seed value; srand() [argument omitted] sets |
| 1071 |
the seed to an 'unpredictable' value (based on date |
| 1072 |
and time, for instance, so should be unrepeatable) |
| 1073 |
4 string_functions |
| 1074 |
Builtin string functions |
| 1075 |
index(s,t) search string s for substring t; result is 1-based |
| 1076 |
offset of t within s, or 0 if not found |
| 1077 |
length(s) returns the length of string s; either 'length()' |
| 1078 |
with its argument omitted or 'length' without any |
| 1079 |
parenthesized argument list will return length of $0 |
| 1080 |
match(s,r) search string s for regular expression r; the offset |
| 1081 |
of the longest, left-most substring which matches |
| 1082 |
is returned, or 0 if no match was found; the builtin |
| 1083 |
variables RSTART and RLENGTH are also set [RSTART to |
| 1084 |
the return value and RLENGTH to the size of the |
| 1085 |
matching substring, or to -1 if no match was found] |
| 1086 |
split(s,a,f,x) break string s into components based on field |
| 1087 |
separator f and store them in array a (into elements |
| 1088 |
[1], [2], and so on); the third argument is optional, |
| 1089 |
if omitted, the value of FS is used; the fourth one |
| 1090 |
is optional too, and is a gawk extension; when |
| 1091 |
specified it should be an array which will receive |
| 1092 |
the separators between the corresponding fields; the |
| 1093 |
return value is the number of components found |
| 1094 |
patsplit(s,a,p,x) similar to split, but p is a regexp pattern |
| 1095 |
specifying field contents rather than a separator; |
| 1096 |
if not specified, the value of FPAT is used; this |
| 1097 |
function is a gawk extension |
| 1098 |
sprintf(f,e,...) format expression(s) e using format string f and |
| 1099 |
return the result as a string; formatting is similar |
| 1100 |
to the printf function |
| 1101 |
sub(r,t,s) search string target s for regular expression r, and |
| 1102 |
if a match is found, replace the matching text with |
| 1103 |
substring t, then store the result back in s; if s |
| 1104 |
is omitted, use $0 for the string; the result is |
| 1105 |
either 1 if a match+substitution was made, or 0 |
| 1106 |
otherwise; if substring t contains the character |
| 1107 |
'&', the text which matched the regular expression |
| 1108 |
is used instead of '&' [to suppress this feature |
| 1109 |
of '&', 'quote' it with a backslash (\); since this |
| 1110 |
will be inside a quoted string which will receive |
| 1111 |
'backslash' processing before being passed to sub(), |
| 1112 |
*two* consecutive backslashes will be needed "\\&"] |
| 1113 |
gsub(r,t,s) similar to sub(), but gsub() replaces all nonoverlapping |
| 1114 |
substrings instead of just the first, and the return |
| 1115 |
value is the number of substitutions made |
| 1116 |
gensub(r,t,n,s) search string s ($0 if omitted) for regexp r and |
| 1117 |
replace the n'th occurrence with substring t; the |
| 1118 |
result is the new string and s (or $0) remains |
| 1119 |
unchanged; if n begins with letter "g" or "G" then |
| 1120 |
all matches are replaced instead of just the n'th; |
| 1121 |
if r has parenthesized subexpressions in it, t may |
| 1122 |
contain the special sequences \\0, \\1, through \\9 |
| 1123 |
which expand into the value of the corresponding |
| 1124 |
subexpression; this function is a gawk extension |
| 1125 |
substr(s,p,l) extract a substring l characters long starting at |
| 1126 |
offset p in string s; l is optional, if omitted then |
| 1127 |
the remainder of the string (p thru end) is returned |
| 1128 |
tolower(s) return a copy of string s in which every uppercase |
| 1129 |
letter has been converted into lowercase |
| 1130 |
toupper(s) analogous to tolower(); convert lowercase to uppercase |
| 1131 |
strtonum(s) convert string s into the corresponding number; if s |
| 1132 |
begins with "0x", the rest of the string will be |
| 1133 |
considered to be hexacimal digits, otherwise if it |
| 1134 |
begins with "0" (not "o"), the rest will be treated |
| 1135 |
as octal digits; this function is a gawk extension |
| 1136 |
4 array_functions |
| 1137 |
isarray(a) returns 1 of a is an array, 0 otherwise; most useful |
| 1138 |
when traversing an array which might contain array |
| 1139 |
values (sub-arrays) |
| 1140 |
split(s,a[,f[,x]]) break string s into components based on field |
| 1141 |
separator f and store them in array a (into elements |
| 1142 |
[1], [2], and so on); the third argument is optional, |
| 1143 |
if omitted, the value of FS is used; the fourth one |
| 1144 |
is optional too, and is a gawk extension; when |
| 1145 |
specified it should be an array which will receive |
| 1146 |
the separators between the corresponding fields; the |
| 1147 |
return value is the number of components found |
| 1148 |
patsplit(s,a[,p[,x]]) similar to split, but p is a regexp pattern |
| 1149 |
specifying field contents rather than a separator; |
| 1150 |
if not specified, the value of FPAT is used; this |
| 1151 |
function is a gawk extension |
| 1152 |
asort(s[,d[,m]]) sort the contents of array s, replacing the index |
| 1153 |
values with an integer sequence of 1 to N; if d is |
| 1154 |
specified, leave the indices of s intact and put the |
| 1155 |
values and sequence index into d; if m is specified, |
| 1156 |
it should be a string containing "ascending" or |
| 1157 |
"descending" to control order, or "string" or "number" |
| 1158 |
to control how comparisons are performed, or a |
| 1159 |
combination of the two; m can also be a comparison |
| 1160 |
function similar to ones used by PROCINFO["sorted_in"] |
| 1161 |
asorti(s[,d[,m]]) sort the indices of array s, replacing the values |
| 1162 |
with an integer sequence of 1 to N; if d is specified, |
| 1163 |
leave the values of s intact and put the indices and |
| 1164 |
sequence values into d; m is the same as for asort() |
| 1165 |
4 time_functions |
| 1166 |
Builtin time functions |
| 1167 |
systime() return the current time of day as the number of seconds |
| 1168 |
since some reference point; on VMS the reference point |
| 1169 |
is January 1, 1970, at 12 AM local time (not UTC) |
| 1170 |
mktime(s) convert string s into number of seconds since the |
| 1171 |
reference point; s should contain a value of the form |
| 1172 |
"yyyy mm dd hh mm ss[ dst]" where yyyy is a four digit |
| 1173 |
year, mm a month number from 1 to 12, dd day-of-month |
| 1174 |
number from 1 to 31, hh hour 0 to 23, mm minute 0 to |
| 1175 |
59, ss second 0 to 60, and [ dst] is an optional flag |
| 1176 |
to handle daylight savings time: if dst is positive, |
| 1177 |
then daylight savins time is in effect, if zero, then |
| 1178 |
it isn't, and if negative or omitted, gawk attempts |
| 1179 |
to determine whether it was--or will be--at specified |
| 1180 |
date and time |
| 1181 |
strftime(f,t,u) format time value t using format f; if it is omitted |
| 1182 |
then PROCINFO["strftime"] is used; if t is omitted, |
| 1183 |
the default is systime(); if u is present and non-zero |
| 1184 |
then t is treated as a UTC value, otherwise it is |
| 1185 |
considered to be local time |
| 1186 |
|
| 1187 |
5 time_logical_names |
| 1188 |
Gawk needs the SYS$TIMEZONE_RULE or TZ logical names defined or it will |
| 1189 |
output the time in the GMT timezone. |
| 1190 |
5 time_formats |
| 1191 |
Formatting directives similar to the 'printf' & 'sprintf' functions |
| 1192 |
(each is introduced in the format string by preceding it with a |
| 1193 |
percent sign (%)); the directive is substituted by the corresponding |
| 1194 |
value |
| 1195 |
a abbreviated weekday name (Sun,Mon,Tue,Wed,Thu,Fri,Sat) |
| 1196 |
A full weekday name |
| 1197 |
b abbreviated month name (Jan,Feb,...) |
| 1198 |
B full month name |
| 1199 |
c date and time (Unix-style "aaa bbb dd HH:MM:SS YYYY" format) |
| 1200 |
C century prefix (19 or 20) [not century number, ie 20th] |
| 1201 |
d day of month as two digit decimal number (01-31) |
| 1202 |
D date in mm/dd/yy format |
| 1203 |
e day of month with leading space instead of leading 0 ( 1-31) |
| 1204 |
E ignored; following format character used |
| 1205 |
H hour (24 hour clock) as two digit number (00-23) |
| 1206 |
h abbreviated month name (Jan,Feb,...) [same as %b] |
| 1207 |
I hour (12 hour clock) as two digit number (01-12) |
| 1208 |
j day of year as three digit number (001-366) |
| 1209 |
m month as two digit number (01-12) |
| 1210 |
M minute as two digit number (00-59) |
| 1211 |
n 'newline' (ie, treat %n as \n) |
| 1212 |
O ignored; following format character used |
| 1213 |
p AM/PM designation for 12 hour clock |
| 1214 |
r time in AM/PM format ("II:MM:SS p") |
| 1215 |
R time without seconds ("HH:MM") |
| 1216 |
S second as two digit number (00-59) |
| 1217 |
t tab (ie, treat %t as \t) |
| 1218 |
T time ("HH:MM:SS") |
| 1219 |
U week of year (00-53) [first Sunday is first day of week 1] |
| 1220 |
V date (VMS-style "dd-bbb-YYYY" with 'bbb' forced to uppercase) |
| 1221 |
w weekday as decimal digit (0 [Sunday] through 6 [Saturday]) |
| 1222 |
W week of year (00-53) [first _Monday_ is first day of week 1] |
| 1223 |
x date ("aaa bbb dd YYYY") |
| 1224 |
X time ("HH:MM:SS") |
| 1225 |
y year without century (00-99) |
| 1226 |
Y year with century (19yy-20yy) |
| 1227 |
Z time zone name (always "local" for VMS) |
| 1228 |
% literal percent sign (%) |
| 1229 |
4 IO_functions |
| 1230 |
Builtin I/O functions |
| 1231 |
print x,... print the values of one or more expressions; if none |
| 1232 |
are listed, $0 is used; parentheses are optional; |
| 1233 |
when multiple values are printed, the current value |
| 1234 |
of builtin OFS (default is 1 space) is used to |
| 1235 |
separate them; the print line is implicitly |
| 1236 |
terminated with the current value of ORS (default |
| 1237 |
is newline); print does not have a return value |
| 1238 |
printf(f,x,...) print the values of one or more expressions, using |
| 1239 |
the specified format string; null strings are used |
| 1240 |
to supply missing values (if any); no between field |
| 1241 |
or trailing newline characters are printed, they |
| 1242 |
should be specified within the format string; the |
| 1243 |
argument-enclosing parentheses are optional; |
| 1244 |
printf does not have a return value |
| 1245 |
getline v read a record into variable v; if v is omitted, $0 is |
| 1246 |
used (and NF, NR, and FNR are updated); if v is |
| 1247 |
specified, then field-splitting won't be performed; |
| 1248 |
note: parentheses around the argument are *not* |
| 1249 |
allowed; return value is 1 for successful read, 0 |
| 1250 |
if end of file is encountered, or -1 if some sort |
| 1251 |
of error occurred; [see 'redirection' for several |
| 1252 |
variants] |
| 1253 |
close(s) close a file or pipe specified by the string s; the |
| 1254 |
string used should have the same value as the one |
| 1255 |
used in a getline or print/printf redirection |
| 1256 |
fflush(s) flush output stream s; if s is omitted, stdout is |
| 1257 |
flushed; if it is specified but its value is an |
| 1258 |
empty string, all output streams are flushed |
| 1259 |
system(s) pass string s to executed by the operating system; |
| 1260 |
the command string is executed in a subprocess |
| 1261 |
5 redirection |
| 1262 |
Both getline and print/printf support variant forms which use |
| 1263 |
redirection and pipes. |
| 1264 |
|
| 1265 |
To read from a file (instead of from the primary input file), use |
| 1266 |
getline var < "file" |
| 1267 |
or getline < "file" (read into $0) |
| 1268 |
where the string "file" represents either an actual file name (in |
| 1269 |
quotes) or a variable which contains a file name string value or an |
| 1270 |
expression which evaluates to a string filename. |
| 1271 |
|
| 1272 |
To create a pipe executing some command and read the result into |
| 1273 |
a variable (or into $0), use |
| 1274 |
"command" | getline var |
| 1275 |
or "command" | getline (read into $0) |
| 1276 |
where "command" is a literal string containing an operating system |
| 1277 |
command or a variable with a string value representing such a |
| 1278 |
command. |
| 1279 |
|
| 1280 |
To output into a file other that the primary output, use |
| 1281 |
print x,... > "file" (or >> "file") |
| 1282 |
or printf(f,x,...) > "file" (or >> "file") |
| 1283 |
similar to the 'getline' example above. '>>' causes output to be |
| 1284 |
appended to an existing file if it exists, or create the file if |
| 1285 |
it doesn't already exist. '>' always creates a new file. The |
| 1286 |
alternate redirection method of '>$' (for RMS text file attributes) |
| 1287 |
is *only* available on the command line, not with 'print' or |
| 1288 |
'printf' in the current release. |
| 1289 |
|
| 1290 |
To output an error message, use 'print' or 'printf' and redirect |
| 1291 |
the output to file "/dev/stderr" (or equivalently to "SYS$ERROR:" |
| 1292 |
on VMS). 'stderr' will normally be the user's terminal, even if |
| 1293 |
ordinary output is being redirected into a file. |
| 1294 |
|
| 1295 |
To feed awk output into another command, use |
| 1296 |
print x,... | "command" (similarly for 'printf') |
| 1297 |
similar to the second 'getline' example. In this case, output |
| 1298 |
from awk will be passed as input to the specified operating system |
| 1299 |
command. The command must be capable of reading input from 'stdin' |
| 1300 |
("SYS$INPUT:" on VMS) in order to receive data in this manner. |
| 1301 |
|
| 1302 |
The 'close' function operates on the "file" or "command" argument |
| 1303 |
specified here (either a literal string or a variable or expression |
| 1304 |
resulting in a string value). It completely closes the file or |
| 1305 |
pipe so that further references to the same file or command string |
| 1306 |
would re-open that file or command at the beginning. Closing a |
| 1307 |
pipe or redirection also releases some file-oriented resources. |
| 1308 |
|
| 1309 |
Note: the VMS implementation of GAWK uses temporary files to |
| 1310 |
simulate pipes, so a command must finish before 'getline' can get |
| 1311 |
any input from it, and 'close' must be called for an output pipe |
| 1312 |
before any data can be passed to the specified command. |
| 1313 |
5 formats |
| 1314 |
Formatting characters used by the 'printf' and 'sprintf' functions |
| 1315 |
(each is introduced in the format string by preceding it with a |
| 1316 |
percent sign (%)) |
| 1317 |
% include a literal percent sign (%) in the result |
| 1318 |
c format the next argument as a single ASCII character |
| 1319 |
(prints first character of string argument, or corresponding |
| 1320 |
ASCII character if numeric argument, e.g. 65 is 'A') |
| 1321 |
s format the next argument as a string (numeric arguments are |
| 1322 |
converted into strings on demand) |
| 1323 |
d decimal number (ie, integer value in base 10) |
| 1324 |
i integer (equivalent to decimal) |
| 1325 |
o octal number (integer in base 8) |
| 1326 |
x hexadecimal number (integer in base 16) [lowercase] |
| 1327 |
X hexadecimal number [digits 'A' thru 'E' in uppercase] |
| 1328 |
f floating point number (digits, decimal point, fraction digits) |
| 1329 |
e exponential (scientific notation) number (digit, decimal |
| 1330 |
point, fraction digits, letter 'e', sign '+' or '-', |
| 1331 |
exponent digits) |
| 1332 |
g 'fractional' number in either 'e' or 'f' format, whichever |
| 1333 |
produces shorter result |
| 1334 |
|
| 1335 |
Several optional modifiers can be placed between the initiating |
| 1336 |
percent sign and the format character (doesn't apply to %%). |
| 1337 |
- left justify (only matters when width specifier is present) |
| 1338 |
(space) for numeric specifiers, prefix nonnegative values with |
| 1339 |
a space and negative values with a minus sign |
| 1340 |
+ for numeric specifiers, prefix nonnegative values with a plus |
| 1341 |
sign and negative values with a minus sign |
| 1342 |
# alternate form applicable to several of the format characters |
| 1343 |
(o, x, X, e, E, f, g, G) |
| 1344 |
NN width ['NN' represents 1 or more decimal digits]; actually |
| 1345 |
minimum width to use, longer items will not be truncated; a |
| 1346 |
leading 0 will cause right-justified numbers to be padded on |
| 1347 |
the left with zeroes instead of spaces when they're aligned |
| 1348 |
.MM precision [decimal point followed by 1 or more digits]; used |
| 1349 |
as maximum width for strings (causing truncation if they're |
| 1350 |
actually longer) or as number of fraction digits for 'f' or |
| 1351 |
'e' numeric formats, or number of significant digits for 'g' |
| 1352 |
numeric format |
| 1353 |
4 bitwise_functions |
| 1354 |
Bitwise functions operate on bits (binary digits) of integer |
| 1355 |
numeric values. Non-integer numbers are converted into integers |
| 1356 |
before their bits are accessed. |
| 1357 |
|
| 1358 |
and(x,y) x AND y, where result contains 1 for bits that both x |
| 1359 |
and y have set, 0 for other bits |
| 1360 |
or(x,y) x OR y, where the result contains 1 for any bits that |
| 1361 |
either x or y or both have set, 0 for other bits |
| 1362 |
xor(x,y) x XOR y, where the result contains 1 for bits that x |
| 1363 |
has set but y has clear or vice versa, 0 for other bits |
| 1364 |
compl(x) NOT x, where the result contains 1 for bits that x |
| 1365 |
has clear and 0 for bits that it has set |
| 1366 |
lshift(x,n) x << n, shift the bits of x by n positions left, |
| 1367 |
approximately the same as x * 2^n |
| 1368 |
rshift(x,n) x >> n, shift the bits of x by n positions right, |
| 1369 |
approximately the same as int(x / 2^n) |
| 1370 |
|
| 1371 |
The set of bitwise functions is a gawk extension. |
| 1372 |
4 user_defined_functions |
| 1373 |
User-defined functions may be created as needed to simplify awk |
| 1374 |
programs or to collect commonly used code into one place. The |
| 1375 |
general syntax of a user-defined function is the 'function' keyword |
| 1376 |
followed by unique function name, followed by a comma-separated |
| 1377 |
parameter list enclosed in parentheses, followed by statement(s) |
| 1378 |
enclosed within braces ({}). A 'return' statement is customary |
| 1379 |
but is not required. |
| 1380 |
function FuncName(arg1,arg2) { |
| 1381 |
# arbitrary statements |
| 1382 |
return (arg1 + arg2) / 2 |
| 1383 |
} |
| 1384 |
If a function does not use 'return' to specify an output value, the |
| 1385 |
result received by the caller will be unpredictable. |
| 1386 |
|
| 1387 |
Functions may be placed in an awk program before, between, or after |
| 1388 |
the pattern-action rules. The abbreviation 'func' may be used in |
| 1389 |
place of 'function', unless POSIX compatibility mode is in effect. |
| 1390 |
4 indirect_function_calls |
| 1391 |
A gawk extension allows you to assign a string containing the name |
| 1392 |
of a function to a variable, then call the function by preceding |
| 1393 |
the variable with @ (at-sign) and following with the parenthesized |
| 1394 |
argument list. For example |
| 1395 |
|
| 1396 |
function my_max(x, y) { return (x > y) ? x : y } |
| 1397 |
function my_min(x, y) { return (x < y) ? x : y } |
| 1398 |
... |
| 1399 |
max_or_min = some_criterion ? "my_max" : "my_min" |
| 1400 |
... |
| 1401 |
c = @max_or_min(a, b) |
| 1402 |
|
| 1403 |
would call either my_max() or my_min() depending upon the value of |
| 1404 |
some_criterion at the time max_or_min was assigned. |
| 1405 |
|
| 1406 |
Indirect function calls only operate on user-defined functions, not |
| 1407 |
on built-in ones. If you need to use one of the latter, create a |
| 1408 |
user-defined function to call the built-in function; this if often |
| 1409 |
referred to as a "wrapper" function. |
| 1410 |
3 regular_expressions |
| 1411 |
A regular expression is a shorthand way of specifying a 'wildcard' |
| 1412 |
type of string comparison. Regular expression matching is very |
| 1413 |
fundamental to awk's operation. |
| 1414 |
|
| 1415 |
Meta symbols |
| 1416 |
^ matches beginning of line or beginning of string; note that |
| 1417 |
embedded newlines ('\n') create multi-line strings, so |
| 1418 |
beginning of line is not necessarily beginning of string |
| 1419 |
$ matches end of line or end of string |
| 1420 |
. any single character (except newline) |
| 1421 |
[ ] set of characters; [ABC] matches either 'A' or 'B' or 'C'; a |
| 1422 |
dash (other than first or last of the set) denotes a range |
| 1423 |
of characters: [A-Z] matches any upper case letter; if the |
| 1424 |
first character of the set is '^', then the sense of match |
| 1425 |
is reversed: [^0-9] matches any non-digit; several |
| 1426 |
characters need to be quoted with backslash (\) if they |
| 1427 |
occur in a set: '\', ']', '-', and '^'; within sets, |
| 1428 |
various special character class designations are recognized, |
| 1429 |
such as [:digit:] and [:punct:], as per POSIX |
| 1430 |
| alternation (similar to boolean 'or'); match either of two |
| 1431 |
patterns [for example "^start|stop$" matches leading 'start' |
| 1432 |
or trailing 'stop'] |
| 1433 |
( ) grouping, alter normal precedence [for example, "^(start|stop)$" |
| 1434 |
matches lines reading either 'start' or 'stop'] |
| 1435 |
* repeated matching; when placed after a pattern, indicates that |
| 1436 |
the pattern should match any number of times [for example, |
| 1437 |
"[a-z][0-9]*" matches a lower case letter followed by zero or |
| 1438 |
more digits] |
| 1439 |
+ repeated matching; when placed after a pattern, indicates that |
| 1440 |
the pattern should match one or more times ["[0-9]+" matches |
| 1441 |
any non-empty sequence of digits] |
| 1442 |
? optional matching; indicates that the pattern can match zero or |
| 1443 |
one times ["[a-z][0-9]?" matches lower case letter alone or |
| 1444 |
followed by a single digit] |
| 1445 |
{ } interval specification; {n} to match n times or {m,n} to match |
| 1446 |
at least m but not more than n times; only functional when |
| 1447 |
either the `-Wposix' or `-Wre-interval' options are used |
| 1448 |
\ quote; prevent the character which follows from having special |
| 1449 |
meaning; if the regexp is specified as a string, then the |
| 1450 |
backslash itself will need to be quoted by preceding it with |
| 1451 |
another backslash |
| 1452 |
|
| 1453 |
A regular expression which matches a string or line will match against |
| 1454 |
the first (left-most) substring which meets the pattern and include |
| 1455 |
the longest sequence of characters which still meets that pattern. |
| 1456 |
3 comments |
| 1457 |
Comments in awk programs are introduced with '#'. Anything after |
| 1458 |
'#' on a line is ignored by GAWK. It's a good idea to include an |
| 1459 |
explanation of what an awk program is doing and also who wrote it |
| 1460 |
and when. |
| 1461 |
3 further_information |
| 1462 |
For complete documentation on GAWK, see "Effective AWK Programming" |
| 1463 |
by Arnold Robbins. The second edition (ISBN 1-57831-000-8) is jointly |
| 1464 |
published by SSC and the FSF (http://www.ssc.com). |
| 1465 |
|
| 1466 |
Source text for it is present in the file GAWK.TEXI. A postscript |
| 1467 |
version is available via anonymous FTP from host gnudist.gnu.org in |
| 1468 |
directory /gnu/gawk, file gawk-{version}-doc.tar.gz where {version} |
| 1469 |
would be the current version number, such as 3.0.6. |
| 1470 |
|
| 1471 |
Another source of documentation is "The AWK Programming Language" |
| 1472 |
by Aho, Weinberger, and Kernighan (1988), published by Addison-Wesley. |
| 1473 |
ISBN code is 0-201-07981-X. |
| 1474 |
|
| 1475 |
Each of these works contains both a reference on the awk language |
| 1476 |
and a tutorial on awk's use, with many sample programs. |
| 1477 |
3 authors |
| 1478 |
The awk programming language was originally created by Alfred V. Aho, |
| 1479 |
Peter J. Weinberger, and Brian W. Kernighan in 1977. The language |
| 1480 |
was revised and enhanced in a new version which was released in 1985. |
| 1481 |
|
| 1482 |
GAWK, the GNU implementation of awk, was written in 1986 by Paul Rubin |
| 1483 |
and Jay Fenlason, with advice from Richard Stallman, and with |
| 1484 |
contributions from John Woods. In 1988 and 1989, David Trueman and |
| 1485 |
Arnold Robbins revised GAWK for compatibility with the newer awk. |
| 1486 |
Arnold Robbins is the current maintainer. |
| 1487 |
|
| 1488 |
GAWK version 2.11.1 was ported to VMS by Pat Rankin in November, 1989, |
| 1489 |
with further revisions in the Spring of 1990. The VMS port was |
| 1490 |
incorporated into the official GNU distribution of version 2.13 in |
| 1491 |
Spring 1991. (Version 2.12 was never publically released.) |
| 1492 |
2 release_notes |
| 1493 |
GAWK 4.0.0 has many changes from 3.1.8, and these release_notes were |
| 1494 |
not updated for any of the 3.1.* releases, so some information is |
| 1495 |
probably missing or out of date. In particular, the known_problems |
| 1496 |
subtopic hasn't been touched in many years. |
| 1497 |
3 AWK_LIBRARY |
| 1498 |
GAWK uses a built in search path when looking for a program file |
| 1499 |
specified by the -f option (or the /input qualifier) when that file |
| 1500 |
name does not include a device and/or directory. GAWK will first |
| 1501 |
look in the current default directory, then if the file wasn't found |
| 1502 |
it will look in the directory specified by the translation of logical |
| 1503 |
name "AWK_LIBRARY". |
| 1504 |
3 known_problems |
| 1505 |
There are several known problems with GAWK running on VMS. Some can |
| 1506 |
be ignored, others require work-arounds. |
| 1507 |
4 file_formats |
| 1508 |
If a file having the RMS attribute "Fortran carriage control" is |
| 1509 |
read as input, it will generate an empty first record if the first |
| 1510 |
actual record begins with a space (leading space becomes a newline). |
| 1511 |
Also, the last record of the file will give a "record not terminated" |
| 1512 |
warning. Both of these minor problems are due to the way that the |
| 1513 |
C Run-Time Library (VAXCRTL) converts record attributes. |
| 1514 |
|
| 1515 |
Another poor feature without a work-around is that there's no way to |
| 1516 |
specify "append if possible, create with RMS text attributes if not" |
| 1517 |
with the current command line I/O redirection. '>>$' isn't supported. |
| 1518 |
Ditto for binary output; '>>+' isn't supported. |
| 1519 |
4 RS_peculiarities |
| 1520 |
Changing the record separator to something other than newline ('\n') |
| 1521 |
will produce anomalous results for ordinary files. For example, |
| 1522 |
using RS = "\f" and FS = "\n" with the following input |
| 1523 |
|rec 1, line 1 |
| 1524 |
|rec 1, line 2 |
| 1525 |
|^L (form feed) |
| 1526 |
|rec 2, line 1 |
| 1527 |
|rec 2, line 2 |
| 1528 |
|^L (form feed) |
| 1529 |
|rec 3, line 1 |
| 1530 |
|rec 3, line 2 |
| 1531 |
|(end of file) |
| 1532 |
will produce two fields for record 1, but three fields each for |
| 1533 |
records 2 and 3. This is because the form-feed record delimiter is |
| 1534 |
on its own line, so awk sees a newline after it. Since newline is |
| 1535 |
now a field separator, records 2 and 3 will have null first fields. |
| 1536 |
The following awk code will work-around this problem by inserting |
| 1537 |
a null first field in the first record, so that all records can be |
| 1538 |
handled the same by subsequent processing. |
| 1539 |
# fix up for first record (RS != "\n") |
| 1540 |
FNR == 1 { if ( $0 == "" ) #leading separator |
| 1541 |
next #skip its null record |
| 1542 |
else #otherwise, |
| 1543 |
$0 = FS $0 #realign fields |
| 1544 |
} |
| 1545 |
There is a second problem with this same example. It will always |
| 1546 |
trigger a "record not terminated" warning when it reaches the end of |
| 1547 |
file. In the sample shown, there is no final separator; however, if |
| 1548 |
a trailing form-feed were present, it would produce a spurious final |
| 1549 |
record with two null fields. This occurs because the I/O system |
| 1550 |
sees an implicit newline at the end of the last record, so awk sees |
| 1551 |
a pair of null fields separated by that newline. The following code |
| 1552 |
fragment will fix that provided there are no null records (in this |
| 1553 |
case, that would be two consecutive lines containing just form-feeds). |
| 1554 |
# fix up for last record (RS != "\n") |
| 1555 |
$0 == FS { next } #drop spurious final record |
| 1556 |
Note that the "record not terminated" warning will persist. |
| 1557 |
4 cmd_inconsistency |
| 1558 |
The DCL qualifier /OUTPUT is internally equivalent to '>$' output |
| 1559 |
redirection, but the qualifier /INPUT corresponds to the -f option |
| 1560 |
rather than to '<' input redirection. |
| 1561 |
4 exit |
| 1562 |
The exit statement can optionally pass a final status value to the |
| 1563 |
operating system. GAWK expects a UN*X-style value instead of a |
| 1564 |
VMS status value, so 0 indicates success. A failure is indicated |
| 1565 |
by 1 and VMS will set the ERROR status. A fatal error is indicated |
| 1566 |
by 2 and VMS will set the FATAL status. All other values will will have |
| 1567 |
the SUCCESS status. The exit value is encoded to comply with VMS |
| 1568 |
coding standards and will have the C_FACILITY_NO of 0x350000 with |
| 1569 |
the constant 0xA000 added to the number shifted over by 3 bits to |
| 1570 |
make room for the severity codes. |
| 1571 |
|
| 1572 |
To extract the actual gawk exit code from the VMS status use: |
| 1573 |
unix_status = (vms_status .and. &x7f8) / 8 |
| 1574 |
|
| 1575 |
A C program that uses exec() to call gawk will get the original |
| 1576 |
UN*X-style exit value. |
| 1577 |
|
| 1578 |
Older versions of Gawk treated Unix exit code 0 as 1, A failure as |
| 1579 |
2, and a fatal error as 4, and passed all the other numbers through. |
| 1580 |
This violated the VMS exit status coding requirements. |
| 1581 |
|
| 1582 |
4 rounding |
| 1583 |
VAX/VMS floating point uses unbiased rounding. This is different than |
| 1584 |
what portable gawk programs expect. |
| 1585 |
|
| 1586 |
3 changes |
| 1587 |
Changes between version 4.0.0 and earlier versions |
| 1588 |
|
| 1589 |
[This 'changes' section hasn't been updated in many releases. Some |
| 1590 |
features mentioned here may have become available in versions 3.1.*.] |
| 1591 |
|
| 1592 |
General |
| 1593 |
dgawk.exe does interactive debugging of awk programs |
| 1594 |
pgawk.exe does comprehensive execution profiling of awk programs |
| 1595 |
pgawk.exe is not currently supplied for VMS. |
| 1596 |
-d[file] and -p[file] options added |
| 1597 |
-Wcompat and -Wusage options dropped; use -Wtraditional and -Whelp |
| 1598 |
BEGINFILE and ENDFILE built-in rule patterns |
| 1599 |
nextfile statement skips remainder of current input file |
| 1600 |
switch-case statement performs an alternate form of if-then-else |
| 1601 |
indirect function calls: var="user_function"; @var(args) |
| 1602 |
|
| 1603 |
FPAT regexp pattern as alternative to FS field splitting |
| 1604 |
patsplit() function, FPAT analog to split() |
| 1605 |
PROCINFO["sorted_in"] can be used to control traversal order for |
| 1606 |
'for (index in array)' statement |
| 1607 |
asort(), asorti() functions, to sort arrays |
| 1608 |
sub-arrays: array element values can be arrays |
| 1609 |
isarray() function, to test whether a value is an array |
| 1610 |
|
| 1611 |
PROCINFO["strftime"] can be used to supply default format for |
| 1612 |
date/time formatting by strftime() function |
| 1613 |
mktime() function, to convert list of separate date and time fields |
| 1614 |
into single numeric date/time value |
| 1615 |
and(), or(), xor(), compl(), lshift(), rshift() functions, to |
| 1616 |
perform bit-wise logic operations on numeric values |
| 1617 |
strtonum() function, to convert string of digits into number, with |
| 1618 |
support for radix prefix '0' (octal) and '0x' (hexadecimal) |
| 1619 |
|
| 1620 |
VMS-specific |
| 1621 |
The VMS exit codes now correctly encode the gawk exit status and |
| 1622 |
the VMS severity bits are set. |
| 1623 |
Large file support is enabled on the platforms that support it. |
| 1624 |
Extended filename support is enabled on the platforms that support it. |
| 1625 |
New command qualifiers: /EXTRA_COMMANDS, /PROFILE, /DUMP_VARIABLES, |
| 1626 |
/OPTIMIZE, /TRADITIONAL, /SANDBOX, /NON_DECIMAL_DATA |
| 1627 |
Revised qualifier: /LINT, takes optional argument list |
| 1628 |
Deprecated qualifier: /STRICT, superseded by /TRADITIONAL |
| 1629 |
3 prior_changes |
| 1630 |
Changes between version 3.1.8 and [...] and 3.0.6 |
| 1631 |
|
| 1632 |
[Someday someone ought to dig up and document this information....] |
| 1633 |
|
| 1634 |
Changes between version 3.0.6 and 2.15.6 |
| 1635 |
|
| 1636 |
General |
| 1637 |
RS can contain multiple characters or be a regexp |
| 1638 |
Regular expression interval support added |
| 1639 |
gensub() and fflush() functions added |
| 1640 |
memory leak(s) introduced in 3.0.2 or 3.0.1 fixed |
| 1641 |
the user manual has been substantially revised |
| 1642 |
|
| 1643 |
VMS-specific |
| 1644 |
Switched to build with DEC C by default |
| 1645 |
Changes between version 2.15.6 and 2.14 |
| 1646 |
|
| 1647 |
General |
| 1648 |
Many obscure bugs fixed |
| 1649 |
`delete' may operate on an entire array |
| 1650 |
ARGIND and ERRNO builtin variables added |
| 1651 |
|
| 1652 |
VMS-specific |
| 1653 |
`>+ file' binary-mode output redirection added |
| 1654 |
/variable=(foo=42) fixed |
| 1655 |
Floating point number formatting improved |
| 1656 |
|
| 1657 |
Changes between version 2.14 and 2.13.2: |
| 1658 |
|
| 1659 |
General |
| 1660 |
'next file' construct added |
| 1661 |
'continue' outside of any loop is treated as 'next' |
| 1662 |
Assorted bug fixes and efficiency improvements |
| 1663 |
_The_GAWK_Manual_ updated |
| 1664 |
Test suite expanded |
| 1665 |
|
| 1666 |
VMS-specific |
| 1667 |
VMS POSIX support added |
| 1668 |
Disk I/O throughput enhanced |
| 1669 |
Pipe emulation improved and incorrect interaction with user-mode |
| 1670 |
redefinition of SYS$OUTPUT eliminated |
| 1671 |
|
| 1672 |
Changes between version 2.13 and 2.11.1: (2.12 was not released) |
| 1673 |
|
| 1674 |
General |
| 1675 |
CONVFMT and FIELDWIDTHS builtin control variables added |
| 1676 |
systime() and strftime() date/time functions added |
| 1677 |
'lint' and 'posix' run-time options added |
| 1678 |
'-W' command line option syntax supercedes '-c', '-C', and '-V' |
| 1679 |
'-a' and '-e' regular expression options made obsolete |
| 1680 |
Various bug fixes and efficiency improvements |
| 1681 |
More platforms supported ('officially' including VMS) |
| 1682 |
|
| 1683 |
VMS-specific |
| 1684 |
%g printf format fixed |
| 1685 |
Handling of '\' on command line modified; no longer necessary to |
| 1686 |
double it up |
| 1687 |
Problem redirecting stderr (>&efile) at same time as stdin (<ifile) |
| 1688 |
or stdout (>ofile) has been fixed |
| 1689 |
``2>&1'' and ``1>&2'' redirection constructs added |
| 1690 |
Interaction between command line I/O redirection and gawk pipes |
| 1691 |
fixed; also, name used for pseudo-pipe temporary file expanded |
| 1692 |
3 license |
| 1693 |
GAWK is covered by the "GNU General Public License", the gist of which |
| 1694 |
is that if you supply this software to a third party, you are expressly |
| 1695 |
forbidden to prevent them from supplying it to a fourth party, and if |
| 1696 |
you supply binaries you must make the source code available to them |
| 1697 |
at no additional cost. Any revisions or modified versions are also |
| 1698 |
covered by the same license. There is no warranty, express or implied, |
| 1699 |
for this software. It is provided "as is." |
| 1700 |
|
| 1701 |
[Disclaimer: This is just an informal summary with no legal basis; |
| 1702 |
refer to the actual GNU General Public License for specific details.] |
| 1703 |
!2 examples |
| 1704 |
! |