home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume22 / gawk2.11 / part05 / gawk.texinfo.02 next >
Text File  |  1990-06-07  |  50KB  |  1,375 lines

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