home *** CD-ROM | disk | FTP | other *** search
/ Garbo / Garbo.cdr / pc / unix / gawk_doc.zoo / gawk-info-2 < prev    next >
Encoding:
Text File  |  1989-04-13  |  48.8 KB  |  1,266 lines

  1. Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
  2. file gawk.texinfo.
  3.  
  4. This file documents `awk', a program that you can use to select
  5. particular records in a file and perform operations upon them.
  6.  
  7. Copyright (C) 1989 Free Software Foundation, Inc.
  8.  
  9. Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.  
  13. Permission is granted to copy and distribute modified versions of
  14. this manual under the conditions for verbatim copying, provided that
  15. the entire resulting derived work is distributed under the terms of a
  16. permission notice identical to this one.
  17.  
  18. Permission is granted to copy and distribute translations of this
  19. manual into another language, under the above conditions for modified
  20. versions, except that this permission notice may be stated in a
  21. translation approved by the Foundation.
  22.  
  23.  
  24. 
  25. File: gawk-info,  Node: Fields,  Next: Non-Constant Fields,  Prev: Records,  Up: Reading Files
  26.  
  27. Examining Fields
  28. ================
  29.  
  30. When `awk' reads an input record, the record is automatically
  31. separated or "parsed" by the interpreter into pieces called "fields".
  32. By default, fields are separated by whitespace, like words in a line.
  33. Whitespace in `awk' means any string of one or more spaces and/or
  34. tabs; other characters such as newline, formfeed, and so on, that are
  35. considered whitespace by other languages are *not* considered
  36. whitespace by `awk'.
  37.  
  38. The purpose of fields is to make it more convenient for you to refer
  39. to these pieces of the record.  You don't have to use them--you can
  40. operate on the whole record if you wish--but fields are what make
  41. simple `awk' programs so powerful.
  42.  
  43. To refer to a field in an `awk' program, you use a dollar--sign, `$',
  44. followed by the number of the field you want.  Thus, `$1' refers to
  45. the first field, `$2' to the second, and so on.  For example, suppose
  46. the following is a line of input:
  47.  
  48.      This seems like a pretty nice example.
  49.  
  50.  Here the first field, or `$1', is `This'; the second field, or `$2',
  51. is `seems'; and so on.  Note that the last field, `$7', is
  52. `example.'.  Because there is no space between the `e' and the `.',
  53. the period is considered part of the seventh field.
  54.  
  55. No matter how many fields there are, the last field in a record can
  56. be represented by `$NF'.  So, in the example above, `$NF' would be
  57. the same as `$7', which is `example.'.  Why this works is explained
  58. below (*note Non-Constant Fields::.).  If you try to refer to a field
  59. beyond the last one, such as `$8' when the record has only 7 fields,
  60. you get the empty string.
  61.  
  62. Plain `NF', with no `$', is a special variable whose value is the
  63. number of fields in the current record.
  64.  
  65. `$0', which looks like an attempt to refer to the zeroth field, is a
  66. special case: it represents the whole input record.  This is what you
  67. would use when you aren't interested in fields.
  68.  
  69. Here are some more examples:
  70.  
  71.      awk '$1 ~ /foo/ { print $0 }' BBS-list
  72.  
  73. This example contains the "matching" operator `~' (*note Comparison
  74. Ops::.).  Using this operator, all records in the file `BBS-list'
  75. whose first field contains the string `foo' are printed.
  76.  
  77. By contrast, the following example:
  78.  
  79.      awk '/foo/ { print $1, $NF }' BBS-list
  80.  
  81. looks for the string `foo' in *the entire record* and prints the
  82. first field and the last field for each input record containing the
  83. pattern.
  84.  
  85. The following program will search the system password file, and print
  86. the entries for users who have no password.
  87.  
  88.      awk -F: '$2 == ""' /etc/passwd
  89.  
  90. This program uses the `-F' option on the command line to set the file
  91. separator.  (Fields in `/etc/passwd' are separated by colons.  The
  92. second field represents a user's encrypted password, but if the field
  93. is empty, that user has no password.)
  94.  
  95.  
  96. 
  97. File: gawk-info,  Node: Non-Constant Fields,  Next: Changing Fields,  Prev: Fields,  Up: Reading Files
  98.  
  99. Non-constant Field Numbers
  100. ==========================
  101.  
  102. The number of a field does not need to be a constant.  Any expression
  103. in the `awk' language can be used after a `$' to refer to a field. 
  104. The `awk' utility evaluates the expression and uses the "numeric
  105. value" as a field number.  Consider this example:
  106.  
  107.      awk '{ print $NR }'
  108.  
  109. Recall that `NR' is the number of records read so far: 1 in the first
  110. record, 2 in the second, etc.  So this example will print the first
  111. field of the first record, the second field of the second record, and
  112. so on.  For the twentieth record, field number 20 will be printed;
  113. most likely this will make a blank line, because the record will not
  114. have 20 fields.
  115.  
  116. Here is another example of using expressions as field numbers:
  117.  
  118.      awk '{ print $(2*2) }' BBS-list
  119.  
  120. The `awk' language must evaluate the expression `(2*2)' and use its
  121. value as the field number to print.  The `*' sign represents
  122. multiplication, so the expression `2*2' evaluates to 4.  This
  123. example, then, prints the hours of operation (the fourth field) for
  124. every line of the file `BBS-list'.
  125.  
  126. When you use non--constant field numbers, you may ask for a field
  127. with a negative number.  This always results in an empty string, just
  128. like a field whose number is too large for the input record.  For
  129. example, `$(1-4)' would try to examine field number -3; it would
  130. result in an empty string.
  131.  
  132. If the field number you compute is zero, you get the entire record.
  133.  
  134. The number of fields in the current record is stored in the special
  135. variable `NF' (*note Special::.).  The expression `$NF' is not a
  136. special feature: it is the direct consequence of evaluating `NF' and
  137. using its value as a field number.
  138.  
  139.  
  140. 
  141. File: gawk-info,  Node: Changing Fields,  Next: Field Separators,  Prev: Non-Constant Fields,  Up: Reading Files
  142.  
  143. Changing the Contents of a Field
  144. ================================
  145.  
  146. You can change the contents of a field as seen by `awk' within an
  147. `awk' program; this changes what `awk' perceives as the current input
  148. record.  (The actual input is untouched: `awk' never modifies the
  149. input file.)
  150.  
  151. Look at this example:
  152.  
  153.      awk '{ $3 = $2 - 10; print $2, $3 }' inventory-shipped
  154.  
  155. The `-' sign represents subtraction, so this program reassigns field
  156. three, `$3', to be the value of field two minus ten, ``$2' - 10'. 
  157. (*Note Arithmetic Ops::.)  Then field two, and the new value for
  158. field three, are printed.
  159.  
  160. In order for this to work, the text in field `$2' must make sense as
  161. a number; the string of characters must be converted to a number in
  162. order for the computer to do arithmetic on it.  The number resulting
  163. from the subtraction is converted back to a string of characters
  164. which then becomes field 3.  *Note Conversion::.
  165.  
  166. When you change the value of a field (as perceived by `awk'), the
  167. text of the input record is recalculated to contain the new field
  168. where the old one was.  `$0' will from that time on reflect the
  169. altered field.  Thus,
  170.  
  171.      awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
  172.  
  173. will print a copy of the input file, with 10 subtracted from the
  174. second field of each line.
  175.  
  176. You can also assign contents to fields that are out of range.  For
  177. example:
  178.  
  179.      awk '{ $6 = ($5 + $4 + $3 + $2)/4) ; print $6 }' inventory-shipped
  180.  
  181. We've just created `$6', whose value is the average of fields `$2',
  182. `$3', `$4', and `$5'.  The `+' sign represents addition, and the `/'
  183. sign represents division.  For the file `inventory-shipped' `$6'
  184. represents the average number of parcels shipped for a particular
  185. month.
  186.  
  187. Creating a new field changes what `awk' interprets as the current
  188. input record.  The value of `$0' will be recomputed.  This
  189. recomputation affects and is affected by features not yet discussed,
  190. in particular, the "Output Field Separator", `OFS', which is used to
  191. separate the fields (*note Output Separators::.), and `NF' (the
  192. number of fields; *note Fields::.).  For example, the value of `NF'
  193. will be set to the number of the highest out--of--range field you
  194. create.
  195.  
  196. Note, however, that merely *referencing* an out--of--range field will
  197. *not* change the value of either `$0' or `NF'.  Referencing an
  198. out--of--range field merely produces a null string.  For example:
  199.  
  200.      if ($(NF+1) != "")
  201.          print "can't happen"
  202.      else
  203.          print "everything is normal"
  204.  
  205. should print `everything is normal'.  (*Note If::, for more
  206. information about `awk''s `if-else' statements.)
  207.  
  208.  
  209. 
  210. File: gawk-info,  Node: Field Separators,  Next: Multiple,  Prev: Changing Fields,  Up: Reading Files
  211.  
  212. Specifying How Fields Are Separated
  213. ===================================
  214.  
  215. You can change the way `awk' splits a record into fields by changing
  216. the value of the "field separator".  The field separator is
  217. represented by the special variable `FS' in an `awk' program, and can
  218. be set by `-F' on the command line.  The `awk' language scans each
  219. input line for the field separator character to determine the
  220. positions of fields within that line.  Shell programmers take note! 
  221. `awk' uses the variable `FS', not `IFS'.
  222.  
  223. The default value of the field separator is a string containing a
  224. single space.  This value is actually a special case; as you know, by
  225. default, fields are separated by whitespace sequences, not by single
  226. spaces: two spaces in a row do not delimit an empty field. 
  227. ``Whitespace'' is defined as sequences of one or more spaces or tab
  228. characters.
  229.  
  230. You change the value of `FS' by "assigning" it a new value.  You can
  231. do this using the special `BEGIN' pattern (*note BEGIN/END::.).  This
  232. pattern allows you to change the value of `FS' before any input is
  233. read.  The new value of `FS' is enclosed in quotations.  For example,
  234. set the value of `FS' to the string `","':
  235.  
  236.      awk 'BEGIN { FS = "," } ; { print $2 }'
  237.  
  238. and use the input line:
  239.  
  240.      John Q. Smith, 29 Oak St., Walamazoo, MI 42139
  241.  
  242. This `awk' program will extract the string `29 Oak St.'.
  243.  
  244. Sometimes your input data will contain separator characters that
  245. don't separate fields the way you thought they would.  For instance,
  246. the person's name in the example we've been using might have a title
  247. or suffix attached, such as `John Q. Smith, LXIX'.  If you assigned
  248. `FS' to be `,' then:
  249.  
  250.      awk 'BEGIN { FS = "," } ; { print $2 }
  251.  
  252. would extract `LXIX', instead of `29 Oak St.'.  If you were expecting
  253. the program to print the address, you would be surprised.  So, choose
  254. your data layout and separator characters carefully to prevent
  255. problems like this from happening.
  256.  
  257. You can assign `FS' to be a series of characters.  For example, the
  258. assignment:
  259.  
  260.      FS = ", \t"
  261.  
  262. makes every area of an input line that consists of a comma followed
  263. by a space and a tab, into a field separator.  (`\t' stands for a tab.)
  264.  
  265. If `FS' is any single character other than a blank, then that
  266. character is used as the field separator, and two successive
  267. occurrences of that character do delimit an empty field.
  268.  
  269. If you assign `FS' to a string longer than one character, that string
  270. is evaluated as a "regular expression" (*note Regexp::.).  The value
  271. of the regular expression is used as a field separator.
  272.  
  273. `FS' can be set on the command line.  You use the `-F' argument to do
  274. so.  For example:
  275.  
  276.      awk -F, 'PROGRAM' INPUT-FILES
  277.  
  278. sets `FS' to be the `,' character.  Notice that the argument uses a
  279. capital `F'.  Contrast this with `-f', which specifies a file
  280. containing an `awk' program.  Case is significant in command options:
  281. the `-F' and `-f' options have nothing to do with each other.  You
  282. can use both options at the same time to set the `FS' argument *and*
  283. get an `awk' program from a file.
  284.  
  285. As a special case, if the argument to `-F' is `t', then `FS' is set
  286. to the tab character.  (This is because if you type `-F\t', without
  287. the quotes, at the shell, the `\' gets deleted, so `awk' figures that
  288. you really want your fields to be separated with tabs, and not `t's. 
  289. Use `FS="t"' if you really do want to separate your fields with `t's.)
  290.  
  291. For example, let's use an `awk' program file called `baud.awk' that
  292. contains the pattern `/300/', and the action `print $1'.  We'll use
  293. the operating system utility `cat' to ``look'' at our program:
  294.  
  295.      % cat baud.awk
  296.      /300/   { print $1 }
  297.  
  298. Let's also set `FS' to be the `-' character.  We will apply all this
  299. information to the file `BBS-list'.  This `awk' program will now
  300. print a list of the names of the bulletin boards that operate at 300
  301. baud and the first three digits of their phone numbers.
  302.  
  303.      awk -F- -f baud.awk BBS-list
  304.  
  305. produces this output:
  306.  
  307.      aardvark     555
  308.      alpo
  309.      barfly       555
  310.      bites        555
  311.      camelot      555
  312.      core         555
  313.      fooey        555
  314.      foot         555
  315.      macfoo       555
  316.      sdace        555
  317.      sabafoo      555
  318.  
  319. Note the second line of output.  If you check the original file, you
  320. will see that the second line looked like this:
  321.  
  322.      alpo-net     555-3412     2400/1200/300     A
  323.  
  324. The `-' as part of the system's name was used as the field separator,
  325. instead of the `-' in the phone number that was originally intended. 
  326. This demonstrates why you have to be careful in choosing your field
  327. and record separators.
  328.  
  329.  
  330. 
  331. File: gawk-info,  Node: Multiple,  Next: Assignment Options,  Prev: Field Separators,  Up: Reading Files
  332.  
  333. Multiple--Line Records
  334. ======================
  335.  
  336. In some data bases, a single line cannot conveniently hold all the
  337. information in one entry.  Then you will want to use multi--line
  338. records.
  339.  
  340. The first step in doing this is to choose your data format: when
  341. records are not defined as single lines, how will you want to define
  342. them?  What should separate records?
  343.  
  344. One technique is to use an unusual character or string to separate
  345. records.  For example, you could use the formfeed character (written
  346. `\f' in `awk', as in C) to separate them, making each record a page
  347. of the file.  To do this, just set the variable `RS' to `"\f"' (a
  348. string containing the formfeed character), or whatever string you
  349. prefer to use.
  350.  
  351. Another technique is to have blank lines separate records.  By a
  352. special dispensation, a null string as the value of `RS' indicates
  353. that records are separated by one or more blank lines.  If you set
  354. `RS' to the null string, a record will always end at the first blank
  355. line encountered.  And the next record won't start until the first
  356. nonblank line that follows--no matter how many blank lines appear in
  357. a row, they will be considered one record--separator.
  358.  
  359. The second step is to separate the fields in the record.  One way to
  360. do this is to put each field on a separate line: to do this, just set
  361. the variable `FS' to the string `"\n"'.  (This simple regular
  362. expression matches a single newline.)  Another idea is to divide each
  363. of the lines into fields in the normal manner; the regular expression
  364. `"[ \t\n]+"' will do this nicely by treating the newlines inside the
  365. record just like spaces.
  366.  
  367. When `RS' is set to the null string, the newline character *always*
  368. acts as a field separator.  This is in addition to whatever value
  369. `FS' has.  The probable reason for this rule is so that you get
  370. rational behavior in the default case (i.e. `FS == " "').  This can
  371. be a problem if you really don't want the newline character to
  372. separate fields, since there is no way to do that.  However, you can
  373. work around this by using the `split' function to manually break up
  374. your data (*note String Functions::.).
  375.  
  376. Here is how to use records separated by blank lines and break each
  377. line into fields normally:
  378.  
  379.      awk 'BEGIN { RS = ""; FS = "[ \t\n]+" } ; { print $0 }' BBS-list
  380.  
  381.  
  382. 
  383. File: gawk-info,  Node: Assignment Options,  Next: Getline,  Prev: Multiple,  Up: Reading Files
  384.  
  385. Assigning Variables on the Command Line
  386. =======================================
  387.  
  388. You can include variable "assignments" among the file names on the
  389. command line used to invoke `awk' (*note Command Line::.).  Such
  390. assignments have the form:
  391.  
  392.      VARIABLE=TEXT
  393.  
  394. and allow you to change variables either at the beginning of the
  395. `awk' run or in between input files.  The variable assignment is
  396. performed at a time determined by its position among the input file
  397. arguments: after the processing of the preceding input file argument.
  398. For example:
  399.  
  400.      awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
  401.  
  402. prints the value of field number `n' for all input records.  Before
  403. the first file is read, the command line sets the variable `n' equal
  404. to 4.  This causes the fourth field of the file `inventory-shipped'
  405. to be printed.  After the first file has finished, but before the
  406. second file is started, `n' is set to 2, so that the second field of
  407. the file `BBS-list' will be printed.
  408.  
  409. Command line arguments are made available for explicit examination by
  410. the `awk' program in an array named `ARGV' (*note Special::.).
  411.  
  412.  
  413. 
  414. File: gawk-info,  Node: Getline,  Prev: Assignment Options,  Up: Reading Files
  415.  
  416. Explicit Input with `getline'
  417. =============================
  418.  
  419. So far we have been getting our input files from `awk''s main input
  420. stream--either the standard input (usually your terminal) or the
  421. files specified on the command line.  The `awk' language has a
  422. special built--in function called `getline' that can be used to read
  423. input under your explicit control.
  424.  
  425. This command is quite complex and should *not* be used by beginners. 
  426. The command (and its variations) is covered here because this is the
  427. section about input.  The examples that follow the explanation of the
  428. `getline' command include material that has not been covered yet. 
  429. Therefore, come back and attempt the `getline' command *after* you
  430. have reviewed the rest of this manual and have a good knowledge of
  431. how `awk' works.
  432.  
  433. When retrieving input, `getline' returns a 1 if it found a record,
  434. and a 0 if the end of the file was encountered.  If there was some
  435. error in getting a record, such as a file that could not be opened,
  436. then `getline' returns a -1.
  437.  
  438. In the following examples, COMMAND stands for a string value that
  439. represents a shell command.
  440.  
  441. `getline'
  442.      The `getline' function can be used by itself, in an `awk'
  443.      program, to read input from the current input.  All it does in
  444.      this case is read the next input record and split it up into
  445.      fields.  This is useful if you've finished processing the
  446.      current record, but you want to do some special processing
  447.      *right now* on the next record.  Here's an example:
  448.  
  449.           awk '{
  450.                if (t = index($0, "/*")) {
  451.                     if(t > 1)
  452.                          tmp = substr($0, 1, t - 1)
  453.                     else
  454.                          tmp = ""
  455.                     u = index(substr($0, t + 2), "*/")
  456.                     while (! u) {
  457.                          getline
  458.                          t = -1
  459.                          u = index($0, "*/")
  460.                     }
  461.                     if(u <= length($0) - 2)
  462.                          $0 = tmp substr($0, t + u + 3)
  463.                     else
  464.                          $0 = tmp
  465.                }
  466.                print $0
  467.           }'
  468.  
  469.      This `awk' program deletes all comments, `/* ...  */', from the
  470.      input.  By replacing the `print $0' with other statements, you
  471.      could perform more complicated processing on the de--commented
  472.      input, such as search it for matches for a regular expression.
  473.  
  474.      This form of the `getline' command sets `NF' (the number of
  475.      fields; *note Fields::.), `NR' (the number of records read so
  476.      far), the `FNR' variable (*note Records::.), and the value of
  477.      `$0'.
  478.  
  479.      *Note:* The new value of `$0' will be used in testing the
  480.      patterns of any subsequent rules. The original value of `$0'
  481.      that triggered the rule which executed `getline' is lost.  By
  482.      contrast, the `next' statement reads a new record but
  483.      immediately begins processing it normally, starting with the
  484.      first rule in the program.  *Note Next::.
  485.  
  486. `getline VAR'
  487.      This form of `getline' reads a record into the variable VAR. 
  488.      This is useful when you want your program to read the next
  489.      record from the input file, but you don't want to subject the
  490.      record to the normal input processing.
  491.  
  492.      For example, suppose the next line is a comment, or a special
  493.      string, and you want to read it, but you must make certain that
  494.      it won't accidentally trigger any rules.  This version of
  495.      `getline' will allow you to read that line and store it in a
  496.      variable so that the main read--a--line--and--check--each--rule
  497.      loop of `awk' never sees it.
  498.  
  499.      The following example swaps every two lines of input.  For
  500.      example, given:
  501.  
  502.           wan
  503.           tew
  504.           free
  505.           phore
  506.  
  507.      it outputs:
  508.  
  509.           tew
  510.           wan
  511.           phore
  512.           free
  513.  
  514.      Here's the program:
  515.  
  516.           awk '{
  517.                if ((getline tmp) > 0) {
  518.                     print tmp
  519.                     print $0
  520.                } else
  521.                     print $0
  522.           }'
  523.  
  524.      The `getline' function used in this way sets only `NR' and `FNR'
  525.      (and of course, VAR).  The record is not split into fields, so
  526.      the values of the fields (including `$0') and the value of `NF'
  527.      do not change.
  528.  
  529. `getline < FILE'
  530.      This form of the `getline' function takes its input from the
  531.      file FILE.  Here FILE is a string--valued expression that
  532.      specifies the file name.
  533.  
  534.      This form is useful if you want to read your input from a
  535.      particular file, instead of from the main input stream.  For
  536.      example, the following program reads its input record from the
  537.      file `foo.input' when it encounters a first field with a value
  538.      equal to 10 in the current input file.
  539.  
  540.           awk '{
  541.           if ($1 == 10) {
  542.                getline < "foo.input"
  543.                print
  544.           } else
  545.                print
  546.           }'
  547.  
  548.      Since the main input stream is not used, the values of `NR' and
  549.      `FNR' are not changed.  But the record read is split into fields
  550.      in the normal manner, so the values of `$0' and other fields are
  551.      changed.  So is the value of `NF'.
  552.  
  553.      This does not cause the record to be tested against all the
  554.      patterns in the `awk' program, in the way that would happen if
  555.      the record were read normally by the main processing loop of
  556.      `awk'.  However the new record is tested against any subsequent
  557.      rules, just as when `getline' is used without a redirection.
  558.  
  559. `getline VAR < FILE'
  560.      This form of the `getline' function takes its input from the
  561.      file FILE and puts it in the variable VAR.  As above, FILE is a
  562.      string--valued expression that specifies the file to read from.
  563.  
  564.      In this version of `getline', none of the built--in variables
  565.      are changed, and the record is not split into fields.  The only
  566.      variable changed is VAR.
  567.  
  568.      For example, the following program copies all the input files to
  569.      the output, except for records that say `@include FILENAME'. 
  570.      Such a record is replaced by the contents of the file FILENAME.
  571.  
  572.           awk '{
  573.                if (NF == 2 && $1 == "@include") {
  574.                     while ((getline line < $2) > 0)
  575.                          print line
  576.                     close($2)
  577.                } else
  578.                     print
  579.           }'
  580.  
  581.      Note here how the name of the extra input file is not built into
  582.      the program; it is taken from the data, from the second field on
  583.      the `@include' line.
  584.  
  585.      The `close' command is used to ensure that if two identical
  586.      `@include' lines appear in the input, the entire specified file
  587.      is included twice.  *Note Close Input::.
  588.  
  589.      One deficiency of this program is that it does not process
  590.      nested `@include' statements the way a true macro preprocessor
  591.      would.
  592.  
  593. `COMMAND | getline'
  594.      You can "pipe" the output of a command into `getline'.  A pipe
  595.      is simply a way to link the output of one program to the input
  596.      of another.  In this case, the string COMMAND is run as a shell
  597.      command and its output is piped into `awk' to be used as input. 
  598.      This form of `getline' reads one record from the pipe.
  599.  
  600.      For example, the following program copies input to output,
  601.      except for lines that begin with `@execute', which are replaced
  602.      by the output produced by running the rest of the line as a
  603.      shell command:
  604.  
  605.           awk '{
  606.                if ($1 == "@execute") {
  607.                     tmp = substr($0, 10)
  608.                     while ((tmp | getline) > 0)
  609.                          print
  610.                     close(tmp)
  611.                } else
  612.                     print
  613.           }'
  614.  
  615.      The `close' command is used to ensure that if two identical
  616.      `@execute' lines appear in the input, the command is run again
  617.      for each one.  *Note Close Input::.
  618.  
  619.      Given the input:
  620.  
  621.           foo
  622.           bar
  623.           baz
  624.           @execute who
  625.           bletch
  626.  
  627.      the program might produce:
  628.  
  629.           foo
  630.           bar
  631.           baz
  632.           hack     ttyv0   Jul 13 14:22
  633.           hack     ttyp0   Jul 13 14:23     (gnu:0)
  634.           hack     ttyp1   Jul 13 14:23     (gnu:0)
  635.           hack     ttyp2   Jul 13 14:23     (gnu:0)
  636.           hack     ttyp3   Jul 13 14:23     (gnu:0)
  637.           bletch
  638.  
  639.      Notice that this program ran the command `who' and printed the
  640.      result.  (If you try this program yourself, you will get
  641.      different results, showing you logged in.)
  642.  
  643.      This variation of `getline' splits the record into fields, sets
  644.      the value of `NF' and recomputes the value of `$0'.  The values
  645.      of `NR' and `FNR' are not changed.
  646.  
  647. `COMMAND | getline VAR'
  648.      The output of the command COMMAND is sent through a pipe to
  649.      `getline' and into the variable VAR.  For example, the following
  650.      program reads the current date and time into the variable
  651.      `current_time', using the utility called `date', and then prints
  652.      it.
  653.  
  654.           awk 'BEGIN {
  655.                "date" | getline current_time
  656.                close("date")
  657.                print "Report printed on " current_time
  658.           }'
  659.  
  660.      In this version of `getline', none of the built--in variables
  661.      are changed, and the record is not split into fields.
  662.  
  663.  
  664. 
  665. File: gawk-info,  Node: Close Input,  Up: Getline
  666.  
  667. Closing Input Files
  668. -------------------
  669.  
  670. If the same file name or the same shell command is used with
  671. `getline' more than once during the execution of the `awk' program,
  672. the file is opened (or the command is executed) only the first time. 
  673. At that time, the first record of input is read from that file or
  674. command.  The next time the same file or command is used in
  675. `getline', another record is read from it, and so on.
  676.  
  677. What this implies is that if you want to start reading the same file
  678. again from the beginning, or if you want to rerun a shell command
  679. (rather that reading more output from the command), you must take
  680. special steps.  What you can do is use the `close' statement:
  681.  
  682.      close (FILENAME)
  683.  
  684. This statement closes a file or pipe, represented here by FILENAME. 
  685. The string value of FILENAME must be the same value as the string
  686. used to open the file or pipe to begin with.
  687.  
  688. Once this statement is executed, the next `getline' from that file or
  689. command will reopen the file or rerun the command.
  690.  
  691.  
  692. 
  693. File: gawk-info,  Node: Printing,  Next: One-liners,  Prev: Reading Files,  Up: Top
  694.  
  695. Printing Output
  696. ***************
  697.  
  698. One of the most common things that actions do is to output or "print"
  699. some or all of the input.  For simple output, use the `print'
  700. statement.  For fancier formatting use the `printf' statement.  Both
  701. are described in this chapter.
  702.  
  703. * Menu:
  704.  
  705. * Print::              The `print' statement.
  706. * Print Examples::     Simple examples of `print' statements.
  707. * Output Separators::  The output separators and how to change them.
  708.  
  709. * Redirection::        How to redirect output to multiple files and pipes.
  710. * Close Output::       How to close output files and pipes.
  711.  
  712. * Printf::             The `printf' statement.
  713.  
  714.  
  715. 
  716. File: gawk-info,  Node: Print,  Next: Print Examples,  Up: Printing
  717.  
  718. The `print' Statement
  719. =====================
  720.  
  721. The `print' statement does output with simple, standardized
  722. formatting.  You specify only the strings or numbers to be printed,
  723. in a list separated by commas.  They are output, separated by single
  724. spaces, followed by a newline.  The statement looks like this:
  725.  
  726.      print ITEM1, ITEM2, ...
  727.  
  728.  The entire list of items may optionally be enclosed in parentheses. 
  729. The parentheses are necessary if any of the item expressions uses a
  730. relational operator; otherwise it could be confused with a
  731. redirection (*note Redirection::.).  The relational operators are
  732. `==', `!=', `<', `>', `>=', `<=', `~' and `!~' (*note Comparison
  733. Ops::.).
  734.  
  735. The items printed can be constant strings or numbers, fields of the
  736. current record (such as `$1'), variables, or any `awk' expressions. 
  737. The `print' statement is completely general for computing *what*
  738. values to print.  With one exception (*note Output Separators::.),
  739. what you can't do is specify *how* to print them--how many columns to
  740. use, whether to use exponential notation or not, and so on.  For
  741. that, you need the `printf' statement (*note Printf::.).
  742.  
  743. To print a fixed piece of text, write a string constant as one item,
  744. such as `"Hello there"'.  If you forget to use the double--quote
  745. characters, your text will be taken as an `awk' expression, and you
  746. will probably get an error.  Keep in mind that a space will be
  747. printed between any two items.
  748.  
  749. The simple statement `print' with no items is equivalent to `print
  750. $0': it prints the entire current record.  To print a blank line, use
  751. `print ""', where `""' is the null, or empty, string.
  752.  
  753. Most often, each `print' statement makes one line of output.  But it
  754. isn't limited to one line.  If an item value is a string that
  755. contains a newline, the newline is output along with the rest of the
  756. string.  A single `print' can make any number of lines this way.
  757.  
  758.  
  759. 
  760. File: gawk-info,  Node: Print Examples,  Next: Output Separators,  Prev: Print,  Up: Printing
  761.  
  762. Examples of `print' Statements
  763. ==============================
  764.  
  765. Here is an example that prints the first two fields of each input
  766. record, with a space between them:
  767.  
  768.      awk '{ print $1, $2 }' inventory-shipped
  769.  
  770. Its output looks like this:
  771.  
  772.      Jan 13
  773.      Feb 15
  774.      Mar 15
  775.      ...
  776.  
  777.  A common mistake in using the `print' statement is to omit the comma
  778. between two items.  This often has the effect of making the items run
  779. together in the output, with no space.  The reason for this is that
  780. juxtaposing two string expressions in `awk' means to concatenate
  781. them.  For example, without the comma:
  782.  
  783.      awk '{ print $1 $2 }' inventory-shipped
  784.  
  785. prints:
  786.  
  787.      Jan13
  788.      Feb15
  789.      Mar15
  790.      ...
  791.  
  792.  Neither example's output makes much sense to someone unfamiliar with
  793. the file `inventory-shipped'.  A heading line at the beginning would
  794. make it clearer.  Let's add some headings to our table of months
  795. (`$1') and green crates shipped (`$2').  We do this using the BEGIN
  796. pattern (*note BEGIN/END::.) to cause the headings to be printed only
  797. once:
  798.  
  799.      awk 'BEGIN {  print "Month Crates"
  800.                    print "---- -----" }
  801.                 {  print $1, $2 }' inventory-shipped
  802.  
  803. Did you already guess what will happen?  This program prints the
  804. following:
  805.  
  806.      Month Crates
  807.      ---- -----
  808.      Jan 13
  809.      Feb 15
  810.      Mar 15
  811.      ...
  812.  
  813.  The headings and the table data don't line up!  We can fix this by
  814. printing some spaces between the two fields:
  815.  
  816.      awk 'BEGIN { print "Month Crates"
  817.                   print "---- -----" }
  818.                 { print $1, "     ", $2 }' inventory-shipped
  819.  
  820. You can imagine that this way of lining up columns can get pretty
  821. complicated when you have many columns to fix.  Counting spaces for
  822. two or three columns can be simple, but more than this and you can
  823. get ``lost'' quite easily.  This is why the `printf' statement was
  824. created (*note Printf::.); one of its specialties is lining up
  825. columns of data.
  826.  
  827.  
  828. 
  829. File: gawk-info,  Node: Output Separators,  Next: Redirection,  Prev: Print Examples,  Up: Printing
  830.  
  831. Output Separators
  832. =================
  833.  
  834. As mentioned previously, a `print' statement contains a list of
  835. items, separated by commas.  In the output, the items are normally
  836. separated by single spaces.  But they do not have to be spaces; a
  837. single space is only the default.  You can specify any string of
  838. characters to use as the "output field separator", by setting the
  839. special variable `OFS'.  The initial value of this variable is the
  840. string `" "'.
  841.  
  842. The output from an entire `print' statement is called an "output
  843. record".  Each `print' statement outputs one output record and then
  844. outputs a string called the "output record separator".  The special
  845. variable `ORS' specifies this string.  The initial value of the
  846. variable is the string `"\n"' containing a newline character; thus,
  847. normally each `print' statement makes a separate line.
  848.  
  849. You can change how output fields and records are separated by
  850. assigning new values to the variables `OFS' and/or `ORS'.  The usual
  851. place to do this is in the `BEGIN' rule (*note BEGIN/END::.), so that
  852. it happens before any input is processed.  You may also do this with
  853. assignments on the command line, before the names of your input files.
  854.  
  855. The following example prints the first and second fields of each
  856. input record separated by a semicolon, with a blank line added after
  857. each line:
  858.  
  859.      awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
  860.                 { print $1, $2 }'  BBS-list
  861.  
  862. If the value of `ORS' does not contain a newline, all your output
  863. will be run together on a single line, unless you output newlines
  864. some other way.
  865.  
  866.  
  867. 
  868. File: gawk-info,  Node: Redirection,  Next: Printf,  Prev: Output Separators,  Up: Printing
  869.  
  870. Redirecting Output of `print' and `printf'
  871. ==========================================
  872.  
  873. So far we have been dealing only with output that prints to the
  874. standard output, usually your terminal.  Both `print' and `printf'
  875. can be told to send their output to other places.  This is called
  876. "redirection".
  877.  
  878. A redirection appears after the `print' or `printf' statement. 
  879. Redirections in `awk' are written just like redirections in shell
  880. commands, except that they are written inside the `awk' program.
  881.  
  882. Here are the three forms of output redirection.  They are all shown
  883. for the `print' statement, but they work for `printf' also.
  884.  
  885. `print ITEMS > OUTPUT-FILE'
  886.      This type of redirection prints the items onto the output file
  887.      OUTPUT-FILE.  The file name OUTPUT-FILE can be any expression. 
  888.      Its value is changed to a string and then used as a filename
  889.      (*note Expressions::.).
  890.  
  891.      When this type of redirection is used, the OUTPUT-FILE is erased
  892.      before the first output is written to it.  Subsequent writes do
  893.      not erase OUTPUT-FILE, but append to it.  If OUTPUT-FILE does
  894.      not exist, then it is created.
  895.  
  896.      For example, here is how one `awk' program can write a list of
  897.      BBS names to a file `name-list' and a list of phone numbers to a
  898.      file `phone-list'.  Each output file contains one name or number
  899.      per line.
  900.  
  901.           awk '{ print $2 > "phone-list"
  902.                  print $1 > "name-list" }' BBS-list
  903.  
  904. `print ITEMS >> OUTPUT-FILE'
  905.      This type of redirection prints the items onto the output file
  906.      OUTPUT-FILE.  The difference between this and the single--`>'
  907.      redirection is that the old contents (if any) of OUTPUT-FILE are
  908.      not erased.  Instead, the `awk' output is appended to the file.
  909.  
  910. `print ITEMS | COMMAND'
  911.      It is also possible to send output through a "pipe" instead of
  912.      into a file.   This type of redirection opens a pipe to COMMAND
  913.      and writes the values of ITEMS through this pipe, to another
  914.      process created to execute COMMAND.
  915.  
  916.      The redirection argument COMMAND is actually an `awk'
  917.      expression.  Its value is converted to a string, whose contents
  918.      give the shell command to be run.
  919.  
  920.      For example, this produces two files, one unsorted list of BBS
  921.      names and one list sorted in reverse alphabetical order:
  922.  
  923.           awk '{ print $1 > "names.unsorted"
  924.                  print $1 | "sort -r > names.sorted" }' BBS-list
  925.  
  926.      Here the unsorted list is written with an ordinary redirection
  927.      while the sorted list is written by piping through the `sort'
  928.      utility.
  929.  
  930.      Here is an example that uses redirection to mail a message to a
  931.      mailing list `bug-system'.  This might be useful when trouble is
  932.      encountered in an `awk' script run periodically for system
  933.      maintenance.
  934.  
  935.           print "Awk script failed:", $0 | "mail bug-system"
  936.           print "processing record number", FNR, "of", FILENAME  | "mail bug-system"
  937.           close ("mail bug-system")
  938.  
  939.      We use a `close' statement here because it's a good idea to
  940.      close the pipe as soon as all the intended output has been sent
  941.      to it.  *Note Close Output::, for more information on this.
  942.  
  943. Redirecting output using `>', `>>', or `|' asks the system to open a
  944. file or pipe only if the particular FILE or COMMAND you've specified
  945. has not already been written to by your program.
  946.  
  947.  
  948. 
  949. File: gawk-info,  Node: Close Output,  Up: Redirection
  950.  
  951. Closing Output Files and Pipes
  952. ------------------------------
  953.  
  954. When a file or pipe is opened, the filename or command associated
  955. with it is remembered by `awk' and subsequent writes to the same file
  956. or command are appended to the previous writes.  The file or pipe
  957. stays open until `awk' exits.  This is usually convenient.
  958.  
  959. Sometimes there is a reason to close an output file or pipe earlier
  960. than that.  To do this, use the `close' command, as follows:
  961.  
  962.      close (FILENAME)
  963.  
  964. or
  965.  
  966.      close (COMMAND)
  967.  
  968. The argument FILENAME or COMMAND can be any expression.  Its value
  969. must exactly equal the string used to open the file or pipe to begin
  970. with--for example, if you open a pipe with this:
  971.  
  972.      print $1 | "sort -r > names.sorted"
  973.  
  974. then you must close it with this:
  975.  
  976.      close ("sort -r > names.sorted")
  977.  
  978. Here are some reasons why you might need to close an output file:
  979.  
  980.    * To write a file and read it back later on in the same `awk'
  981.      program.  Close the file when you are finished writing it; then
  982.      you can start reading it with `getline' (*note Getline::.).
  983.  
  984.    * To write numerous files, successively, in the same `awk'
  985.      program.  If you don't close the files, eventually you will
  986.      exceed the system limit on the number of open files in one
  987.      process.  So close each one when you are finished writing it.
  988.  
  989.    * To make a command finish.  When you redirect output through a
  990.      pipe, the command reading the pipe normally continues to try to
  991.      read input as long as the pipe is open.  Often this means the
  992.      command cannot really do its work until the pipe is closed.  For
  993.      example, if you redirect output to the `mail' program, the
  994.      message will not actually be sent until the pipe is closed.
  995.  
  996.    * To run the same subprogram a second time, with the same arguments.
  997.      This is not the same thing as giving more input to the first run!
  998.  
  999.      For example, suppose you pipe output to the `mail' program.  If
  1000.      you output several lines redirected to this pipe without closing
  1001.      it, they make a single message of several lines.  By contrast,
  1002.      if you close the pipe after each line of output, then each line
  1003.      makes a separate message.
  1004.  
  1005.  
  1006. 
  1007. File: gawk-info,  Node: Printf,  Prev: Redirection,  Up: Printing
  1008.  
  1009. Using `printf' Statements For Fancier Printing
  1010. ==============================================
  1011.  
  1012. If you want more precise control over the output format than `print'
  1013. gives you, use `printf'.  With `printf' you can specify the width to
  1014. use for each item, and you can specify various stylistic choices for
  1015. numbers (such as what radix to use, whether to print an exponent,
  1016. whether to print a sign, and how many digits to print after the
  1017. decimal point).  You do this by specifying a "format string".
  1018.  
  1019. * Menu:
  1020.  
  1021. * Basic Printf::       Syntax of the `printf' statement.
  1022. * Format-Control::     Format-control letters.
  1023. * Modifiers::          Format--specification modifiers.
  1024. * Printf Examples::    Several examples.
  1025.  
  1026.  
  1027. 
  1028. File: gawk-info,  Node: Basic Printf,  Next: Format-Control,  Up: Printf
  1029.  
  1030. Introduction to the `printf' Statement
  1031. --------------------------------------
  1032.  
  1033. The `printf' statement looks like this:
  1034.  
  1035.      printf FORMAT, ITEM1, ITEM2, ...
  1036.  
  1037.  The entire list of items may optionally be enclosed in parentheses. 
  1038. The parentheses are necessary if any of the item expressions uses a
  1039. relational operator; otherwise it could be confused with a
  1040. redirection (*note Redirection::.).  The relational operators are
  1041. `==', `!=', `<', `>', `>=', `<=', `~' and `!~' (*note Comparison
  1042. Ops::.).
  1043.  
  1044. The difference between `printf' and `print' is the argument FORMAT. 
  1045. This is an expression whose value is taken as a string; its job is to
  1046. say how to output each of the other arguments.  It is called the
  1047. "format string".
  1048.  
  1049. The format string is essentially the same as in the C library
  1050. function `printf'.  Most of FORMAT is text to be output verbatim. 
  1051. Scattered among this text are "format specifiers", one per item. 
  1052. Each format specifier says to output the next item at that place in
  1053. the format.
  1054.  
  1055. The `printf' statement does not automatically append a newline to its
  1056. output.  It outputs nothing but what the format specifies.  So if you
  1057. want a newline, you must include one in the format.  The output
  1058. separator variables `OFS' and `ORS' have no effect on `printf'
  1059. statements.
  1060.  
  1061.  
  1062. 
  1063. File: gawk-info,  Node: Format-Control,  Next: Modifiers,  Prev: Basic Printf,  Up: Printf
  1064.  
  1065. Format--Control Characters
  1066. --------------------------
  1067.  
  1068. A format specifier starts with the character `%' and ends with a
  1069. "format--control letter"; it tells the `printf' statement how to
  1070. output one item.  (If you actually want to output a `%', write `%%'.)
  1071. The format--control letter specifies what kind of value to print. 
  1072. The rest of the format specifier is made up of optional "modifiers"
  1073. which are parameters such as the field width to use.
  1074.  
  1075. Here is a list of them:
  1076.  
  1077. `c'
  1078.      This prints a number as an ASCII character.  Thus, `printf "%c",
  1079.      65' outputs the letter `A'.  The output for a string value is
  1080.      the first character of the string.
  1081.  
  1082. `d'
  1083.      This prints a decimal integer.
  1084.  
  1085. `e'
  1086.      This prints a number in scientific (exponential) notation.  For
  1087.      example,
  1088.  
  1089.           printf "%4.3e", 1950
  1090.  
  1091.      prints `1.950e+03', with a total of 4 significant figures of
  1092.      which 3 follow the decimal point.  The `4.3' are "modifiers",
  1093.      discussed below.
  1094.  
  1095. `f'
  1096.      This prints a number in floating point notation.
  1097.  
  1098. `g'
  1099.      This prints either scientific notation or floating point
  1100.      notation, whichever is shorter.
  1101.  
  1102. `o'
  1103.      This prints an unsigned octal integer.
  1104.  
  1105. `s'
  1106.      This prints a string.
  1107.  
  1108. `x'
  1109.      This prints an unsigned hexadecimal integer.
  1110.  
  1111. `%'
  1112.      This isn't really a format--control letter, but it does have a
  1113.      meaning when used after a `%': the sequence `%%' outputs one
  1114.      `%'.  It does not consume an argument.
  1115.  
  1116.  
  1117. 
  1118. File: gawk-info,  Node: Modifiers,  Next: Printf Examples,  Prev: Format-Control,  Up: Printf
  1119.  
  1120. Modifiers for `printf' Formats
  1121. ------------------------------
  1122.  
  1123. A format specification can also include "modifiers" that can control
  1124. how much of the item's value is printed and how much space it gets. 
  1125. The modifiers come between the `%' and the format--control letter. 
  1126. Here are the possible modifiers, in the order in which they may appear:
  1127.  
  1128. `-'
  1129.      The minus sign, used before the width modifier, says to
  1130.      left--justify the argument within its specified width.  Normally
  1131.      the argument is printed right--justified in the specified width.
  1132.  
  1133. `WIDTH'
  1134.      This is a number representing the desired width of a field. 
  1135.      Inserting any number between the `%' sign and the format control
  1136.      character forces the field to be expanded to this width.  The
  1137.      default way to do this is to pad with spaces on the left.
  1138.  
  1139. `.PREC'
  1140.      This is a number that specifies the precision to use when
  1141.      printing.  This specifies the number of digits you want printed
  1142.      to the right of the decimal place.
  1143.  
  1144. The C library `printf''s dynamic WIDTH and PREC capability (for
  1145. example, `"%*.*s"') is not supported.  However, it can be easily
  1146. simulated using concatenation to dynamically build the format string.
  1147.  
  1148.  
  1149. 
  1150. File: gawk-info,  Node: Printf Examples,  Prev: Modifiers,  Up: Printf
  1151.  
  1152. Examples of Using `printf'
  1153. --------------------------
  1154.  
  1155. Here is how to use `printf' to make an aligned table:
  1156.  
  1157.      awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
  1158.  
  1159. prints the names of bulletin boards (`$1') of the file `BBS-list' as
  1160. a string of 10 characters, left justified.  It also prints the phone
  1161. numbers (`$2') afterward on the line.  This will produce an aligned
  1162. two--column table of names and phone numbers, like so:
  1163.  
  1164.      aardvark   555-5553
  1165.      alpo-net   555-3412
  1166.      barfly     555-7685
  1167.      bites      555-1675
  1168.      camelot    555-0542
  1169.      core       555-2912
  1170.      fooey      555-1234
  1171.      foot       555-6699
  1172.      macfoo     555-6480
  1173.      sdace      555-3430
  1174.      sabafoo    555-2127
  1175.  
  1176. Did you notice that we did not specify that the phone numbers be
  1177. printed as numbers?  They had to be printed as strings because the
  1178. numbers are separated by a dash.  This dash would be interpreted as a
  1179. "minus" sign if we had tried to print the phone numbers as numbers. 
  1180. This would have led to some pretty confusing results.
  1181.  
  1182. We did not specify a width for the phone numbers because they are the
  1183. last things on their lines.  We don't need to put spaces after them.
  1184.  
  1185. We could make our table look even nicer by adding headings to the
  1186. tops of the columns.  To do this, use the BEGIN pattern (*note
  1187. BEGIN/END::.) to cause the header to be printed only once, at the
  1188. beginning of the `awk' program:
  1189.  
  1190.      awk 'BEGIN { print "Name      Number"
  1191.                   print "---      -----" }
  1192.            { printf "%-10s %s\n", $1, $2 }' BBS-list
  1193.  
  1194. Did you notice that we mixed `print' and `printf' statements in the
  1195. above example?  We could have used just `printf' statements to get
  1196. the same results:
  1197.  
  1198.      awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
  1199.                   printf "%-10s %s\n", "---", "-----" }
  1200.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  1201.  
  1202. By outputting each column heading with the same format specification
  1203. used for the elements of the column, we have made sure that the
  1204. headings will be aligned just like the columns.
  1205.  
  1206. The fact that the same format specification is used can be emphasized
  1207. by storing it in a variable, like so:
  1208.  
  1209.      awk 'BEGIN { format = "%-10s %s\n"
  1210.                   printf format, "Name", "Number"
  1211.                   printf format, "---", "-----" }
  1212.           { printf format, $1, $2 }' BBS-list
  1213.  
  1214. See if you can use the `printf' statement to line up the headings and
  1215. table data for our `inventory-shipped' example covered earlier in the
  1216. section on the `print' statement (*note Print::.).
  1217.  
  1218.  
  1219. 
  1220. File: gawk-info,  Node: One-liners,  Next: Patterns,  Prev: Printing,  Up: Top
  1221.  
  1222. Useful ``One-liners''
  1223. *********************
  1224.  
  1225. Useful `awk' programs are often short, just a line or two.  Here is a
  1226. collection of useful, short programs to get you started.  Some of
  1227. these programs contain constructs that haven't been covered yet.  The
  1228. description of the program will give you a good idea of what is going
  1229. on, but please read the rest of the manual to become an `awk' expert!
  1230.  
  1231. `awk '{ num_fields = num_fields + NF }'
  1232. ``     END { print num_fields }'''
  1233.      This program prints the total number of fields in all input lines.
  1234.  
  1235. `awk 'length($0) > 80''
  1236.      This program prints every line longer than 80 characters.  The
  1237.      sole rule has a relational expression as its pattern, and has no
  1238.      action (so the default action, printing the record, is used).
  1239.  
  1240. `awk 'NF > 0''
  1241.      This program prints every line that has at least one field. 
  1242.      This is an easy way to delete blank lines from a file (or
  1243.      rather, to create a new file similar to the old file but from
  1244.      which the blank lines have been deleted).
  1245.  
  1246. `awk '{ if (NF > 0) print }''
  1247.      This program also prints every line that has at least one field.
  1248.      Here we allow the rule to match every line, then decide in the
  1249.      action whether to print.
  1250.  
  1251. `awk 'BEGIN { for (i = 1; i <= 7; i++)'
  1252. ``              print int(101 * rand()) }'''
  1253.      This program prints 7 random numbers from 0 to 100, inclusive.
  1254.  
  1255. `ls -l FILES | awk '{ x += $4 } ; END { print "total bytes: " x }''
  1256.      This program prints the total number of bytes used by FILES.
  1257.  
  1258. `expand FILE | awk '{ if (x < length()) x = length() }'
  1259. ``                  END { print "maximum line length is " x }'''
  1260.      This program prints the maximum line length of FILE.  The input
  1261.      is piped through the `expand' program to change tabs into
  1262.      spaces, so the widths compared are actually the right--margin
  1263.      columns.
  1264.  
  1265.  
  1266.