home *** CD-ROM | disk | FTP | other *** search
/ The Datafile PD-CD 4 / DATAFILE_PDCD4.iso / unix / riscbsd / datafile / usd / 19_awk / awk_txt
Encoding:
Text File  |  1996-10-12  |  26.5 KB  |  991 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.      Awk -- A Pattern Scanning and Processing Language
  11.                       (Second Edition)
  12.  
  13.                        Alfred V. Aho
  14.                      Brian W. Kernighan
  15.                     Peter J. Weinberger
  16.  
  17.  
  18.                           ABSTRACT
  19.  
  20.  
  21.           Awk  is  a  programming  language whose basic
  22.      operation is to search a set  of  files  for  pat-
  23.      terns, and to perform specified actions upon lines
  24.      or fields of  lines  which  contain  instances  of
  25.      those  patterns.  Awk makes certain data selection
  26.      and transformation operations easy to express; for
  27.      example, the awk program
  28.  
  29.                         length > 72
  30.  
  31.      prints  all  input  lines  whose length exceeds 72
  32.      characters; the program
  33.  
  34.                         NF % 2 == 0
  35.  
  36.      prints all lines with an even  number  of  fields;
  37.      and the program
  38.  
  39.                   { $1 = log($1); print }
  40.  
  41.      replaces the first field of each line by its loga-
  42.      rithm.
  43.  
  44.           Awk patterns may  include  arbitrary  boolean
  45.      combinations  of  regular expressions and of rela-
  46.      tional  operators  on  strings,  numbers,  fields,
  47.      variables,   and   array  elements.   Actions  may
  48.      include the same pattern-matching constructions as
  49.      in  patterns,  as  well  as  arithmetic and string
  50.      expressions and assignments, if-else,  while,  for
  51.      statements, and multiple output streams.
  52.  
  53.           This  report  contains a user's guide, a dis-
  54.      cussion of the design and implementation  of  awk,
  55.      and some timing statistics.
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. USD:19-2   Awk -- A Pattern Scanning and Processing Language
  71.  
  72.  
  73. 1.  Introduction
  74.  
  75.      Awk  is  a  programming  language designed to make many
  76. common information retrieval  and  text  manipulation  tasks
  77. easy to state and to perform.
  78.  
  79.      The  basic  operation  of awk is to scan a set of input
  80. lines in order, searching for lines which match any of a set
  81. of patterns which the user has specified.  For each pattern,
  82. an action can be specified; this action will be performed on
  83. each line that matches the pattern.
  84.  
  85.      Readers  familiar  with  the  UNIX(R) program grep unix
  86. program manual will recognize the approach, although in  awk
  87. the  patterns  may  be  more  general  than in grep, and the
  88. actions allowed are more involved than merely  printing  the
  89. matching line.  For example, the awk program
  90.  
  91.    {print $3, $2}
  92.  
  93. prints  the  third  and  second  columns  of a table in that
  94. order.  The program
  95.  
  96.    $2 ~ /A|B|C/
  97.  
  98. prints all input lines with an A, B,  or  C  in  the  second
  99. field.  The program
  100.  
  101.    $1 != prev     { print; prev = $1 }
  102.  
  103. prints  all lines in which the first field is different from
  104. the previous first field.
  105.  
  106. 1.1.  Usage
  107.  
  108.      The command
  109.  
  110.    awk  program  [files]
  111.  
  112. executes the awk commands in the string program on  the  set
  113. of  named  files,  or  on the standard input if there are no
  114. files.  The statements can also be placed in a  file  pfile,
  115. and executed by the command
  116.  
  117.    awk  -f pfile  [files]
  118.  
  119.  
  120. 1.2.  Program Structure
  121.  
  122.      An awk program is a sequence of statements of the form:
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. Awk -- A Pattern Scanning and Processing Language   USD:19-3
  137.  
  138.  
  139.         pattern   { action }
  140.         pattern   { action }
  141.         ...
  142.  
  143. Each line of input is matched against each of  the  patterns
  144. in  turn.   For  each  pattern  that matches, the associated
  145. action is executed.  When all the patterns have been tested,
  146. the next line is fetched and the matching starts over.
  147.  
  148.      Either  the  pattern or the action may be left out, but
  149. not both.  If there is no action for a pattern, the matching
  150. line  is  simply  copied  to the output.  (Thus a line which
  151. matches several patterns can be printed several times.)   If
  152. there  is  no pattern for an action, then the action is per-
  153. formed for every input line.  A line which matches  no  pat-
  154. tern is ignored.
  155.  
  156.      Since  patterns  and actions are both optional, actions
  157. must be enclosed in braces to  distinguish  them  from  pat-
  158. terns.
  159.  
  160. 1.3.  Records and Fields
  161.  
  162.      Awk  input  is divided into ``records'' terminated by a
  163. record separator.  The default record separator  is  a  new-
  164. line,  so  by  default  awk  processes its input a line at a
  165. time.  The number of the current record is  available  in  a
  166. variable named NR.
  167.  
  168.      Each  input  record  is  considered  to be divided into
  169. ``fields.''  Fields are normally separated by white space --
  170. blanks  or  tabs  --  but  the  input field separator may be
  171. changed, as described below.  Fields are referred to as  $1,
  172. $2, and so forth, where $1 is the first field, and $0 is the
  173. whole input record itself.  Fields may be assigned to.   The
  174. number  of  fields  in  the current record is available in a
  175. variable named NF.
  176.  
  177.      The variables FS and RS refer to the  input  field  and
  178. record  separators;  they  may be changed at any time to any
  179. single character.  The optional  command-line  argument  -Fc
  180. may also be used to set FS to the character c.
  181.  
  182.      If  the  record separator is empty, an empty input line
  183. is taken as the record separator, and blanks, tabs and  new-
  184. lines are treated as field separators.
  185.  
  186.      The  variable FILENAME contains the name of the current
  187. input file.
  188.  
  189. 1.4.  Printing
  190.  
  191.      An action may have no pattern, in which case the action
  192. is  executed for all lines.  The simplest action is to print
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. USD:19-4   Awk -- A Pattern Scanning and Processing Language
  203.  
  204.  
  205. some or all of a record; this is  accomplished  by  the  awk
  206. command print.  The awk program
  207.  
  208.    { print }
  209.  
  210. prints  each  record,  thus  copying the input to the output
  211. intact.  More useful is to print a field or fields from each
  212. record.  For instance,
  213.  
  214.    print $2, $1
  215.  
  216. prints  the  first two fields in reverse order.  Items sepa-
  217. rated by a comma in the print statement will be separated by
  218. the  current  output field separator when output.  Items not
  219. separated by commas will be concatenated, so
  220.  
  221.    print $1 $2
  222.  
  223. runs the first and second fields together.
  224.  
  225.      The predefined variables NF and NR  can  be  used;  for
  226. example
  227.  
  228.    { print NR, NF, $0 }
  229.  
  230. prints  each  record  preceded  by the record number and the
  231. number of fields.
  232.  
  233.      Output may be diverted to multiple files; the program
  234.  
  235.    { print $1 >"foo1"; print $2 >"foo2" }
  236.  
  237. writes the first field, $1, on the file foo1, and the second
  238. field on file foo2.  The >> notation can also be used:
  239.  
  240.    print $1 >>"foo"
  241.  
  242. appends the output to the file foo.  (In each case, the out-
  243. put files are created if necessary.)  The file name can be a
  244. variable or a field as well as a constant; for example,
  245.  
  246.    print $1 >$2
  247.  
  248. uses the contents of field 2 as a file name.
  249.  
  250.      Naturally  there  is  a  limit  on the number of output
  251. files; currently it is 10.
  252.  
  253.      Similarly, output can be piped into another process (on
  254. UNIX only); for instance,
  255.  
  256.    print | "mail bwk"
  257.  
  258. mails the output to bwk.
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. Awk -- A Pattern Scanning and Processing Language   USD:19-5
  269.  
  270.  
  271.      The  variables  OFS  and  ORS may be used to change the
  272. current output field separator and output record  separator.
  273. The output record separator is appended to the output of the
  274. print statement.
  275.  
  276.      Awk also provides the printf statement for output  for-
  277. matting:
  278.  
  279.    printf format expr, expr, ...
  280.  
  281. formats  the expressions in the list according to the speci-
  282. fication in format and prints them.  For example,
  283.  
  284.    printf "%8.2f  %10ld\n", $1, $2
  285.  
  286. prints $1 as a floating point number 8 digits wide, with two
  287. after  the  decimal point, and $2 as a 10-digit long decimal
  288. number, followed by a newline.   No  output  separators  are
  289. produced  automatically;  you  must add them yourself, as in
  290. this example.  The version of printf is  identical  to  that
  291. used with C.  C programm language prentice hall 1978
  292.  
  293. 2.  Patterns
  294.  
  295.      A pattern in front of an action acts as a selector that
  296. determines whether the action is to be executed.  A  variety
  297. of expressions may be used as patterns: regular expressions,
  298. arithmetic  relational  expressions,  string-valued  expres-
  299. sions, and arbitrary boolean combinations of these.
  300.  
  301. 2.1.  BEGIN and END
  302.  
  303.      The  special pattern BEGIN matches the beginning of the
  304. input, before the first record is  read.   The  pattern  END
  305. matches the end of the input, after the last record has been
  306. processed.  BEGIN and END thus provide a way to gain control
  307. before  and after processing, for initialization and wrapup.
  308.  
  309.      As an example, the field separator  can  be  set  to  a
  310. colon by
  311.  
  312.    BEGIN     { FS = ":" }
  313.    ... rest of program ...
  314.  
  315. Or the input lines may be counted by
  316.  
  317.    END  { print NR }
  318.  
  319. If  BEGIN is present, it must be the first pattern; END must
  320. be the last if used.
  321.  
  322.  
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. USD:19-6   Awk -- A Pattern Scanning and Processing Language
  335.  
  336.  
  337. 2.2.  Regular Expressions
  338.  
  339.      The simplest regular expression is a literal string  of
  340. characters enclosed in slashes, like
  341.  
  342.    /smith/
  343.  
  344. This is actually a complete awk program which will print all
  345. lines which contain any occurrence of  the  name  ``smith''.
  346. If  a  line  contains ``smith'' as part of a larger word, it
  347. will also be printed, as in
  348.  
  349.    blacksmithing
  350.  
  351.  
  352.      Awk regular expressions include the regular  expression
  353. forms  found  in the UNIX text editor ed unix program manual
  354. and  grep  (without  back-referencing).   In  addition,  awk
  355. allows  parentheses  for grouping, | for alternatives, + for
  356. ``one or more'', and ? for ``zero or one'', all as  in  lex.
  357. Character classes may be abbreviated: [a-zA-Z0-9] is the set
  358. of all letters and digits.  As an example, the awk program
  359.  
  360.    /[Aa]ho|[Ww]einberger|[Kk]ernighan/
  361.  
  362. will print all lines which contain any of the names ``Aho,''
  363. ``Weinberger'' or ``Kernighan,'' whether capitalized or not.
  364.  
  365.      Regular expressions (with the extensions listed  above)
  366. must  be enclosed in slashes, just as in ed and sed.  Within
  367. a regular expression,  blanks  and  the  regular  expression
  368. metacharacters  are significant.  To turn of the magic mean-
  369. ing of one of the regular expression characters, precede  it
  370. with a backslash.  An example is the pattern
  371.  
  372.    /\/.*\//
  373.  
  374. which  matches any string of characters enclosed in slashes.
  375.  
  376.      One can also specify that any field or variable matches
  377. a  regular expression (or does not match it) with the opera-
  378. tors ~ and !~.  The program
  379.  
  380.    $1 ~ /[jJ]ohn/
  381.  
  382. prints all lines where the first field matches  ``john''  or
  383. ``John.''   Notice  that  this  will also match ``Johnson'',
  384. ``St. Johnsbury'', and so on.  To  restrict  it  to  exactly
  385. [jJ]ohn, use
  386.  
  387.    $1 ~ /^[jJ]ohn$/
  388.  
  389. The  caret ^ refers to the beginning of a line or field; the
  390. dollar sign $ refers to the end.
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. Awk -- A Pattern Scanning and Processing Language   USD:19-7
  401.  
  402.  
  403. 2.3.  Relational Expressions
  404.  
  405.      An awk pattern can be a relational expression involving
  406. the usual relational operators <, <=, ==, !=, >=, and >.  An
  407. example is
  408.  
  409.    $2 > $1 + 100
  410.  
  411. which selects lines where the second field is at  least  100
  412. greater than the first field.  Similarly,
  413.  
  414.    NF % 2 == 0
  415.  
  416. prints lines with an even number of fields.
  417.  
  418.      In  relational  tests, if neither operand is numeric, a
  419. string comparison is made; otherwise it is numeric.  Thus,
  420.  
  421.    $1 >= "s"
  422.  
  423. selects lines that begin with an  s,  t,  u,  etc.   In  the
  424. absence  of  any  other  information,  fields are treated as
  425. strings, so the program
  426.  
  427.    $1 > $2
  428.  
  429. will perform a string comparison.
  430.  
  431. 2.4.  Combinations of Patterns
  432.  
  433.      A pattern can be any boolean combination  of  patterns,
  434. using  the  operators  ||  (or), && (and), and ! (not).  For
  435. example,
  436.  
  437.    $1 >= "s" && $1 < "t" && $1 != "smith"
  438.  
  439. selects lines where the first field begins with  ``s'',  but
  440. is  not  ``smith''.  && and || guarantee that their operands
  441. will be evaluated from left to right;  evaluation  stops  as
  442. soon as the truth or falsehood is determined.
  443.  
  444. 2.5.  Pattern Ranges
  445.  
  446.      The ``pattern'' that selects an action may also consist
  447. of two patterns separated by a comma, as in
  448.  
  449.    pat1, pat2     { ... }
  450.  
  451. In this case, the action is performed for each line  between
  452. an  occurrence  of  pat1  and  the  next  occurrence of pat2
  453. (inclusive).  For example,
  454.  
  455.    /start/, /stop/
  456.  
  457.  
  458.  
  459.  
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. USD:19-8   Awk -- A Pattern Scanning and Processing Language
  467.  
  468.  
  469. prints all lines between start and stop, while
  470.  
  471.    NR == 100, NR == 200 { ... }
  472.  
  473. does the action for lines 100 through 200 of the input.
  474.  
  475. 3.  Actions
  476.  
  477.      An awk action is a sequence of action statements termi-
  478. nated  by  newlines  or semicolons.  These action statements
  479. can be used to do a variety of bookkeeping and string manip-
  480. ulating tasks.
  481.  
  482. 3.1.  Built-in Functions
  483.  
  484.      Awk  provides  a  ``length''  function  to  compute the
  485. length of a string of characters.  This program prints  each
  486. record, preceded by its length:
  487.  
  488.    {print length, $0}
  489.  
  490. length  by  itself is a ``pseudo-variable'' which yields the
  491. length of the current record; length(argument) is a function
  492. which  yields  the length of its argument, as in the equiva-
  493. lent
  494.  
  495.    {print length($0), $0}
  496.  
  497. The argument may be any expression.
  498.  
  499.      Awk also provides the arithmetic functions  sqrt,  log,
  500. exp,  and  int,  for square root, base e logarithm, exponen-
  501. tial, and integer part of their respective arguments.
  502.  
  503.      The name of one of these  built-in  functions,  without
  504. argument  or  parentheses, stands for the value of the func-
  505. tion on the whole record.  The program
  506.  
  507.    length < 10 || length > 20
  508.  
  509. prints lines whose length is less than 10  or  greater  than
  510. 20.
  511.  
  512.      The  function substr(s, m, n) produces the substring of
  513. s that begins at position m (origin 1)  and  is  at  most  n
  514. characters long.  If n is omitted, the substring goes to the
  515. end of s.  The function index(s1, s2) returns  the  position
  516. where the string s2 occurs in s1, or zero if it does not.
  517.  
  518.      The function sprintf(f, e1, e2, ...) produces the value
  519. of the expressions e1, e2, etc., in the printf format speci-
  520. fied by f.  Thus, for example,
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. Awk -- A Pattern Scanning and Processing Language   USD:19-9
  533.  
  534.  
  535.    x = sprintf("%8.2f %10ld", $1, $2)
  536.  
  537. sets x to the string produced by formatting the values of $1
  538. and $2.
  539.  
  540. 3.2.  Variables, Expressions, and Assignments
  541.  
  542.      Awk variables  take  on  numeric  (floating  point)  or
  543. string values according to context.  For example, in
  544.  
  545.    x = 1
  546.  
  547. x is clearly a number, while in
  548.  
  549.    x = "smith"
  550.  
  551. it  is  clearly  a string.  Strings are converted to numbers
  552. and vice versa whenever context demands it.  For instance,
  553.  
  554.    x = "3" + "4"
  555.  
  556. assigns 7 to x.  Strings which cannot be interpreted as num-
  557. bers  in  a  numerical  context  will generally have numeric
  558. value zero, but it is unwise to count on this behavior.
  559.  
  560.      By default, variables (other than built-ins)  are  ini-
  561. tialized to the null string, which has numerical value zero;
  562. this eliminates the need for most BEGIN sections.  For exam-
  563. ple, the sums of the first two fields can be computed by
  564.  
  565.         { s1 += $1; s2 += $2 }
  566.    END  { print s1, s2 }
  567.  
  568.  
  569.      Arithmetic  is  done internally in floating point.  The
  570. arithmetic operators are +, -, *, /, and  %  (mod).   The  C
  571. increment  ++ and decrement -- operators are also available,
  572. and so are the assignment operators +=, -=, *=, /=, and  %=.
  573. These operators may all be used in expressions.
  574.  
  575. 3.3.  Field Variables
  576.  
  577.      Fields  in  awk share essentially all of the properties
  578. of variables -- they may be used  in  arithmetic  or  string
  579. operations,  and  may  be assigned to.  Thus one can replace
  580. the first field with a sequence number like this:
  581.  
  582.    { $1 = NR; print }
  583.  
  584. or accumulate two fields into a third, like this:
  585.  
  586.    { $1 = $2 + $3; print $0 }
  587.  
  588. or assign a string to a field:
  589.  
  590.  
  591.  
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. USD:19-10  Awk -- A Pattern Scanning and Processing Language
  599.  
  600.  
  601.    { if ($3 > 1000)
  602.         $3 = "too big"
  603.      print
  604.    }
  605.  
  606. which replaces the third field by ``too big''  when  it  is,
  607. and in any case prints the record.
  608.  
  609.      Field references may be numerical expressions, as in
  610.  
  611.    { print $i, $(i+1), $(i+n) }
  612.  
  613. Whether  a field is deemed numeric or string depends on con-
  614. text; in ambiguous cases like
  615.  
  616.    if ($1 == $2) ...
  617.  
  618. fields are treated as strings.
  619.  
  620.      Each input line is split into fields  automatically  as
  621. necessary.   It  is  also  possible to split any variable or
  622. string into fields:
  623.  
  624.    n = split(s, array, sep)
  625.  
  626. splits the the string s into array[1], ...,  array[n].   The
  627. number  of  elements found is returned.  If the sep argument
  628. is provided, it is used as the field separator; otherwise FS
  629. is used as the separator.
  630.  
  631. 3.4.  String Concatenation
  632.  
  633.      Strings may be concatenated.  For example
  634.  
  635.    length($1 $2 $3)
  636.  
  637. returns the length of the first three fields.  Or in a print
  638. statement,
  639.  
  640.    print $1 " is " $2
  641.  
  642. prints the two fields separated by `` is ''.  Variables  and
  643. numeric expressions may also appear in concatenations.
  644.  
  645. 3.5.  Arrays
  646.  
  647.      Array elements are not declared; they spring into exis-
  648. tence by being mentioned.  Subscripts may have any  non-null
  649. value,  including  non-numeric  strings.  As an example of a
  650. conventional numeric subscript, the statement
  651.  
  652.    x[NR] = $0
  653.  
  654. assigns the current input record to the NR-th element of the
  655.  
  656.  
  657.  
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. Awk -- A Pattern Scanning and Processing Language  USD:19-11
  665.  
  666.  
  667. array  x.  In fact, it is possible in principle (though per-
  668. haps slow) to process the entire input  in  a  random  order
  669. with the awk program
  670.  
  671.         { x[NR] = $0 }
  672.    END  { ... program ... }
  673.  
  674. The first action merely records each input line in the array
  675. x.
  676.  
  677.      Array elements may  be  named  by  non-numeric  values,
  678. which  gives  awk  a  capability rather like the associative
  679. memory of Snobol tables.  Suppose the input contains  fields
  680. with values like apple, orange, etc.  Then the program
  681.  
  682.    /apple/   { x["apple"]++ }
  683.    /orange/  { x["orange"]++ }
  684.    END       { print x["apple"], x["orange"] }
  685.  
  686. increments  counts  for the named array elements, and prints
  687. them at the end of the input.
  688.  
  689. 3.6.  Flow-of-Control Statements
  690.  
  691.      Awk provides the basic flow-of-control  statements  if-
  692. else,  while, for, and statement grouping with braces, as in
  693. C.  We showed  the  if  statement  in  section  3.3  without
  694. describing  it.   The condition in parentheses is evaluated;
  695. if it is true, the statement following the if is done.   The
  696. else part is optional.
  697.  
  698.      The  while  statement  is  exactly like that of C.  For
  699. example, to print all input fields one per line,
  700.  
  701.    i = 1
  702.    while (i <= NF) {
  703.         print $i
  704.         ++i
  705.    }
  706.  
  707.  
  708.      The for statement is also exactly that of C:
  709.  
  710.    for (i = 1; i <= NF; i++)
  711.         print $i
  712.  
  713. does the same job as the while statement above.
  714.  
  715.      There is an alternate form of the for  statement  which
  716. is  suited  for  accessing  the  elements  of an associative
  717. array:
  718.  
  719.  
  720.  
  721.  
  722.  
  723.  
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. USD:19-12  Awk -- A Pattern Scanning and Processing Language
  731.  
  732.  
  733.    for (i in array)
  734.         statement
  735.  
  736. does statement with i set in turn to each element of  array.
  737. The  elements  are  accessed  in an apparently random order.
  738. Chaos will ensue if i is altered, or if any new elements are
  739. accessed during the loop.
  740.  
  741.      The expression in the condition part of an if, while or
  742. for can include relational operators like <, <=, >,  >=,  ==
  743. (``is  equal  to''),  and  !=  (``not  equal  to''); regular
  744. expression matches with the match operators ~  and  !~;  the
  745. logical  operators  ||, &&, and !; and of course parentheses
  746. for grouping.
  747.  
  748.      The break statement causes an immediate  exit  from  an
  749. enclosing  while  or  for; the continue statement causes the
  750. next iteration to begin.
  751.  
  752.      The statement next causes awk to  skip  immediately  to
  753. the  next  record  and  begin scanning the patterns from the
  754. top.  The statement exit causes the program to behave as  if
  755. the end of the input had occurred.
  756.  
  757.      Comments may be placed in awk programs: they begin with
  758. the character # and end with the end of the line, as in
  759.  
  760.    print x, y     # this is a comment
  761.  
  762.  
  763. 4.  Design
  764.  
  765.      The UNIX system already provides several programs  that
  766. operate  by  passing  input  through  a selection mechanism.
  767. Grep, the first and simplest, merely prints all lines  which
  768. match  a single specified pattern.  Egrep provides more gen-
  769. eral patterns, i.e., regular expressions in full generality;
  770. fgrep  searches  for  a  set of keywords with a particularly
  771. fast algorithm.  Sed unix programm manual provides  most  of
  772. the editing facilities of the editor ed, applied to a stream
  773. of input.  None of these programs provides numeric capabili-
  774. ties, logical relations, or variables.
  775.  
  776.      Lex lesk lexical analyzer cstr provides general regular
  777. expression recognition capabilities, and, by serving as a  C
  778. program generator, is essentially open-ended in its capabil-
  779. ities.  The use of lex, however, requires a knowledge  of  C
  780. programming,  and  a lex program must be compiled and loaded
  781. before use, which discourages its use for one-shot  applica-
  782. tions.
  783.  
  784.      Awk is an attempt to fill in another part of the matrix
  785. of possibilities.  It provides  general  regular  expression
  786. capabilities and an implicit input/output loop.  But it also
  787.  
  788.  
  789.  
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. Awk -- A Pattern Scanning and Processing Language  USD:19-13
  797.  
  798.  
  799. provides convenient numeric processing, variables, more gen-
  800. eral  selection,  and  control flow in the actions.  It does
  801. not require compilation or a knowledge of C.   Finally,  awk
  802. provides  a convenient way to access fields within lines; it
  803. is unique in this respect.
  804.  
  805.      Awk also tries to integrate strings  and  numbers  com-
  806. pletely,  by  treating  all  quantities  as  both string and
  807. numeric, deciding which  representation  is  appropriate  as
  808. late  as possible.  In most cases the user can simply ignore
  809. the differences.
  810.  
  811.      Most of the effort in developing awk went into deciding
  812. what  awk  should or should not do (for instance, it doesn't
  813. do string substitution) and what the syntax  should  be  (no
  814. explicit  operator for concatenation) rather than on writing
  815. or debugging the code.  We have tried  to  make  the  syntax
  816. powerful but easy to use and well adapted to scanning files.
  817. For example, the absence of declarations and  implicit  ini-
  818. tializations,  while  probably  a  bad  idea  for a general-
  819. purpose programming language, is  desirable  in  a  language
  820. that  is meant to be used for tiny programs that may even be
  821. composed on the command line.
  822.  
  823.      In practice, awk usage seems to  fall  into  two  broad
  824. categories.   One  is  what might be called ``report genera-
  825. tion'' -- processing an input to extract counts, sums,  sub-
  826. totals, etc.  This also includes the writing of trivial data
  827. validation programs, such as verifying that a field contains
  828. only  numeric  information  or  that  certain delimiters are
  829. properly balanced.  The combination of textual  and  numeric
  830. processing is invaluable here.
  831.  
  832.      A second area of use is as a data transformer, convert-
  833. ing data from the form produced by  one  program  into  that
  834. expected  by  another.   The simplest examples merely select
  835. fields, perhaps with rearrangements.
  836.  
  837. 5.  Implementation
  838.  
  839.      The actual implementation  of  awk  uses  the  language
  840. development  tools  available  on the UNIX operating system.
  841. The grammar is specified with yacc; yacc  johnson  cstr  the
  842. lexical analysis is done by lex; the regular expression rec-
  843. ognizers  are  deterministic  finite  automata   constructed
  844. directly from the expressions.  An awk program is translated
  845. into a parse tree which is then directly executed by a  sim-
  846. ple interpreter.
  847.  
  848.      Awk was designed for ease of use rather than processing
  849. speed; the delayed evaluation  of  variable  types  and  the
  850. necessity to break input into fields makes high speed diffi-
  851. cult to achieve in any case.  Nonetheless, the  program  has
  852. not proven to be unworkably slow.
  853.  
  854.  
  855.  
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. USD:19-14  Awk -- A Pattern Scanning and Processing Language
  863.  
  864.  
  865.      Table  I below shows the execution (user + system) time
  866. on a PDP-11/70 of the UNIX programs wc, grep, egrep,  fgrep,
  867. sed, lex, and awk on the following simple tasks:
  868.  
  869.   1. count the number of lines.
  870.  
  871.   2. print all lines containing ``doug''.
  872.  
  873.   3. print   all   lines  containing  ``doug'',  ``ken''  or
  874.      ``dmr''.
  875.  
  876.   4. print the third field of each line.
  877.  
  878.   5. print the third and second fields of each line, in that
  879.      order.
  880.  
  881.   6. append  all  lines  containing  ``doug'',  ``ken'', and
  882.      ``dmr'' to files  ``jdoug'',  ``jken'',  and  ``jdmr'',
  883.      respectively.
  884.  
  885.   7. print each line prefixed by ``line-number : ''.
  886.  
  887.   8. sum the fourth column of a table.
  888.  
  889. The  program wc merely counts words, lines and characters in
  890. its input; we have already mentioned  the  others.   In  all
  891. cases  the  input was a file containing 10,000 lines as cre-
  892. ated by the command ls -l; each line has the form
  893.  
  894.    -rw-rw-rw- 1 ava 123 Oct 15 17:05 xxx
  895.  
  896. The total length of this input is 452,960 characters.  Times
  897. for lex do not include compile or load.
  898.  
  899.      As  might  be  expected, awk is not as fast as the spe-
  900. cialized tools wc, sed, or the programs in the grep  family,
  901. but is faster than the more general tool lex.  In all cases,
  902. the tasks were about as easy to express as awk  programs  as
  903. programs  in  these  other languages; tasks involving fields
  904. were considerably easier to express as awk  programs.   Some
  905. of the test programs are shown in awk, sed and lex.  $LIST$
  906. center;  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c  c c
  907. c|n|n|n|n|n|n|n|n|.                                     Task
  908. Program   1    2    3    4    5    6    7    8  --  wc   8.6
  909. grep 11.7 13.1                      egrep     6.2  11.5 11.6
  910. fgrep     7.7  13.8 16.1  sed  10.2 11.6 15.8 29.0 30.5 16.1
  911. lex  65.1 150.1     144.2     67.7 70.3 104.0     81.7 92.8
  912. awk  15.0 25.6 29.9 33.3 38.9 46.4 71.4 31.1 --
  913.  
  914.  
  915.  Table I.  Execution Times of Programs. (Times are in sec.)
  916.  
  917.  
  918.                                      The  programs  for some
  919.  
  920.  
  921.  
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. Awk -- A Pattern Scanning and Processing Language  USD:19-15
  929.  
  930.  
  931. of  these  jobs  are   shown       5.   /[^ ]* [ ]*\([^ ]*\) [ ]*\([^ ]*\) .*/s//\2 \1/p
  932. below.  The lex programs are
  933. generally too long to  show.
  934.                                    6.   /ken/w jken
  935. AWK:                                    /doug/w jdoug
  936.                                         /dmr/w jdmr
  937.  
  938.    1.   END  {print NR}
  939.                                 LEX:
  940.  
  941.    2.   /doug/
  942.                                    1.   %{
  943.                                         int i;
  944.    3.   /ken|doug|dmr/                  %}
  945.                                         %%
  946.                                         \n   i++;
  947.    4.   {print $3}                      .    ;
  948.                                         %%
  949.                                         yywrap() {
  950.    5.   {print $3, $2}                       printf("%d\n", i);
  951.                                         }
  952.  
  953.    6.   /ken/     {print >"jken"}
  954.         /doug/    {print >"jdoug"} 2.   %%
  955.         /dmr/     {print >"jdmr"}       ^.*doug.*$     printf("%s\n", yytext);
  956.                                         .    ;
  957.                                         \n   ;
  958.    7.   {print NR ": " $0}
  959.  
  960.  
  961.    8.        {sum = sum + $4}
  962.         END  {print sum}
  963.  
  964.  
  965. SED:
  966.  
  967.  
  968.    1.   $=
  969.  
  970.  
  971.    2.   /doug/p
  972.  
  973.  
  974.    3.   /doug/p
  975.         /doug/d
  976.         /ken/p
  977.         /ken/d
  978.         /dmr/p
  979.         /dmr/d
  980.  
  981.  
  982.    4.   /[^ ]* [ ]*[^ ]* [ ]*\([^ ]*\) .*/s//\1/p
  983.  
  984.  
  985.  
  986.  
  987.  
  988.  
  989.  
  990.  
  991.