home *** CD-ROM | disk | FTP | other *** search
/ Power Programming / powerprogramming1994.iso / progtool / cmplngmg / cl_jun89.arc / AWK210.ARC / AWK.MAN < prev    next >
Text File  |  1988-11-15  |  19KB  |  479 lines

  1.  
  2. AWK                                                                    AWK
  3.  
  4.  
  5. NAME
  6.  
  7.         awk - pattern scanning and processing language
  8.  
  9.  
  10. SYNOPSIS
  11.  
  12.         awk [-ffile] [-Fstr] [program] [var=text] [file] ...
  13.  
  14.  
  15. DESCRIPTION
  16.  
  17. Awk scans each input file for lines that match any of a set of patterns 
  18. specified in the program.  With each pattern in the program there can be an 
  19. associated action that will be performed when a line of a file matches the 
  20. pattern.
  21.  
  22. The AWK program may be specified as a file with the -f option as:
  23.  
  24.         -ffilename.ext
  25.         -f filename.ext
  26.  
  27. in which case the AWK program is read from the named file.  If the file does 
  28. not exist then an error message will be printed. 
  29.  
  30. The AWK program may also be specified as a single argument as:
  31.  
  32.         filename.ext
  33.         filename[.awk]
  34.  
  35. or as a valid AWK program:
  36.  
  37.         { for (i in ARGV) printf ("%d: %s\n", i, ARGV[i]) }
  38.  
  39. AWK will first try to open the first argument as a file, it it can't open a 
  40. file, it then adds the extension ".awk" and tries again to open a file, 
  41. finally AWK will attempt to read the argument directly as an AWK program. 
  42.  
  43. If the filename is a minus sign (-) then the AWK program is read from the 
  44. standard input.  The program may then be terminated with either a ctrl-Z or
  45. a period (.) on a line by itself.  The second method is useful for entering 
  46. an AWK program followed by the data for the program.  If no program file is 
  47. specified then the program is read from standard input.
  48.  
  49. If the -f option is selected the full path/name/extension must be specified.  
  50. If only the filename is specified AWK will first attempt to open the named 
  51. file, then the file with the extension ".AWK", finally AWK will attempt to 
  52. parse the parameter as a program.
  53.  
  54. Files are read in order, the file name '-' means standard input.  Each line 
  55. is matched against the pattern portion of every pattern-action statement; 
  56. the associated action is performed for each matched pattern.
  57.  
  58. If a file name has the form variable=value, program variables may be changed 
  59. before a file is read.  The assignment takes place when the argument would be 
  60. treated as the next file to read. 
  61.  
  62.         awk "{ print code, NR, $$0 }" code=10 file1 code=75 file2
  63.  
  64. No assignment will happen before a BEGIN block, however an assignment after 
  65. the last file will occur before any END block unless an exit was performed.
  66.  
  67. If no files are specified the input is read from standard input.
  68.  
  69. An input line is made up of fields separated by the field separator FS.  
  70. The fields are denoted by $1, $2 ...; $0 denotes the entire line:
  71.  
  72.         $0 = "now is the time"
  73.  
  74.         $1 = "now"      $2 = "is"
  75.         $3 = "the"      $4 = "time"
  76.  
  77. with the default FS (white space).  If the field separator is set to comma (,)
  78. with "-F," on the command line then the fields might be:
  79.  
  80.         $0 = "a, b,c,, ,"
  81.  
  82.         $1 = "a"        $2 = " b"       $3 = "c"
  83.         $4 = ""         $5 = " "        $6 = ""
  84.  
  85. A pattern-action statement has the form:
  86.  
  87.         pattern { action }
  88.  
  89. A missing { action } has the same effect as { print $0 }, a missing pattern 
  90. always matches. 
  91.  
  92. Pattern-Actions are separated by semicolons or newlines.  A statement may be 
  93. continued on the next line by putting a backslash (\) at the end of the line. 
  94.  
  95.         { words += NF }; END { print words }
  96.  
  97. A pattern is a test that is performed on each input line.  If the pattern 
  98. matches the input line then the corresponding action is performed.
  99.  
  100. Patterns come in several forms:
  101.  
  102. Form            Example         Meaning
  103.  
  104. BEGIN           BEGIN {N=1}     initialize N before input is read
  105. END             END {print N}   print N after all input is read
  106. function        function x(y)   define a function called x
  107. text match      /stop/          line contains the string "stop"
  108. expression      $1 == 3         first field is the number 3
  109. compound        /x/ && NF > 2   more that two fields and contain "x"
  110. range           NR==10,NR==20   records ten through twenty inclusive
  111.  
  112. BEGIN and END patterns are special patterns that match before any files are 
  113. read and after all files have been read respectivly.  There may be multiple 
  114. occurances of these patterns and the associated actions are executed in the 
  115. order that they occur.  
  116.  
  117. If there is only a series of BEGIN blocks in the awk program and no other 
  118. pattern/action blocks except function declarations then no input files are 
  119. read.  If only END blocks are defined then all the files are read and NR will 
  120. be set to the number of records in all the files.
  121.  
  122.         BEGIN { page = 5 }
  123.  
  124. A function pattern is never matched and serves to declare a user defined 
  125. function.  You can declare a function with more parameters than are 
  126. passed as arguments so that the extra parameters can act as local 
  127. variables.  
  128.  
  129.         function show(a, i) { for (i in a) print a[i] }
  130.  
  131. A regular expression by itself is matched against the input record ($0). That 
  132. is "/abc/" is equivalent to "$0 ~ /abc/". 
  133.  
  134. Any expression will match if it evaluates to != 0 or !="".  Also any logical 
  135. combination of expressions and regular expressions may be used as a pattern.
  136.  
  137.         FILENAME != oldname && FILENAME != "skip"
  138.  
  139. The last special pattern is two patterns separated by a comma.  This pattern 
  140. specifies a range of records that match the pattern.  The pattern starts to 
  141. match when the first pattern matches and stops matching when the second 
  142. pattern matches.  If they both match on the same input record then only that 
  143. record will match the pattern.
  144.  
  145.         /AUTHOR/,/NOTES/
  146.  
  147. An action is a sequence of statements that are performed when a pattern 
  148. matches.  
  149.  
  150. A statement can be one of the following: 
  151.  
  152.         { STATEMENT_LIST }
  153.         EXPRESSION
  154.         print EXPRESSION-LIST
  155.         printf FORMAT, EXPRESSION_LIST
  156.         if ( EXPRESSION ) STATEMENT [ else STATEMENT ]
  157.         for ( VARIABLE in ARRAY ) STATEMENT
  158.         for ( EXPRESSION; EXPRESSION; EXPRESSION) STATEMENT
  159.         while ( EXPRESSION ) STATEMENT
  160.         do STATEMENT while ( EXPRESSION )
  161.         break
  162.         continue
  163.         next
  164.         exit [ EXPRESSION ]
  165.         return [EXPRESSION ]
  166.  
  167. A STATEMENT_LIST is a list of statements separated by newlines or semicolons.
  168. As with pattern-actions statements may be extended over more than one line 
  169. with backslash (\). 
  170.         {
  171.             print "value:", i, \
  172.                   "number:", j
  173.             i = i + $3; j++
  174.         }
  175.  
  176. Expressions take on string or numeric values depending on the operators.
  177. There is only one string operator, concatenation, indicated by adjacent 
  178. expressions.  The following are the operators in order of increasing 
  179. precedence:
  180.  
  181. Operation           Operator      Example     Meaning
  182.  
  183. assignment          = *= /= %=    x += 2      two is added to x
  184.                     += -= ^=
  185. conditional         ?:            x?y:z       if x then y else z
  186. logical OR          ||            x||y        if (x) 1 else if (y) 1 else 0
  187. logical AND         &&            x&&y        if (x) if (y) 1 else 0 else 0
  188. array membership    in            x in y      if (exists(y[x])) 1 else 0
  189. matching            ~ !~          $1~/x/      if ($1 contains x) 1 else 0
  190. relational          == != >       x==y        if (x equals y) 1 else 0
  191.                     <= >= <
  192. concatenation                     "x" "y"     a new string "xy"
  193. add, subtract       +  -          x+y         sum of x and y
  194. mul, div, mod       * / %         x*y         product of x and y
  195. unary plus minus    + -           -x          negative of x
  196. logical not         !             !x          if (x is 0 or null) 1 else 0
  197. exponentiation      ^             x^y         x to the yth power
  198. inc, dec            ++ --         x++         x then add 1 to x
  199. field               $             $3          the 3rd field
  200. grouping            ()            ($1)++      increment the 1st field
  201.  
  202. Variables may be scalars, array elements (denoted x[i]) or fields (denoted 
  203. $expression).  Variable names begin with a letter or underscore and may 
  204. contain any number of letters, digits, or underscores.
  205.  
  206. Array subscripts may be any string.  Multi dimensional arrays are simulated in 
  207. AWK by concatenating the individual indexes with the subscript separator 
  208. between them.  So array[1,1] is equivalent to array[1 SUBSEP 1]. 
  209.  
  210. Variables are initialized to both zero and the null string.  Fields and the 
  211. command line arguments will be both string and numeric if they can be 
  212. completely represented as numbers.  The range for numbers is 1E-306..1E306.
  213.  
  214. Comparison will be numeric if both operands are numeric otherwise a string 
  215. comparison will be made.  Operands will be coerced to strings if necessary.  
  216. Uninitialized variables will compare as numeric if the other operand is 
  217. numeric or uninitialized.  Eg. 2 > "10" and 2 < 10.
  218.  
  219. There are a number of built in variables they are:
  220.  
  221. Variable        Meaning                                         Default
  222.  
  223. ARGC            number of command line arguments                   -
  224. ARGV            array of command line arguments                    -
  225. FILENAME        name of current input file                         -
  226. FNR             record number in current file                      -
  227. FS              controls the input field separator                " "
  228. NF              number of fields in current record                 -
  229. NR              number of records read so far                      -
  230. OFMT            output format for records                        "%.6g"
  231. OFS             output field separator                            " "
  232. ORS             output record separator                           "\n"
  233. RLENGTH         length of string matched by match function         -
  234. RS              controls input record separator                   "\n"
  235. RSTART          start of string match by match function            -
  236. SUBSEP          subscript separator                              "\034"
  237.  
  238.  
  239. ARGC and ARGV are the count and values of the command line arguments. ARGV[0] 
  240. is the full path/name of AWK.EXE, and the rest are all the command line 
  241. arguments except the "-F", "-f" and program arguments which are used by AWK.
  242.  
  243. The field separator is a string that is interpreted as a regular expression.
  244. A single space has a special meaning and is changed to /[ \t]+/, any leading 
  245. spaces or tabs are removed.  A BEGIN action may be used to set the separator 
  246. or it may be set by using the -F command line option. 
  247.  
  248.         BEGIN { FS = "," }      sets FS to a single comma
  249.         "-F[ ]"                 sets FS to a single space
  250.  
  251. The record separator is a string that is interpreted as a regular expression. 
  252. If the record separator RS is set to the null string then multi line records 
  253. may be read.  In this case the record separator is an empty line. 
  254.  
  255. There are a number of built in functions:
  256.  
  257. Function            Value returned
  258.  
  259. atan2(x, y)         arctangent of x/y           in the range -pi to pi
  260. cos(x)              cosine of x                 x in radians
  261. exp(x)              exponentiation of x         (e ^ x)
  262. gsub(r, s)          number of substitutions     substitute s for all r in $0
  263. gsub(r, s, t)       number of substitutions     substitute s for all r in t     
  264. index(s)            position of s in $0         0 if not in $0
  265. index(s, t)         position of t in s          0 if not in s
  266. length(s)           number of characters in s
  267. log(x)              natural log of x
  268. match(s, r)         position of r in s or 0     sets RSTART and RLENGTH
  269. rand()              random number               0 <= rand < 1
  270. sin(x)              sine of x                   x in radians
  271. split(s, a)         number of fields            split s into a on FS 
  272. split(s, a, fs)     number of fields            split s into a on fs
  273. sprintf(f, e, ...)  formatted string
  274. sqrt(x)             square root of x
  275. sub(r, s)           number of substitutions     substitute s for one r in $0
  276. sub(r, s, t)        number of substitutions     substitute s for one r in t
  277. substr(s, p)        substring of s from p to end
  278. substr(s, p, n)     substring of s from p of length n
  279. system(s)           exit status                 execute command s
  280.  
  281. The numeric procedure srand(x) sets a new seed for the random number 
  282. generator.  srand() sets the seed from the system time.
  283.  
  284. The regular expression arguments of sub, gsub, and match may be either regular 
  285. expressions delimited by slashes or any expression.  The expression is coerced 
  286. to a string and the resulting string is converted into a regular expression.  
  287. This coersion and conversion occurs every time the procedure is called so the 
  288. regular expression form will always be faster. 
  289.  
  290. The print and printf statements come in several forms:
  291.  
  292. Form                            Meaning
  293.  
  294. print                           print $0 on standard output
  295. print expression, ...           prints expressions separated by OFS
  296. print(expression, ...)  
  297. printf format, expression, ...
  298. printf(format, expression, ...)
  299. print >"file"                   print $0 on file "file"
  300. print >>"file"                  append $0 to file "file"
  301. printf(format, ...) >"file"
  302. printf(format, ...) >>"file"
  303.  
  304. close("file")                   close the file "file"
  305.  
  306. The print statement prints its arguments on the standard output, or the 
  307. specified file, separated by the current output field separator, and 
  308. terminated by the output record separator.  The printf statement formats its 
  309. expression-list according to the format.  The file is only opened once unless 
  310. it is closed between executions of the print statement.  A file than is open 
  311. for output must be closed if it is to be used for input.  The "file" argument 
  312. may any expression that evaluates to a DOS file name. 
  313.  
  314. There is one function that is used for input.  It has several forms
  315.  
  316. Form                            Meaning
  317.  
  318. getline                         read the next record into $0
  319. getline s                       read the next record into s
  320. getline <"file"                 read a record from file "file" into $0
  321. getline s <"file"               read a record from file "file" into s
  322.  
  323. getline returns -1 if there is an error (such as non existent file), 0 on 
  324. end of file and 1 otherwise.  The pipe form mentioned in the book is not 
  325. implemented in this version.
  326.  
  327. The for ( i in a ) statement assigns to i the indexes of a for all elements 
  328. in a.  The while (), do while (), and for (;;) statement is as in C as are 
  329. break and continue. 
  330.  
  331. The next statements stops processing the pattern action statements and reads 
  332. in the next record.  An exit will cause the END actions to be performed or if 
  333. encountered in an END action will cause termination of the program.  The 
  334. optional expression is returned as the exit status unless overridden by a 
  335. further exit statement in an END action. 
  336.  
  337. The return statement may be used only in function declarations.  It may have 
  338. an option value to return as the value of the function.  The value of a 
  339. function defaults to zero/null (0/""). 
  340.  
  341. REGULAR EXPRESSIONS
  342.  
  343. A \ followed by a single character matches that character.
  344.  
  345. The ^ matches the beginning of the string.
  346.  
  347. The $ matches the end of the string.
  348.  
  349. A . matches any character.
  350.  
  351. A single character with no special meaning matches that character.
  352.  
  353. A string enclosed in brackets [] matches any single character in that string.  
  354. Ranges of ASCII character codes may be abbreviated as 'a-z0-9'.  A left 
  355. bracket ] may occur only as the first character of the string.  A literal - 
  356. must be placed where it can't be mistaken as a range indicator. If the first 
  357. character is the caret ^ then any character not in the string will match. 
  358.  
  359. A regular expression followed by * matches a sequence of 0 or more
  360. matches of the regular expression.
  361.  
  362. A regular expression followed by + matches a sequence of 1 or more
  363. matches of the regular expression.
  364.  
  365. A regular expression followed by ? matches a sequence of 0 or 1
  366. matches of the regular expression.
  367.  
  368. Two adjacent (concatenated) regular expressions match a match of the first 
  369. followed by a match of the second. 
  370.  
  371. Two regular expressions separated by | match either a match for the
  372. first or a match for the second.
  373.  
  374. A regular expression enclosed in parentheses matches a match for the
  375. regular expression.
  376.  
  377. The order of precedence of operators at the same parenthesis level is 
  378. [] then *+? then concatenation then |.
  379.  
  380.  
  381. PRINTF FORMAT
  382.  
  383. Any character except % and \ is printed as that character.
  384.  
  385. A \ followed by up to three octal digits is the ASCII character
  386. represented by that number.
  387.  
  388. A \ followed by n, t, r, b, f, v, or p is newline, tab, return, backspace, 
  389. form feed, vertical tab, or escape. 
  390.  
  391. %[-][number][.number][l][c|d|E|e|F|f|G|g|o|s|X|x|%] prints an expression:
  392.  
  393. The optional leading - means left justified in the field
  394. The optional first number is the field width
  395. The optional . and second number is the precision
  396. The optional l denotes a long expression
  397. The final character denotes the form of the expression
  398.  
  399.         c character
  400.         d decimal
  401.         e exponential floating point
  402.         f fixed, or exponential floating point
  403.         g decimal, fixed, or exponential floating point
  404.         o octal
  405.         s string
  406.         x hexadecimal 
  407.  
  408. An upper case E, F, or G denotes use of upper case E in exponential format.
  409. An upper case X denotest hexadecimal in upper case.
  410. Two percent characters (%%) will print as one.
  411.  
  412. A format will match the regular expression:
  413.  
  414.         /[^%]*(%(%|(-?([0-9]+)?(\.[0-9]+)?l?[cdEeFfGgosXx]))[^%]*)*/
  415.  
  416. EXAMPLES
  417.  
  418. Print lines longer than 72 characters (missing action is print):
  419.  
  420.         length($0) > 72
  421.  
  422. Print first two fields in opposite order (missing pattern is always match):
  423.  
  424.         { print $2, $1 }
  425.  
  426. Add up first column, print sum and average:
  427.  
  428.                 { s = s + $1 }
  429.         END     { print "sum is", s, "average is", s/NR }
  430.  
  431. Print fields in reverse order:
  432.  
  433.         { for (i = NF; i > 0; --i ) print $i }
  434.  
  435. Print all lines between start/stop pairs:
  436.  
  437.         /start/,/stop/
  438.  
  439. Print all lines whose first field is different from previous one:
  440.  
  441.         $1 != prev { print; prev = $1 }
  442.  
  443. Convert date from MM/DD/YY to metric (YYMMDD):
  444.  
  445.         { n = split(date, a, "/"); date = a[3] a[1] a[2] }
  446.  
  447. Copy a C program and insert include files:
  448.  
  449.         $1 == "#include" && $2 ~ /^"/ {
  450.                 gsub(/"/, "", $2);
  451.                 while (getline <$2 > 0) print
  452.                 next
  453.         }
  454.         { print }
  455.  
  456. AUTHOR
  457.  
  458. Rob Duff,  Vancouver, B.C.
  459.  
  460. SEE ALSO
  461.  
  462. M. E. Lesk and E. Schmidt,
  463.         LEX - Lexical Analyser Generator
  464.  
  465. A. V Aho, B. W Kernighan, P. J. Weinberger,
  466.         Awk - a pattern scanning and processing language
  467.  
  468. A. V Aho, B. W Kernighan, P. J. Weinberger,
  469.         The AWK Programming Language 
  470.         Addison-Wesley 1988   ISBN 0-201-07981-X
  471.  
  472.  
  473. NOTES
  474.  
  475. There are no explicit conversions between numbers and strings.  To force an 
  476. expression to b treated as a number add 0 to it; to force it to be a string 
  477. concatenate "" to it.  Array indices are strings and may have the same 
  478. numerical value but will index different values (eg "01" vs "1").  
  479.