1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
|
MAWK(1) USER COMMANDS MAWK(1)
NNAAMMEE
mawk - pattern scanning and text processing language
SSYYNNOOPPSSIISS
mmaawwkk [-WW _o_p_t_i_o_n] [-FF _v_a_l_u_e] [-vv _v_a_r_=_v_a_l_u_e] [--] 'program text' [file
...]
mmaawwkk [-WW _o_p_t_i_o_n] [-FF _v_a_l_u_e] [-vv _v_a_r_=_v_a_l_u_e] [-ff _p_r_o_g_r_a_m_-_f_i_l_e] [--] [file
...]
DDEESSCCRRIIPPTTIIOONN
mmaawwkk is an interpreter for the AWK Programming Language. The AWK lan-
guage is useful for manipulation of data files, text retrieval and pro-
cessing, and for prototyping and experimenting with algorithms. mmaawwkk
is a _n_e_w _a_w_k meaning it implements the AWK language as defined in Aho,
Kernighan and Weinberger, _T_h_e _A_W_K _P_r_o_g_r_a_m_m_i_n_g _L_a_n_g_u_a_g_e_, Addison-Wesley
Publishing, 1988 (hereafter referred to as the AWK book.) mmaawwkk con-
forms to the POSIX 1003.2 (draft 11.3) definition of the AWK language
which contains a few features not described in the AWK book, and mmaawwkk
provides a small number of extensions.
An AWK program is a sequence of _p_a_t_t_e_r_n _{_a_c_t_i_o_n_} pairs and function
definitions. Short programs are entered on the command line usually
enclosed in ' ' to avoid shell interpretation. Longer programs can be
read in from a file with the -f option. Data input is read from the
list of files on the command line or from standard input when the list
is empty. The input is broken into records as determined by the record
separator variable, RRSS. Initially, RRSS = "\n" and records are synony-
mous with lines. Each record is compared against each _p_a_t_t_e_r_n and if
it matches, the program text for _{_a_c_t_i_o_n_} is executed.
OOPPTTIIOONNSS
-FF _v_a_l_u_e sets the field separator, FFSS, to _v_a_l_u_e.
-ff _f_i_l_e Program text is read from _f_i_l_e instead of from the com-
mand line. Multiple --ff options are allowed.
-vv _v_a_r_=_v_a_l_u_e assigns _v_a_l_u_e to program variable _v_a_r.
-- indicates the unambiguous end of options.
The above options will be available with any POSIX compatible implemen-
tation of AWK. Implementation specific options are prefaced with --WW.
mmaawwkk provides these:
-WW dump writes an assembler like listing of the internal repre-
sentation of the program to stdout and exits 0 (on suc-
cessful compilation).
-WW exec _f_i_l_e Program text is read from _f_i_l_e and this is the last
option.
This is a useful alternative to -ff on systems that sup-
port the ##!! "magic number" convention for executable
scripts. Those implicitly pass the pathname of the
script itself as the final parameter, and expect no more
than one "-" option on the ##!! line. Because mmaawwkk can
combine multiple -WW options separated by commas, you can
use this option when an additional -WW option is needed.
-WW help prints a usage message to stderr and exits (same as
"-WW usage").
-WW interactive sets unbuffered writes to stdout and line buffered reads
from stdin. Records from stdin are lines regardless of
the value of RRSS.
-WW posix_space forces mmaawwkk not to consider '\n' to be space.
-WW random=_n_u_m calls ssrraanndd with the given parameter (and overrides the
auto-seeding behavior).
-WW sprintf=_n_u_m adjusts the size of mmaawwkk's internal sprintf buffer to
_n_u_m bytes. More than rare use of this option indicates
mmaawwkk should be recompiled.
-WW usage prints a usage message to stderr and exits (same as
"-WW help").
-WW version mmaawwkk writes its version and copyright to stdout and com-
piled limits to stderr and exits 0.
mmaawwkk accepts abbreviations for any of these options, e.g., "-WW v" and
"-WWv" both tell mmaawwkk to show its version.
mmaawwkk allows multiple --WW options to be combined by separating the
options with commas, e.g., -Wsprint=2000,posix. This is useful for
executable ##!! "magic number" invocations in which only one argument is
supported, e.g., -WWiinntteerraaccttiivvee,,eexxeecc.
TTHHEE AAWWKK LLAANNGGUUAAGGEE
11.. PPrrooggrraamm ssttrruuccttuurree
An AWK program is a sequence of _p_a_t_t_e_r_n _{_a_c_t_i_o_n_} pairs and user func-
tion definitions.
A pattern can be:
BBEEGGIINN
EENNDD
expression
expression , expression
One, but not both, of _p_a_t_t_e_r_n _{_a_c_t_i_o_n_} can be omitted. If _{_a_c_t_i_o_n_} is
omitted it is implicitly { print }. If _p_a_t_t_e_r_n is omitted, then it is
implicitly matched. BBEEGGIINN and EENNDD patterns require an action.
Statements are terminated by newlines, semi-colons or both. Groups of
statements such as actions or loop bodies are blocked via { ... } as in
C. The last statement in a block doesn't need a terminator. Blank
lines have no meaning; an empty statement is terminated with a semi-
colon. Long statements can be continued with a backslash, \. A state-
ment can be broken without a backslash after a comma, left brace, &&,
||, ddoo, eellssee, the right parenthesis of an iiff, wwhhiillee or ffoorr statement,
and the right parenthesis of a function definition. A comment starts
with # and extends to, but does not include the end of line.
The following statements control program flow inside blocks.
iiff ( _e_x_p_r ) _s_t_a_t_e_m_e_n_t
iiff ( _e_x_p_r ) _s_t_a_t_e_m_e_n_t eellssee _s_t_a_t_e_m_e_n_t
wwhhiillee ( _e_x_p_r ) _s_t_a_t_e_m_e_n_t
ddoo _s_t_a_t_e_m_e_n_t wwhhiillee ( _e_x_p_r )
ffoorr ( _o_p_t___e_x_p_r ; _o_p_t___e_x_p_r ; _o_p_t___e_x_p_r ) _s_t_a_t_e_m_e_n_t
ffoorr ( _v_a_r iinn _a_r_r_a_y ) _s_t_a_t_e_m_e_n_t
ccoonnttiinnuuee
bbrreeaakk
22.. DDaattaa ttyyppeess,, ccoonnvveerrssiioonn aanndd ccoommppaarriissoonn
There are two basic data types, numeric and string. Numeric constants
can be integer like -2, decimal like 1.08, or in scientific notation
like -1.1e4 or .28E-3. All numbers are represented internally and all
computations are done in floating point arithmetic. So for example,
the expression 0.2e2 == 20 is true and true is represented as 1.0.
String constants are enclosed in double quotes.
"This is a string with a newline at the end.\n"
Strings can be continued across a line by escaping (\) the newline.
The following escape sequences are recognized.
\\ \
\" "
\a alert, ascii 7
\b backspace, ascii 8
\t tab, ascii 9
\n newline, ascii 10
\v vertical tab, ascii 11
\f formfeed, ascii 12
\r carriage return, ascii 13
\ddd 1, 2 or 3 octal digits for ascii ddd
\xhh 1 or 2 hex digits for ascii hh
If you escape any other character \c, you get \c, i.e., mmaawwkk ignores
the escape.
There are really three basic data types; the third is _n_u_m_b_e_r _a_n_d _s_t_r_i_n_g
which has both a numeric value and a string value at the same time.
User defined variables come into existence when first referenced and
are initialized to _n_u_l_l, a number and string value which has numeric
value 0 and string value "". Non-trivial number and string typed data
come from input and are typically stored in fields. (See section 4).
The type of an expression is determined by its context and automatic
type conversion occurs if needed. For example, to evaluate the state-
ments
y = x + 2 ; z = x "hello"
The value stored in variable y will be typed numeric. If x is not
numeric, the value read from x is converted to numeric before it is
added to 2 and stored in y. The value stored in variable z will be
typed string, and the value of x will be converted to string if neces-
sary and concatenated with "hello". (Of course, the value and type
stored in x is not changed by any conversions.) A string expression is
converted to numeric using its longest numeric prefix as with aattooff(3).
A numeric expression is converted to string by replacing _e_x_p_r with
sspprriinnttff((CCOONNVVFFMMTT, _e_x_p_r), unless _e_x_p_r can be represented on the host
machine as an exact integer then it is converted to sspprriinnttff("%d",
_e_x_p_r). SSpprriinnttff(()) is an AWK built-in that duplicates the functionality
of sspprriinnttff(3), and CCOONNVVFFMMTT is a built-in variable used for internal
conversion from number to string and initialized to "%.6g". Explicit
type conversions can be forced, _e_x_p_r "" is string and _e_x_p_r+0 is
numeric.
To evaluate, _e_x_p_r1 rreell--oopp _e_x_p_r2, if both operands are numeric or number
and string then the comparison is numeric; if both operands are string
the comparison is string; if one operand is string, the non-string op-
erand is converted and the comparison is string. The result is
numeric, 1 or 0.
In boolean contexts such as, iiff ( _e_x_p_r ) _s_t_a_t_e_m_e_n_t, a string expression
evaluates true if and only if it is not the empty string ""; numeric
values if and only if not numerically zero.
33.. RReegguullaarr eexxpprreessssiioonnss
In the AWK language, records, fields and strings are often tested for
matching a _r_e_g_u_l_a_r _e_x_p_r_e_s_s_i_o_n. Regular expressions are enclosed in
slashes, and
_e_x_p_r ~ /_r/
is an AWK expression that evaluates to 1 if _e_x_p_r "matches" _r, which
means a substring of _e_x_p_r is in the set of strings defined by _r. With
no match the expression evaluates to 0; replacing ~ with the "not
match" operator, !~ , reverses the meaning. As pattern-action pairs,
/_r/ { _a_c_t_i_o_n } and $$00 ~ /_r/ { _a_c_t_i_o_n }
are the same, and for each input record that matches _r, _a_c_t_i_o_n is exe-
cuted. In fact, /_r/ is an AWK expression that is equivalent to ($$00 ~
/_r/) anywhere except when on the right side of a match operator or
passed as an argument to a built-in function that expects a regular
expression argument.
AWK uses extended regular expressions as with the --EE option of ggrreepp(1).
The regular expression metacharacters, i.e., those with special meaning
in regular expressions are
\ ^ $ . [ ] | ( ) * + ?
Regular expressions are built up from characters as follows:
_c matches any non-metacharacter _c.
\_c matches a character defined by the same escape
sequences used in string constants or the literal
character _c if \_c is not an escape sequence.
. matches any character (including newline).
^ matches the front of a string.
$ matches the back of a string.
[c1c2c3...] matches any character in the class c1c2c3... . An
interval of characters is denoted c1-c2 inside a
class [...].
[^c1c2c3...] matches any character not in the class c1c2c3...
Regular expressions are built up from other regular expressions as fol-
lows:
_r1_r2 matches _r1 followed immediately by _r2 (concatena-
tion).
_r1 | _r2 matches _r1 or _r2 (alternation).
_r* matches _r repeated zero or more times.
_r+ matches _r repeated one or more times.
_r? matches _r zero or once.
(_r) matches _r, providing grouping.
The increasing precedence of operators is alternation, concatenation
and unary (*, + or ?).
For example,
/^[_a-zA-Z][_a-zA-Z0-9]*$/ and
/^[-+]?([0-9]+\.?|\.[0-9])[0-9]*([eE][-+]?[0-9]+)?$/
are matched by AWK identifiers and AWK numeric constants respectively.
Note that "." has to be escaped to be recognized as a decimal point,
and that metacharacters are not special inside character classes.
Any expression can be used on the right hand side of the ~ or !~ opera-
tors or passed to a built-in that expects a regular expression. If
needed, it is converted to string, and then interpreted as a regular
expression. For example,
BEGIN { identifier = "[_a-zA-Z][_a-zA-Z0-9]*" }
$0 ~ "^" identifier
prints all lines that start with an AWK identifier.
mmaawwkk recognizes the empty regular expression, //, which matches the
empty string and hence is matched by any string at the front, back and
between every character. For example,
echo abc | mawk { gsub(//, "X") ; print }
XaXbXcX
44.. RReeccoorrddss aanndd ffiieellddss
Records are read in one at a time, and stored in the _f_i_e_l_d variable $$00.
The record is split into _f_i_e_l_d_s which are stored in $$11, $$22, ..., $$NNFF.
The built-in variable NNFF is set to the number of fields, and NNRR and FFNNRR
are incremented by 1. Fields above $$NNFF are set to "".
Assignment to $$00 causes the fields and NNFF to be recomputed. Assignment
to NNFF or to a field causes $$00 to be reconstructed by concatenating the
$$ii''ss separated by OOFFSS. Assignment to a field with index greater than
NNFF, increases NNFF and causes $$00 to be reconstructed.
Data input stored in fields is string, unless the entire field has
numeric form and then the type is number and string. For example,
echo 24 24E |
mawk '{ print($1>100, $1>"100", $2>100, $2>"100") }'
0 1 1 1
$$00 and $$22 are string and $$11 is number and string. The first comparison
is numeric, the second is string, the third is string (100 is converted
to "100"), and the last is string.
55.. EExxpprreessssiioonnss aanndd ooppeerraattoorrss
The expression syntax is similar to C. Primary expressions are numeric
constants, string constants, variables, fields, arrays and function
calls. The identifier for a variable, array or function can be a
sequence of letters, digits and underscores, that does not start with a
digit. Variables are not declared; they exist when first referenced
and are initialized to _n_u_l_l.
New expressions are composed with the following operators in order of
increasing precedence.
_a_s_s_i_g_n_m_e_n_t = += -= *= /= %= ^=
_c_o_n_d_i_t_i_o_n_a_l ? :
_l_o_g_i_c_a_l _o_r ||
_l_o_g_i_c_a_l _a_n_d &&
_a_r_r_a_y _m_e_m_b_e_r_s_h_i_p iinn
_m_a_t_c_h_i_n_g ~ !~
_r_e_l_a_t_i_o_n_a_l < > <= >= == !=
_c_o_n_c_a_t_e_n_a_t_i_o_n (no explicit operator)
_a_d_d _o_p_s + -
_m_u_l _o_p_s * / %
_u_n_a_r_y + -
_l_o_g_i_c_a_l _n_o_t !
_e_x_p_o_n_e_n_t_i_a_t_i_o_n ^
_i_n_c _a_n_d _d_e_c ++ -- (both post and pre)
_f_i_e_l_d $
Assignment, conditional and exponentiation associate right to left; the
other operators associate left to right. Any expression can be paren-
thesized.
66.. AArrrraayyss
Awk provides one-dimensional arrays. Array elements are expressed as
_a_r_r_a_y[_e_x_p_r]. _E_x_p_r is internally converted to string type, so, for
example, A[1] and A["1"] are the same element and the actual index is
"1". Arrays indexed by strings are called associative arrays. Ini-
tially an array is empty; elements exist when first accessed. An
expression, _e_x_p_r iinn _a_r_r_a_y evaluates to 1 if _a_r_r_a_y[_e_x_p_r] exists, else to
0.
There is a form of the ffoorr statement that loops over each index of an
array.
ffoorr ( _v_a_r iinn _a_r_r_a_y ) _s_t_a_t_e_m_e_n_t
sets _v_a_r to each index of _a_r_r_a_y and executes _s_t_a_t_e_m_e_n_t. The order that
_v_a_r transverses the indices of _a_r_r_a_y is not defined.
The statement, ddeelleettee _a_r_r_a_y[_e_x_p_r], causes _a_r_r_a_y[_e_x_p_r] not to exist.
mmaawwkk supports an extension, ddeelleettee _a_r_r_a_y, which deletes all elements of
_a_r_r_a_y.
Multidimensional arrays are synthesized with concatenation using the
built-in variable SSUUBBSSEEPP. _a_r_r_a_y[_e_x_p_r1,_e_x_p_r2] is equivalent to
_a_r_r_a_y[_e_x_p_r1 SSUUBBSSEEPP _e_x_p_r2]. Testing for a multidimensional element uses
a parenthesized index, such as
if ( (i, j) in A ) print A[i, j]
77.. BBuuiillttiinn--vvaarriiaabblleess
The following variables are built-in and initialized before program
execution.
AARRGGCC number of command line arguments.
AARRGGVV array of command line arguments, 0..ARGC-1.
CCOONNVVFFMMTT format for internal conversion of numbers to string,
initially = "%.6g".
EENNVVIIRROONN array indexed by environment variables. An environment
string, _v_a_r_=_v_a_l_u_e is stored as EENNVVIIRROONN[_v_a_r] = _v_a_l_u_e.
FFIILLEENNAAMMEE name of the current input file.
FFNNRR current record number in FFIILLEENNAAMMEE.
FFSS splits records into fields as a regular expression.
NNFF number of fields in the current record.
NNRR current record number in the total input stream.
OOFFMMTT format for printing numbers; initially = "%.6g".
OOFFSS inserted between fields on output, initially = " ".
OORRSS terminates each record on output, initially = "\n".
RRLLEENNGGTTHH length set by the last call to the built-in function,
mmaattcchh(()).
RRSS input record separator, initially = "\n".
RRSSTTAARRTT index set by the last call to mmaattcchh(()).
SSUUBBSSEEPP used to build multiple array subscripts, initially =
"\034".
88.. BBuuiilltt--iinn ffuunnccttiioonnss
String functions
gsub(_r_,_s_,_t) gsub(_r_,_s)
Global substitution, every match of regular expression _r in
variable _t is replaced by string _s. The number of replace-
ments is returned. If _t is omitted, $$00 is used. An & in
the replacement string _s is replaced by the matched sub-
string of _t. \& and \\ put literal & and \, respectively,
in the replacement string.
index(_s_,_t)
If _t is a substring of _s, then the position where _t starts
is returned, else 0 is returned. The first character of _s
is in position 1.
length(_s)
Returns the length of string or array. _s.
match(_s_,_r)
Returns the index of the first longest match of regular
expression _r in string _s. Returns 0 if no match. As a
side effect, RRSSTTAARRTT is set to the return value. RRLLEENNGGTTHH is
set to the length of the match or -1 if no match. If the
empty string is matched, RRLLEENNGGTTHH is set to 0, and 1 is
returned if the match is at the front, and length(_s)+1 is
returned if the match is at the back.
split(_s_,_A_,_r) split(_s_,_A)
String _s is split into fields by regular expression _r and
the fields are loaded into array _A. The number of fields
is returned. See section 11 below for more detail. If _r
is omitted, FFSS is used.
sprintf(_f_o_r_m_a_t_,_e_x_p_r_-_l_i_s_t)
Returns a string constructed from _e_x_p_r_-_l_i_s_t according to
_f_o_r_m_a_t. See the description of printf() below.
sub(_r_,_s_,_t) sub(_r_,_s)
Single substitution, same as gsub() except at most one sub-
stitution.
substr(_s_,_i_,_n) substr(_s_,_i)
Returns the substring of string _s, starting at index _i, of
length _n. If _n is omitted, the suffix of _s, starting at _i
is returned.
tolower(_s)
Returns a copy of _s with all upper case characters con-
verted to lower case.
toupper(_s)
Returns a copy of _s with all lower case characters con-
verted to upper case.
Time functions
These are available on systems which support the corresponding C mmkkttiimmee
and ssttrrffttiimmee functions:
mktime(_s_p_e_c_i_f_i_c_a_t_i_o_n)
converts a date specification to a timestamp with the same
units as ssyyssttiimmee. The date specification is a string con-
taining the components of the date as decimal integers:
YYYY
the year, e.g., 2012
MM the month of the year starting at 1
DD the day of the month starting at 1
HH hour (0-23)
MM minute (0-59)
SS seconds (0-59)
DST
tells how to treat timezone versus daylight savings
time:
positive
DST is in effect
zero (default)
DST is not in effect
negative
mktime() should (use timezone information and sys-
tem databases to) attempt to determine whether DST
is in effect at the specified time.
strftime([_f_o_r_m_a_t [, _t_i_m_e_s_t_a_m_p [, _u_t_c ]]])
formats the given timestamp using the format (passed to the
C ssttrrffttiimmee function):
+o If the _f_o_r_m_a_t parameter is missing, "%c" is used.
+o If the _t_i_m_e_s_t_a_m_p parameter is missing, the current
value from ssyyssttiimmee is used.
+o If the _u_t_c parameter is present and nonzero, the result
is in UTC. Otherwise local time is used.
systime()
returns the current time of day as the number of seconds
since the Epoch (1970-01-01 00:00:00 UTC on POSIX systems).
Arithmetic functions
atan2(_y_,_x) Arctan of _y/_x between -pi and pi.
cos(_x) Cosine function, _x in radians.
exp(_x) Exponential function.
int(_x) Returns _x truncated towards zero.
log(_x) Natural logarithm.
rand() Returns a random number between zero and one.
sin(_x) Sine function, _x in radians.
sqrt(_x) Returns square root of _x.
srand(_e_x_p_r) srand()
Seeds the random number generator, using the clock if _e_x_p_r
is omitted, and returns the value of the previous seed.
Srand(_e_x_p_r) is useful for repeating pseudo random
sequences.
Note: mmaawwkk is normally configured to seed the random number
generator from the clock at startup, making it unnecessary
to call srand(). This feature can be suppressed via condi-
tional compile, or overridden using the --WWrraannddoomm option.
99.. IInnppuutt aanndd oouuttppuutt
There are two output statements, pprriinntt and pprriinnttff.
print writes $$00 OORRSS to standard output.
print _e_x_p_r1, _e_x_p_r2, ..., _e_x_p_rn
writes _e_x_p_r1 OOFFSS _e_x_p_r2 OOFFSS ... _e_x_p_rn OORRSS to standard out-
put. Numeric expressions are converted to string with
OOFFMMTT.
printf _f_o_r_m_a_t_, _e_x_p_r_-_l_i_s_t
duplicates the printf C library function writing to stan-
dard output. The complete ANSI C format specifications are
recognized with conversions %c, %d, %e, %E, %f, %g, %G, %i,
%o, %s, %u, %x, %X and %%, and conversion qualifiers h and
l.
The argument list to print or printf can optionally be enclosed in
parentheses. Print formats numbers using OOFFMMTT or "%d" for exact inte-
gers. "%c" with a numeric argument prints the corresponding 8 bit
character, with a string argument it prints the first character of the
string. The output of print and printf can be redirected to a file or
command by appending > _f_i_l_e, >> _f_i_l_e or | _c_o_m_m_a_n_d to the end of the
print statement. Redirection opens _f_i_l_e or _c_o_m_m_a_n_d only once, subse-
quent redirections append to the already open stream. By convention,
mmaawwkk associates the filename
+o "/dev/stderr" with stderr,
+o "/dev/stdout" with stdout,
+o "-" and "/dev/stdin" with stdin.
The association with stderr is especially useful because it allows
print and printf to be redirected to stderr. These names can also be
passed to functions.
The input function ggeettlliinnee has the following variations.
getline
reads into $$00, updates the fields, NNFF, NNRR and FFNNRR.
getline < _f_i_l_e
reads into $$00 from _f_i_l_e, updates the fields and NNFF.
getline _v_a_r
reads the next record into _v_a_r, updates NNRR and FFNNRR.
getline _v_a_r < _f_i_l_e
reads the next record of _f_i_l_e into _v_a_r.
_c_o_m_m_a_n_d | getline
pipes a record from _c_o_m_m_a_n_d into $$00 and updates the fields
and NNFF.
_c_o_m_m_a_n_d | getline _v_a_r
pipes a record from _c_o_m_m_a_n_d into _v_a_r.
Getline returns 0 on end-of-file, -1 on error, otherwise 1.
Commands on the end of pipes are executed by /bin/sh.
The function cclloossee(_e_x_p_r) closes the file or pipe associated with _e_x_p_r.
Close returns 0 if _e_x_p_r is an open file, the exit status if _e_x_p_r is a
piped command, and -1 otherwise. Close is used to reread a file or
command, make sure the other end of an output pipe is finished or con-
serve file resources.
The function fffflluusshh(_e_x_p_r) flushes the output file or pipe associated
with _e_x_p_r. Fflush returns 0 if _e_x_p_r is an open output stream else -1.
Fflush without an argument flushes stdout. Fflush with an empty argu-
ment ("") flushes all open output.
The function ssyysstteemm(_e_x_p_r) uses the C runtime ssyysstteemm call to execute
_e_x_p_r and returns the corresponding wait status of the command as fol-
lows:
+o if the ssyysstteemm call failed, setting the status to -1, _m_a_w_k returns
that value.
+o if the command exited normally, _m_a_w_k returns its exit-status.
+o if the command exited due to a signal such as SSIIGGHHUUPP, _m_a_w_k returns
the signal number plus 256.
Changes made to the EENNVVIIRROONN array are not passed to commands executed
with ssyysstteemm or pipes.
1100.. UUsseerr ddeeffiinneedd ffuunnccttiioonnss
The syntax for a user defined function is
ffuunnccttiioonn name( _a_r_g_s ) { _s_t_a_t_e_m_e_n_t_s }
The function body can contain a return statement
rreettuurrnn _o_p_t___e_x_p_r
A return statement is not required. Function calls may be nested or
recursive. Functions are passed expressions by value and arrays by
reference. Extra arguments serve as local variables and are initial-
ized to _n_u_l_l. For example, csplit(_s_,_A) puts each character of _s into
array _A and returns the length of _s.
function csplit(s, A, n, i)
{
n = length(s)
for( i = 1 ; i <= n ; i++ ) A[i] = substr(s, i, 1)
return n
}
Putting extra space between passed arguments and local variables is
conventional. Functions can be referenced before they are defined, but
the function name and the '(' of the arguments must touch to avoid con-
fusion with concatenation.
A function parameter is normally a scalar value (number or string). If
there is a forward reference to a function using an array as a parame-
ter, the function's corresponding parameter will be treated as an
array.
1111.. SSpplliittttiinngg ssttrriinnggss,, rreeccoorrddss aanndd ffiilleess
Awk programs use the same algorithm to split strings into arrays with
split(), and records into fields on FFSS. mmaawwkk uses essentially the same
algorithm to split files into records on RRSS.
Split(_e_x_p_r_,_A_,_s_e_p) works as follows:
(1) If _s_e_p is omitted, it is replaced by FFSS. _S_e_p can be an expres-
sion or regular expression. If it is an expression of non-
string type, it is converted to string.
(2) If _s_e_p = " " (a single space), then <SPACE> is trimmed from the
front and back of _e_x_p_r, and _s_e_p becomes <SPACE>. mmaawwkk defines
<SPACE> as the regular expression /[ \t\n]+/. Otherwise _s_e_p is
treated as a regular expression, except that meta-characters
are ignored for a string of length 1, e.g., split(x, A, "*")
and split(x, A, /\*/) are the same.
(3) If _e_x_p_r is not string, it is converted to string. If _e_x_p_r is
then the empty string "", split() returns 0 and _A is set empty.
Otherwise, all non-overlapping, non-null and longest matches of
_s_e_p in _e_x_p_r, separate _e_x_p_r into fields which are loaded into _A.
The fields are placed in A[1], A[2], ..., A[n] and split()
returns n, the number of fields which is the number of matches
plus one. Data placed in _A that looks numeric is typed number
and string.
Splitting records into fields works the same except the pieces are
loaded into $$11, $$22,..., $$NNFF. If $$00 is empty, NNFF is set to 0 and all $$ii
to "".
mmaawwkk splits files into records by the same algorithm, but with the
slight difference that RRSS is really a terminator instead of a separa-
tor. (OORRSS is really a terminator too).
E.g., if FFSS = ":+" and $$00 = "a::b:" , then NNFF = 3 and $$11 = "a", $$22
= "b" and $$33 = "", but if "a::b:" is the contents of an input file
and RRSS = ":+", then there are two records "a" and "b".
RRSS = " " is not special.
If FFSS = "", then mmaawwkk breaks the record into individual characters,
and, similarly, split(_s_,_A_,"") places the individual characters of _s
into _A.
1122.. MMuullttii--lliinnee rreeccoorrddss
Since mmaawwkk interprets RRSS as a regular expression, multi-line records
are easy. Setting RRSS = "\n\n+", makes one or more blank lines separate
records. If FFSS = " " (the default), then single newlines, by the rules
for <SPACE> above, become space and single newlines are field separa-
tors.
For example, if
+o a file is "a b\nc\n\n",
+o RRSS = "\n\n+" and
+o FFSS = " ",
then there is one record "a b\nc" with three fields "a", "b" and
"c":
+o Changing FFSS = "\n", gives two fields "a b" and "c";
+o changing FFSS = "", gives one field identical to the record.
If you want lines with spaces or tabs to be considered blank, set RRSS =
"\n([ \t]*\n)+". For compatibility with other awks, setting RRSS = ""
has the same effect as if blank lines are stripped from the front and
back of files and then records are determined as if RRSS = "\n\n+".
POSIX requires that "\n" always separates records when RRSS = "" regard-
less of the value of FFSS. mmaawwkk does not support this convention,
because defining "\n" as <SPACE> makes it unnecessary.
Most of the time when you change RRSS for multi-line records, you will
also want to change OORRSS to "\n\n" so the record spacing is preserved on
output.
1133.. PPrrooggrraamm eexxeeccuuttiioonn
This section describes the order of program execution. First AARRGGCC is
set to the total number of command line arguments passed to the execu-
tion phase of the program. AARRGGVV[[00]] is set the name of the AWK inter-
preter and AARRGGVV[[11]] ... AARRGGVV[[AARRGGCC--11]] holds the remaining command line
arguments exclusive of options and program source. For example with
mawk -f prog v=1 A t=hello B
AARRGGCC = 5 with AARRGGVV[[00]] = "mawk", AARRGGVV[[11]] = "v=1", AARRGGVV[[22]] = "A", AARRGGVV[[33]]
= "t=hello" and AARRGGVV[[44]] = "B".
Next, each BBEEGGIINN block is executed in order. If the program consists
entirely of BBEEGGIINN blocks, then execution terminates, else an input
stream is opened and execution continues. If AARRGGCC equals 1, the input
stream is set to stdin, else the command line arguments AARRGGVV[[11]] ...
AARRGGVV[[AARRGGCC--11]] are examined for a file argument.
The command line arguments divide into three sets: file arguments,
assignment arguments and empty strings "". An assignment has the form
_v_a_r=_s_t_r_i_n_g. When an AARRGGVV[[ii]] is examined as a possible file argument,
if it is empty it is skipped; if it is an assignment argument, the
assignment to _v_a_r takes place and ii skips to the next argument; else
AARRGGVV[[ii]] is opened for input. If it fails to open, execution terminates
with exit code 2. If no command line argument is a file argument, then
input comes from stdin. Getline in a BBEEGGIINN action opens input. "-" as
a file argument denotes stdin.
Once an input stream is open, each input record is tested against each
_p_a_t_t_e_r_n, and if it matches, the associated _a_c_t_i_o_n is executed. An
expression pattern matches if it is boolean true (see the end of sec-
tion 2). A BBEEGGIINN pattern matches before any input has been read, and
an EENNDD pattern matches after all input has been read. A range pattern,
_e_x_p_r1,_e_x_p_r2 , matches every record between the match of _e_x_p_r1 and the
match _e_x_p_r2 inclusively.
When end of file occurs on the input stream, the remaining command line
arguments are examined for a file argument, and if there is one it is
opened, else the EENNDD _p_a_t_t_e_r_n is considered matched and all EENNDD _a_c_t_i_o_n_s
are executed.
In the example, the assignment v=1 takes place after the BBEEGGIINN _a_c_t_i_o_n_s
are executed, and the data placed in v is typed number and string.
Input is then read from file A. On end of file A, t is set to the
string "hello", and B is opened for input. On end of file B, the EENNDD
_a_c_t_i_o_n_s are executed.
Program flow at the _p_a_t_t_e_r_n _{_a_c_t_i_o_n_} level can be changed with the
nneexxtt
nneexxttffiillee
eexxiitt _o_p_t___e_x_p_r
statements:
+o A nneexxtt statement causes the next input record to be read and pat-
tern testing to restart with the first _p_a_t_t_e_r_n _{_a_c_t_i_o_n_} pair in the
program.
+o A nneexxttffiillee statement tells mmaawwkk to stop processing the current
input file. It then updates FILENAME to the next file listed on
the command line, and resets FNR to 1.
+o An eexxiitt statement causes immediate execution of the EENNDD actions or
program termination if there are none or if the eexxiitt occurs in an
EENNDD action. The _o_p_t___e_x_p_r sets the exit value of the program unless
overridden by a later eexxiitt or subsequent error.
EEXXAAMMPPLLEESS
1. emulate cat.
{ print }
2. emulate wc.
{ chars += length($0) + 1 # add one for the \n
words += NF
}
END{ print NR, words, chars }
3. count the number of unique "real words".
BEGIN { FS = "[^A-Za-z]+" }
{ for(i = 1 ; i <= NF ; i++) word[$i] = "" }
END { delete word[""]
for ( i in word ) cnt++
print cnt
}
4. sum the second field of every record based on the first field.
$1 ~ /credit|gain/ { sum += $2 }
$1 ~ /debit|loss/ { sum -= $2 }
END { print sum }
5. sort a file, comparing as string
{ line[NR] = $0 "" } # make sure of comparison type
# in case some lines look numeric
END { isort(line, NR)
for(i = 1 ; i <= NR ; i++) print line[i]
}
#insertion sort of A[1..n]
function isort( A, n, i, j, hold)
{
for( i = 2 ; i <= n ; i++)
{
hold = A[j = i]
while ( A[j-1] > hold )
{ j-- ; A[j+1] = A[j] }
A[j] = hold
}
# sentinel A[0] = "" will be created if needed
}
CCOOMMPPAATTIIBBIILLIITTYY IISSSSUUEESS
MMAAWWKK 11..33..33 vveerrssuuss PPOOSSIIXX 11000033..22 DDrraafftt 1111..33
The POSIX 1003.2(draft 11.3) definition of the AWK language is AWK as
described in the AWK book with a few extensions that appeared in Sys-
temVR4 nawk. The extensions are:
+o New functions: toupper() and tolower().
+o New variables: ENVIRON[] and CONVFMT.
+o ANSI C conversion specifications for printf() and sprintf().
+o New command options: -v var=value, multiple -f options and
implementation options as arguments to -W.
+o For systems (MS-DOS or Windows) which provide a _s_e_t_m_o_d_e func-
tion, an environment variable MAWKBINMODE and a built-in vari-
able BINMODE. The bits of the BINMODE value tell _m_a_w_k how to
modify the RRSS and OORRSS variables:
0 set standard input to binary mode, and if BIT-2 is unset, set
RRSS to "\r\n" (CR/LF) rather than "\n" (LF).
1 set standard output to binary mode, and if BIT-2 is unset,
set OORRSS to "\r\n" (CR/LF) rather than "\n" (LF).
2 suppress the assignment to RRSS and OORRSS of CR/LF, making it
possible to run scripts and generate output compatible with
Unix line-endings.
POSIX AWK is oriented to operate on files a line at a time. RRSS can be
changed from "\n" to another single character, but it is hard to find
any use for this -- there are no examples in the AWK book. By conven-
tion, RRSS = "", makes one or more blank lines separate records, allowing
multi-line records. When RRSS = "", "\n" is always a field separator
regardless of the value in FFSS.
mmaawwkk, on the other hand, allows RRSS to be a regular expression. When
"\n" appears in records, it is treated as space, and FFSS always deter-
mines fields.
Removing the line at a time paradigm can make some programs simpler and
can often improve performance. For example, redoing example 3 from
above,
BEGIN { RS = "[^A-Za-z]+" }
{ word[ $0 ] = "" }
END { delete word[ "" ]
for( i in word ) cnt++
print cnt
}
counts the number of unique words by making each word a record. On
moderate size files, mmaawwkk executes twice as fast, because of the sim-
plified inner loop.
The following program replaces each comment by a single space in a C
program file,
BEGIN {
RS = "/\*([^*]|\*+[^/*])*\*+/"
# comment is record separator
ORS = " "
getline hold
}
{ print hold ; hold = $0 }
END { printf "%s" , hold }
Buffering one record is needed to avoid terminating the last record
with a space.
With mmaawwkk, the following are all equivalent,
x ~ /a\+b/ x ~ "a\+b" x ~ "a\\+b"
The strings get scanned twice, once as string and once as regular
expression. On the string scan, mmaawwkk ignores the escape on non-escape
characters while the AWK book advocates _\_c be recognized as _c which
necessitates the double escaping of meta-characters in strings. POSIX
explicitly declines to define the behavior which passively forces pro-
grams that must run under a variety of awks to use the more portable
but less readable, double escape.
POSIX AWK does not recognize "/dev/std{in,out,err}". Some systems pro-
vide an actual device for this, allowing AWKs which do not implement
the feature directly to support it.
POSIX AWK does not recognize \x hex escape sequences in strings.
Unlike ANSI C, mmaawwkk limits the number of digits that follows \x to two
as the current implementation only supports 8 bit characters. The
built-in fffflluusshh first appeared in a recent (1993) AT&T awk released to
netlib, and is not part of the POSIX standard. Aggregate deletion with
ddeelleettee _a_r_r_a_y is not part of the POSIX standard.
POSIX explicitly leaves the behavior of FFSS = "" undefined, and mentions
splitting the record into characters as a possible interpretation, but
currently this use is not portable across implementations.
RRaannddoomm nnuummbbeerrss
POSIX does not prescribe a method for initializing random numbers at
startup.
In practice, most implementations do nothing special, which makes ssrraanndd
and rraanndd follow the C runtime library, making the initial seed value 1.
Some implementations (Solaris XPG4 and Tru64) return 0 from the first
call to ssrraanndd, although the results from rraanndd behave as if the initial
seed is 1. Other implementations return 1.
While mmaawwkk can call ssrraanndd at startup with no parameter (initializing
random numbers from the clock), this feature may be suppressed using
conditional compilation.
EExxtteennssiioonnss aaddddeedd ffoorr ccoommppaattiibbiilliittyy ffoorr GGAAWWKK aanndd BBWWKK
NNeexxttffiillee is a ggaawwkk extension (also implemented by BWK awk), is not yet
part of the POSIX standard (as of October 2012), although it has been
accepted for the next revision of the standard.
MMkkttiimmee, ssttrrffttiimmee and ssyyssttiimmee are ggaawwkk extensions.
The "/dev/stdin" feature was added to mmaawwkk after 1.3.4, for compatibil-
ity with ggaawwkk and BWK awk. The corresponding "-" (alias for
/dev/stdin) was present in mawk 1.3.3.
SSuubbttllee DDiiffffeerreenncceess nnoott iinn PPOOSSIIXX oorr tthhee AAWWKK BBooookk
Finally, here is how mmaawwkk handles exceptional cases not discussed in
the AWK book or the POSIX draft. It is unsafe to assume consistency
across awks and safe to skip to the next section.
+o substr(s, i, n) returns the characters of s in the intersection
of the closed interval [1, length(s)] and the half-open interval
[i, i+n). When this intersection is empty, the empty string is
returned; so substr("ABC", 1, 0) = "" and substr("ABC", -4, 6) =
"A".
+o Every string, including the empty string, matches the empty
string at the front so, s ~ // and s ~ "", are always 1 as is
match(s, //) and match(s, ""). The last two set RRLLEENNGGTTHH to 0.
+o index(s, t) is always the same as match(s, t1) where t1 is the
same as t with metacharacters escaped. Hence consistency with
match requires that index(s, "") always returns 1. Also the
condition, index(s,t) != 0 if and only t is a substring of s,
requires index("","") = 1.
+o If getline encounters end of file, getline var, leaves var
unchanged. Similarly, on entry to the EENNDD actions, $$00, the
fields and NNFF have their value unaltered from the last record.
EENNVVIIRROONNMMEENNTT VVAARRIIAABBLLEESS
MMaawwkk recognizes these variables:
MAWKBINMODE
(see CCOOMMPPAATTIIBBIILLIITTYY IISSSSUUEESS)
MAWK_LONG_OPTIONS
If this is set, mmaawwkk uses its value to decide what to do with
GNU-style long options:
allow MMaawwkk allows the option to be checked against the (small)
set of long options it recognizes.
error MMaawwkk prints an error message and exits. This is the
default.
ignore MMaawwkk ignores the option.
warn Print an warning message and otherwise ignore the
option.
If the variable is unset, mmaawwkk prints an error message and exits.
WHINY_USERS
This is an undocumented ggaawwkk feature. It tells mmaawwkk to sort
array indices before it starts to iterate over the elements of an
array.
SSEEEE AALLSSOO
ggrreepp(1)
Aho, Kernighan and Weinberger, _T_h_e _A_W_K _P_r_o_g_r_a_m_m_i_n_g _L_a_n_g_u_a_g_e, Addison-
Wesley Publishing, 1988, (the AWK book), defines the language, opening
with a tutorial and advancing to many interesting programs that delve
into issues of software design and analysis relevant to programming in
any language.
_T_h_e _G_A_W_K _M_a_n_u_a_l, The Free Software Foundation, 1991, is a tutorial and
language reference that does not attempt the depth of the AWK book and
assumes the reader may be a novice programmer. The section on AWK
arrays is excellent. It also discusses POSIX requirements for AWK.
BBUUGGSS
mmaawwkk implements printf() and sprintf() using the C library functions,
printf and sprintf, so full ANSI compatibility requires an ANSI C
library. In practice this means the h conversion qualifier may not be
available. Also mmaawwkk inherits any bugs or limitations of the library
functions.
Implementors of the AWK language have shown a consistent lack of imagi-
nation when naming their programs.
AAUUTTHHOORR
Mike Brennan (brennan@whidbey.com).
Thomas E. Dickey <dickey@invisible-island.net>.
Version 1.3.4 2019-12-31 MAWK(1)
|