home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / gawk-2.15.6-bin.lha / info / gawk.info-2 (.txt) < prev    next >
GNU Info File  |  1996-10-12  |  51KB  |  945 lines

  1. This is Info file gawk.info, produced by Makeinfo-1.55 from the input
  2. file /gnu-src/gawk-2.15.6/gawk.texi.
  3.    This file documents `awk', a program that you can use to select
  4. particular records in a file and perform operations upon them.
  5.    This is Edition 0.15 of `The GAWK Manual',
  6. for the 2.15 version of the GNU implementation
  7. of AWK.
  8.    Copyright (C) 1989, 1991, 1992, 1993 Free Software Foundation, Inc.
  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.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided that
  14. the entire resulting derived work is distributed under the terms of a
  15. permission notice identical to this one.
  16.    Permission is granted to copy and distribute translations of this
  17. manual into another language, under the above conditions for modified
  18. versions, except that this permission notice may be stated in a
  19. translation approved by the Foundation.
  20. File: gawk.info,  Node: Statements/Lines,  Next: When,  Prev: Comments,  Up: Getting Started
  21. `awk' Statements versus Lines
  22. =============================
  23.    Most often, each line in an `awk' program is a separate statement or
  24. separate rule, like this:
  25.      awk '/12/  { print $0 }
  26.           /21/  { print $0 }' BBS-list inventory-shipped
  27.    But sometimes statements can be more than one line, and lines can
  28. contain several statements.  You can split a statement into multiple
  29. lines by inserting a newline after any of the following:
  30.      ,    {    ?    :    ||    &&    do    else
  31. A newline at any other point is considered the end of the statement.
  32. (Splitting lines after `?' and `:' is a minor `gawk' extension.  The
  33. `?' and `:' referred to here is the three operand conditional
  34. expression described in *Note Conditional Expressions: Conditional Exp.)
  35.    If you would like to split a single statement into two lines at a
  36. point where a newline would terminate it, you can "continue" it by
  37. ending the first line with a backslash character, `\'.  This is allowed
  38. absolutely anywhere in the statement, even in the middle of a string or
  39. regular expression.  For example:
  40.      awk '/This program is too long, so continue it\
  41.       on the next line/ { print $1 }'
  42. We have generally not used backslash continuation in the sample
  43. programs in this manual.  Since in `gawk' there is no limit on the
  44. length of a line, it is never strictly necessary; it just makes
  45. programs prettier.  We have preferred to make them even more pretty by
  46. keeping the statements short.  Backslash continuation is most useful
  47. when your `awk' program is in a separate source file, instead of typed
  48. in on the command line.  You should also note that many `awk'
  49. implementations are more picky about where you may use backslash
  50. continuation.  For maximal portability of your `awk' programs, it is
  51. best not to split your lines in the middle of a regular expression or a
  52. string.
  53.    *Warning: backslash continuation does not work as described above
  54. with the C shell.*  Continuation with backslash works for `awk'
  55. programs in files, and also for one-shot programs *provided* you are
  56. using a POSIX-compliant shell, such as the Bourne shell or the
  57. Bourne-again shell.  But the C shell used on Berkeley Unix behaves
  58. differently!  There, you must use two backslashes in a row, followed by
  59. a newline.
  60.    When `awk' statements within one rule are short, you might want to
  61. put more than one of them on a line.  You do this by separating the
  62. statements with a semicolon, `;'.  This also applies to the rules
  63. themselves.  Thus, the previous program could have been written:
  64.      /12/ { print $0 } ; /21/ { print $0 }
  65. *Note:* the requirement that rules on the same line must be separated
  66. with a semicolon is a recent change in the `awk' language; it was done
  67. for consistency with the treatment of statements within an action.
  68. File: gawk.info,  Node: When,  Prev: Statements/Lines,  Up: Getting Started
  69. When to Use `awk'
  70. =================
  71.    You might wonder how `awk' might be useful for you.  Using additional
  72. utility programs, more advanced patterns, field separators, arithmetic
  73. statements, and other selection criteria, you can produce much more
  74. complex output.  The `awk' language is very useful for producing
  75. reports from large amounts of raw data, such as summarizing information
  76. from the output of other utility programs like `ls'.  (*Note A More
  77. Complex Example: More Complex.)
  78.    Programs written with `awk' are usually much smaller than they would
  79. be in other languages.  This makes `awk' programs easy to compose and
  80. use.  Often `awk' programs can be quickly composed at your terminal,
  81. used once, and thrown away.  Since `awk' programs are interpreted, you
  82. can avoid the usually lengthy edit-compile-test-debug cycle of software
  83. development.
  84.    Complex programs have been written in `awk', including a complete
  85. retargetable assembler for 8-bit microprocessors (*note Glossary::., for
  86. more information) and a microcode assembler for a special purpose Prolog
  87. computer.  However, `awk''s capabilities are strained by tasks of such
  88. complexity.
  89.    If you find yourself writing `awk' scripts of more than, say, a few
  90. hundred lines, you might consider using a different programming
  91. language.  Emacs Lisp is a good choice if you need sophisticated string
  92. or pattern matching capabilities.  The shell is also good at string and
  93. pattern matching; in addition, it allows powerful use of the system
  94. utilities.  More conventional languages, such as C, C++, and Lisp, offer
  95. better facilities for system programming and for managing the complexity
  96. of large programs.  Programs in these languages may require more lines
  97. of source code than the equivalent `awk' programs, but they are easier
  98. to maintain and usually run more efficiently.
  99. File: gawk.info,  Node: Reading Files,  Next: Printing,  Prev: Getting Started,  Up: Top
  100. Reading Input Files
  101. *******************
  102.    In the typical `awk' program, all input is read either from the
  103. standard input (by default the keyboard, but often a pipe from another
  104. command) or from files whose names you specify on the `awk' command
  105. line.  If you specify input files, `awk' reads them in order, reading
  106. all the data from one before going on to the next.  The name of the
  107. current input file can be found in the built-in variable `FILENAME'
  108. (*note Built-in Variables::.).
  109.    The input is read in units called records, and processed by the
  110. rules one record at a time.  By default, each record is one line.  Each
  111. record is split automatically into fields, to make it more convenient
  112. for a rule to work on its parts.
  113.    On rare occasions you will need to use the `getline' command, which
  114. can do explicit input from any number of files (*note Explicit Input
  115. with `getline': Getline.).
  116. * Menu:
  117. * Records::                     Controlling how data is split into records.
  118. * Fields::                      An introduction to fields.
  119. * Non-Constant Fields::         Non-constant Field Numbers.
  120. * Changing Fields::             Changing the Contents of a Field.
  121. * Field Separators::            The field separator and how to change it.
  122. * Constant Size::               Reading constant width data.
  123. * Multiple Line::               Reading multi-line records.
  124. * Getline::                     Reading files under explicit program control
  125.                                 using the `getline' function.
  126. * Close Input::                 Closing an input file (so you can read from
  127.                                 the beginning once more).
  128. File: gawk.info,  Node: Records,  Next: Fields,  Prev: Reading Files,  Up: Reading Files
  129. How Input is Split into Records
  130. ===============================
  131.    The `awk' language divides its input into records and fields.
  132. Records are separated by a character called the "record separator".  By
  133. default, the record separator is the newline character, defining a
  134. record to be a single line of text.
  135.    Sometimes you may want to use a different character to separate your
  136. records.  You can use a different character by changing the built-in
  137. variable `RS'.  The value of `RS' is a string that says how to separate
  138. records; the default value is `"\n"', the string containing just a
  139. newline character.  This is why records are, by default, single lines.
  140.    `RS' can have any string as its value, but only the first character
  141. of the string is used as the record separator.  The other characters are
  142. ignored.  `RS' is exceptional in this regard; `awk' uses the full value
  143. of all its other built-in variables.
  144.    You can change the value of `RS' in the `awk' program with the
  145. assignment operator, `=' (*note Assignment Expressions: Assignment
  146. Ops.).  The new record-separator character should be enclosed in
  147. quotation marks to make a string constant.  Often the right time to do
  148. this is at the beginning of execution, before any input has been
  149. processed, so that the very first record will be read with the proper
  150. separator.  To do this, use the special `BEGIN' pattern (*note `BEGIN'
  151. and `END' Special Patterns: BEGIN/END.).  For example:
  152.      awk 'BEGIN { RS = "/" } ; { print $0 }' BBS-list
  153. changes the value of `RS' to `"/"', before reading any input.  This is
  154. a string whose first character is a slash; as a result, records are
  155. separated by slashes.  Then the input file is read, and the second rule
  156. in the `awk' program (the action with no pattern) prints each record.
  157. Since each `print' statement adds a newline at the end of its output,
  158. the effect of this `awk' program is to copy the input with each slash
  159. changed to a newline.
  160.    Another way to change the record separator is on the command line,
  161. using the variable-assignment feature (*note Invoking `awk': Command
  162. Line.).
  163.      awk '{ print $0 }' RS="/" BBS-list
  164. This sets `RS' to `/' before processing `BBS-list'.
  165.    Reaching the end of an input file terminates the current input
  166. record, even if the last character in the file is not the character in
  167. `RS'.
  168.    The empty string, `""' (a string of no characters), has a special
  169. meaning as the value of `RS': it means that records are separated only
  170. by blank lines.  *Note Multiple-Line Records: Multiple Line, for more
  171. details.
  172.    The `awk' utility keeps track of the number of records that have
  173. been read so far from the current input file.  This value is stored in a
  174. built-in variable called `FNR'.  It is reset to zero when a new file is
  175. started.  Another built-in variable, `NR', is the total number of input
  176. records read so far from all files.  It starts at zero but is never
  177. automatically reset to zero.
  178.    If you change the value of `RS' in the middle of an `awk' run, the
  179. new value is used to delimit subsequent records, but the record
  180. currently being processed (and records already processed) are not
  181. affected.
  182. File: gawk.info,  Node: Fields,  Next: Non-Constant Fields,  Prev: Records,  Up: Reading Files
  183. Examining Fields
  184. ================
  185.    When `awk' reads an input record, the record is automatically
  186. separated or "parsed" by the interpreter into chunks called "fields".
  187. By default, fields are separated by whitespace, like words in a line.
  188. Whitespace in `awk' means any string of one or more spaces and/or tabs;
  189. other characters such as newline, formfeed, and so on, that are
  190. considered whitespace by other languages are *not* considered
  191. whitespace by `awk'.
  192.    The purpose of fields is to make it more convenient for you to refer
  193. to these pieces of the record.  You don't have to use them--you can
  194. operate on the whole record if you wish--but fields are what make
  195. simple `awk' programs so powerful.
  196.    To refer to a field in an `awk' program, you use a dollar-sign, `$',
  197. followed by the number of the field you want.  Thus, `$1' refers to the
  198. first field, `$2' to the second, and so on.  For example, suppose the
  199. following is a line of input:
  200.      This seems like a pretty nice example.
  201. Here the first field, or `$1', is `This'; the second field, or `$2', is
  202. `seems'; and so on.  Note that the last field, `$7', is `example.'.
  203. Because there is no space between the `e' and the `.', the period is
  204. considered part of the seventh field.
  205.    No matter how many fields there are, the last field in a record can
  206. be represented by `$NF'.  So, in the example above, `$NF' would be the
  207. same as `$7', which is `example.'.  Why this works is explained below
  208. (*note Non-constant Field Numbers: Non-Constant Fields.).  If you try
  209. to refer to a field beyond the last one, such as `$8' when the record
  210. has only 7 fields, you get the empty string.
  211.    Plain `NF', with no `$', is a built-in variable whose value is the
  212. number of fields in the current record.
  213.    `$0', which looks like an attempt to refer to the zeroth field, is a
  214. special case: it represents the whole input record.  This is what you
  215. would use if you weren't interested in fields.
  216.    Here are some more examples:
  217.      awk '$1 ~ /foo/ { print $0 }' BBS-list
  218. This example prints each record in the file `BBS-list' whose first
  219. field contains the string `foo'.  The operator `~' is called a
  220. "matching operator" (*note Comparison Expressions: Comparison Ops.); it
  221. tests whether a string (here, the field `$1') matches a given regular
  222. expression.
  223.    By contrast, the following example:
  224.      awk '/foo/ { print $1, $NF }' BBS-list
  225. looks for `foo' in *the entire record* and prints the first field and
  226. the last field for each input record containing a match.
  227. File: gawk.info,  Node: Non-Constant Fields,  Next: Changing Fields,  Prev: Fields,  Up: Reading Files
  228. Non-constant Field Numbers
  229. ==========================
  230.    The number of a field does not need to be a constant.  Any
  231. expression in the `awk' language can be used after a `$' to refer to a
  232. field.  The value of the expression specifies the field number.  If the
  233. value is a string, rather than a number, it is converted to a number.
  234. Consider this example:
  235.      awk '{ print $NR }'
  236. Recall that `NR' is the number of records read so far: 1 in the first
  237. record, 2 in the second, etc.  So this example prints the first field
  238. of the first record, the second field of the second record, and so on.
  239. For the twentieth record, field number 20 is printed; most likely, the
  240. record has fewer than 20 fields, so this prints a blank line.
  241.    Here is another example of using expressions as field numbers:
  242.      awk '{ print $(2*2) }' BBS-list
  243.    The `awk' language must evaluate the expression `(2*2)' and use its
  244. value as the number of the field to print.  The `*' sign represents
  245. multiplication, so the expression `2*2' evaluates to 4.  The
  246. parentheses are used so that the multiplication is done before the `$'
  247. operation; they are necessary whenever there is a binary operator in
  248. the field-number expression.  This example, then, prints the hours of
  249. operation (the fourth field) for every line of the file `BBS-list'.
  250.    If the field number you compute is zero, you get the entire record.
  251. Thus, `$(2-2)' has the same value as `$0'.  Negative field numbers are
  252. not allowed.
  253.    The number of fields in the current record is stored in the built-in
  254. variable `NF' (*note Built-in Variables::.).  The expression `$NF' is
  255. not a special feature: it is the direct consequence of evaluating `NF'
  256. and using its value as a field number.
  257. File: gawk.info,  Node: Changing Fields,  Next: Field Separators,  Prev: Non-Constant Fields,  Up: Reading Files
  258. Changing the Contents of a Field
  259. ================================
  260.    You can change the contents of a field as seen by `awk' within an
  261. `awk' program; this changes what `awk' perceives as the current input
  262. record.  (The actual input is untouched: `awk' never modifies the input
  263. file.)
  264.    Consider this example:
  265.      awk '{ $3 = $2 - 10; print $2, $3 }' inventory-shipped
  266. The `-' sign represents subtraction, so this program reassigns field
  267. three, `$3', to be the value of field two minus ten, `$2 - 10'.  (*Note
  268. Arithmetic Operators: Arithmetic Ops.) Then field two, and the new
  269. value for field three, are printed.
  270.    In order for this to work, the text in field `$2' must make sense as
  271. a number; the string of characters must be converted to a number in
  272. order for the computer to do arithmetic on it.  The number resulting
  273. from the subtraction is converted back to a string of characters which
  274. then becomes field three.  *Note Conversion of Strings and Numbers:
  275. Conversion.
  276.    When you change the value of a field (as perceived by `awk'), the
  277. text of the input record is recalculated to contain the new field where
  278. the old one was.  Therefore, `$0' changes to reflect the altered field.
  279. Thus,
  280.      awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
  281. prints a copy of the input file, with 10 subtracted from the second
  282. field of each line.
  283.    You can also assign contents to fields that are out of range.  For
  284. example:
  285.      awk '{ $6 = ($5 + $4 + $3 + $2) ; print $6 }' inventory-shipped
  286. We've just created `$6', whose value is the sum of fields `$2', `$3',
  287. `$4', and `$5'.  The `+' sign represents addition.  For the file
  288. `inventory-shipped', `$6' represents the total number of parcels
  289. shipped for a particular month.
  290.    Creating a new field changes the internal `awk' copy of the current
  291. input record--the value of `$0'.  Thus, if you do `print $0' after
  292. adding a field, the record printed includes the new field, with the
  293. appropriate number of field separators between it and the previously
  294. existing fields.
  295.    This recomputation affects and is affected by several features not
  296. yet discussed, in particular, the "output field separator", `OFS',
  297. which is used to separate the fields (*note Output Separators::.), and
  298. `NF' (the number of fields; *note Examining Fields: Fields.).  For
  299. example, the value of `NF' is set to the number of the highest field
  300. you create.
  301.    Note, however, that merely *referencing* an out-of-range field does
  302. *not* change the value of either `$0' or `NF'.  Referencing an
  303. out-of-range field merely produces a null string.  For example:
  304.      if ($(NF+1) != "")
  305.          print "can't happen"
  306.      else
  307.          print "everything is normal"
  308. should print `everything is normal', because `NF+1' is certain to be
  309. out of range.  (*Note The `if' Statement: If Statement, for more
  310. information about `awk''s `if-else' statements.)
  311.    It is important to note that assigning to a field will change the
  312. value of `$0', but will not change the value of `NF', even when you
  313. assign the null string to a field.  For example:
  314.      echo a b c d | awk '{ OFS = ":"; $2 = "" ; print ; print NF }'
  315. prints
  316.      a::c:d
  317.      4
  318. The field is still there, it just has an empty value.  You can tell
  319. because there are two colons in a row.
  320. File: gawk.info,  Node: Field Separators,  Next: Constant Size,  Prev: Changing Fields,  Up: Reading Files
  321. Specifying how Fields are Separated
  322. ===================================
  323.    (This section is rather long; it describes one of the most
  324. fundamental operations in `awk'.  If you are a novice with `awk', we
  325. recommend that you re-read this section after you have studied the
  326. section on regular expressions, *Note Regular Expressions as Patterns:
  327. Regexp.)
  328.    The way `awk' splits an input record into fields is controlled by
  329. the "field separator", which is a single character or a regular
  330. expression.  `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 `oo', then the following line:
  333.      moo goo gai pan
  334. would be split into three fields: `m', ` g' and ` gai  pan'.
  335.    The field separator is represented by the built-in variable `FS'.
  336. Shell programmers take note!  `awk' does not use the name `IFS' which
  337. is used by the shell.
  338.    You can change the value of `FS' in the `awk' program with the
  339. assignment operator, `=' (*note Assignment Expressions: Assignment
  340. Ops.).  Often the right time to do this is at the beginning of
  341. execution, before any input has been processed, so that the very first
  342. record will be read with the proper separator.  To do this, use the
  343. special `BEGIN' pattern (*note `BEGIN' and `END' Special Patterns:
  344. BEGIN/END.).  For example, here we set the value of `FS' to the string
  345. `","':
  346.      awk 'BEGIN { FS = "," } ; { print $2 }'
  347. Given the input line,
  348.      John Q. Smith, 29 Oak St., Walamazoo, MI 42139
  349. this `awk' program extracts the string ` 29 Oak St.'.
  350.    Sometimes your input data will contain separator characters that
  351. don't separate fields the way you thought they would.  For instance, the
  352. person's name in the example we've been using might have a title or
  353. suffix attached, such as `John Q. Smith, LXIX'.  From input containing
  354. such a name:
  355.      John Q. Smith, LXIX, 29 Oak St., Walamazoo, MI 42139
  356. the previous sample program would extract ` LXIX', instead of ` 29 Oak
  357. St.'.  If you were expecting the program to print the address, you
  358. would be surprised.  So choose your data layout and separator
  359. characters carefully to prevent such problems.
  360.    As you know, by default, fields are separated by whitespace sequences
  361. (spaces and tabs), not by single spaces: two spaces in a row do not
  362. delimit an empty field.  The default value of the field separator is a
  363. string `" "' containing a single space.  If this value were interpreted
  364. in the usual way, each space character would separate fields, so two
  365. spaces in a row would make an empty field between them.  The reason
  366. this does not happen is that a single space as the value of `FS' is a
  367. special case: it is taken to specify the default manner of delimiting
  368. fields.
  369.    If `FS' is any other single character, such as `","', then each
  370. occurrence of that character separates two fields.  Two consecutive
  371. occurrences delimit an empty field.  If the character occurs at the
  372. beginning or the end of the line, that too delimits an empty field.  The
  373. space character is the only single character which does not follow these
  374. rules.
  375.    More generally, the value of `FS' may be a string containing any
  376. regular expression.  Then each match in the record for the regular
  377. expression separates fields.  For example, the assignment:
  378.      FS = ", \t"
  379. makes every area of an input line that consists of a comma followed by a
  380. space and a tab, into a field separator.  (`\t' stands for a tab.)
  381.    For a less trivial example of a regular expression, suppose you want
  382. single spaces to separate fields the way single commas were used above.
  383. You can set `FS' to `"[ ]"'.  This regular expression matches a single
  384. space and nothing else.
  385.    `FS' can be set on the command line.  You use the `-F' argument to
  386. do so.  For example:
  387.      awk -F, 'PROGRAM' INPUT-FILES
  388. sets `FS' to be the `,' character.  Notice that the argument uses a
  389. capital `F'.  Contrast this with `-f', which specifies a file
  390. containing an `awk' program.  Case is significant in command options:
  391. the `-F' and `-f' options have nothing to do with each other.  You can
  392. use both options at the same time to set the `FS' argument *and* get an
  393. `awk' program from a file.
  394.    The value used for the argument to `-F' is processed in exactly the
  395. same way as assignments to the built-in variable `FS'.  This means that
  396. if the field separator contains special characters, they must be escaped
  397. appropriately.  For example, to use a `\' as the field separator, you
  398. would have to type:
  399.      # same as FS = "\\"
  400.      awk -F\\\\ '...' files ...
  401. Since `\' is used for quoting in the shell, `awk' will see `-F\\'.
  402. Then `awk' processes the `\\' for escape characters (*note Constant
  403. Expressions: Constants.), finally yielding a single `\' to be used for
  404. the field separator.
  405.    As a special case, in compatibility mode (*note Invoking `awk':
  406. Command Line.), if the argument to `-F' is `t', then `FS' is set to the
  407. tab character.  (This is because if you type `-F\t', without the quotes,
  408. at the shell, the `\' gets deleted, so `awk' figures that you really
  409. want your fields to be separated with tabs, and not `t's.  Use `-v
  410. FS="t"' on the command line if you really do want to separate your
  411. fields with `t's.)
  412.    For example, let's use an `awk' program file called `baud.awk' that
  413. contains the pattern `/300/', and the action `print $1'.  Here is the
  414. program:
  415.      /300/   { print $1 }
  416.    Let's also set `FS' to be the `-' character, and run the program on
  417. the file `BBS-list'.  The following command prints a list of the names
  418. of the bulletin boards that operate at 300 baud and the first three
  419. digits of their phone numbers:
  420.      awk -F- -f baud.awk BBS-list
  421. It produces this output:
  422.      aardvark     555
  423.      alpo
  424.      barfly       555
  425.      bites        555
  426.      camelot      555
  427.      core         555
  428.      fooey        555
  429.      foot         555
  430.      macfoo       555
  431.      sdace        555
  432.      sabafoo      555
  433. Note the second line of output.  If you check the original file, you
  434. will see that the second line looked like this:
  435.      alpo-net     555-3412     2400/1200/300     A
  436.    The `-' as part of the system's name was used as the field
  437. separator, instead of the `-' in the phone number that was originally
  438. intended.  This demonstrates why you have to be careful in choosing
  439. your field and record separators.
  440.    The following program searches the system password file, and prints
  441. the entries for users who have no password:
  442.      awk -F: '$2 == ""' /etc/passwd
  443. Here we use the `-F' option on the command line to set the field
  444. separator.  Note that fields in `/etc/passwd' are separated by colons.
  445. The second field represents a user's encrypted password, but if the
  446. field is empty, that user has no password.
  447.    According to the POSIX standard, `awk' is supposed to behave as if
  448. each record is split into fields at the time that it is read.  In
  449. particular, this means that you can change the value of `FS' after a
  450. record is read, but before any of the fields are referenced.  The value
  451. of the fields (i.e. how they were split) should reflect the old value
  452. of `FS', not the new one.
  453.    However, many implementations of `awk' do not do this.  Instead,
  454. they defer splitting the fields until a field reference actually
  455. happens, using the *current* value of `FS'!  This behavior can be
  456. difficult to diagnose. The following example illustrates the results of
  457. the two methods.  (The `sed' command prints just the first line of
  458. `/etc/passwd'.)
  459.      sed 1q /etc/passwd | awk '{ FS = ":" ; print $1 }'
  460. will usually print
  461.      root
  462. on an incorrect implementation of `awk', while `gawk' will print
  463. something like
  464.      root:nSijPlPhZZwgE:0:0:Root:/:
  465.    There is an important difference between the two cases of `FS = " "'
  466. (a single blank) and `FS = "[ \t]+"' (which is a regular expression
  467. matching one or more blanks or tabs).  For both values of `FS', fields
  468. are separated by runs of blanks and/or tabs.  However, when the value of
  469. `FS' is `" "', `awk' will strip leading and trailing whitespace from
  470. the record, and then decide where the fields are.
  471.    For example, the following expression prints `b':
  472.      echo ' a b c d ' | awk '{ print $2 }'
  473. However, the following prints `a':
  474.      echo ' a b c d ' | awk 'BEGIN { FS = "[ \t]+" } ; { print $2 }'
  475. In this case, the first field is null.
  476.    The stripping of leading and trailing whitespace also comes into
  477. play whenever `$0' is recomputed.  For instance, this pipeline
  478.      echo '   a b c d' | awk '{ print; $2 = $2; print }'
  479. produces this output:
  480.         a b c d
  481.      a b c d
  482. The first `print' statement prints the record as it was read, with
  483. leading whitespace intact.  The assignment to `$2' rebuilds `$0' by
  484. concatenating `$1' through `$NF' together, separated by the value of
  485. `OFS'.  Since the leading whitespace was ignored when finding `$1', it
  486. is not part of the new `$0'.  Finally, the last `print' statement
  487. prints the new `$0'.
  488.    The following table summarizes how fields are split, based on the
  489. value of `FS'.
  490. `FS == " "'
  491.      Fields are separated by runs of whitespace.  Leading and trailing
  492.      whitespace are ignored.  This is the default.
  493. `FS == ANY SINGLE CHARACTER'
  494.      Fields are separated by each occurrence of the character.  Multiple
  495.      successive occurrences delimit empty fields, as do leading and
  496.      trailing occurrences.
  497. `FS == REGEXP'
  498.      Fields are separated by occurrences of characters that match
  499.      REGEXP.  Leading and trailing matches of REGEXP delimit empty
  500.      fields.
  501. File: gawk.info,  Node: Constant Size,  Next: Multiple Line,  Prev: Field Separators,  Up: Reading Files
  502. Reading Fixed-width Data
  503. ========================
  504.    (This section discusses an advanced, experimental feature.  If you
  505. are a novice `awk' user, you may wish to skip it on the first reading.)
  506.    `gawk' 2.13 introduced a new facility for dealing with fixed-width
  507. fields with no distinctive field separator.  Data of this nature arises
  508. typically in one of at least two ways:  the input for old FORTRAN
  509. programs where numbers are run together, and the output of programs
  510. that did not anticipate the use of their output as input for other
  511. programs.
  512.    An example of the latter is a table where all the columns are lined
  513. up by the use of a variable number of spaces and *empty fields are just
  514. spaces*.  Clearly, `awk''s normal field splitting based on `FS' will
  515. not work well in this case.  (Although a portable `awk' program can use
  516. a series of `substr' calls on `$0', this is awkward and inefficient for
  517. a large number of fields.)
  518.    The splitting of an input record into fixed-width fields is
  519. specified by assigning a string containing space-separated numbers to
  520. the built-in variable `FIELDWIDTHS'.  Each number specifies the width
  521. of the field *including* columns between fields.  If you want to ignore
  522. the columns between fields, you can specify the width as a separate
  523. field that is subsequently ignored.
  524.    The following data is the output of the `w' utility.  It is useful
  525. to illustrate the use of `FIELDWIDTHS'.
  526.       10:06pm  up 21 days, 14:04,  23 users
  527.      User     tty       login  idle   JCPU   PCPU  what
  528.      hzuo     ttyV0     8:58pm            9      5  vi p24.tex
  529.      hzang    ttyV3     6:37pm    50                -csh
  530.      eklye    ttyV5     9:53pm            7      1  em thes.tex
  531.      dportein ttyV6     8:17pm  1:47                -csh
  532.      gierd    ttyD3    10:00pm     1                elm
  533.      dave     ttyD4     9:47pm            4      4  w
  534.      brent    ttyp0    26Jun91  4:46  26:46   4:41  bash
  535.      dave     ttyq4    26Jun9115days     46     46  wnewmail
  536.    The following program takes the above input, converts the idle time
  537. to number of seconds and prints out the first two fields and the
  538. calculated idle time.  (This program uses a number of `awk' features
  539. that haven't been introduced yet.)
  540.      BEGIN  { FIELDWIDTHS = "9 6 10 6 7 7 35" }
  541.      NR > 2 {
  542.          idle = $4
  543.          sub(/^  */, "", idle)   # strip leading spaces
  544.          if (idle == "") idle = 0
  545.          if (idle ~ /:/) { split(idle, t, ":"); idle = t[1] * 60 + t[2] }
  546.          if (idle ~ /days/) { idle *= 24 * 60 * 60 }
  547.      
  548.          print $1, $2, idle
  549.      }
  550.    Here is the result of running the program on the data:
  551.      hzuo      ttyV0  0
  552.      hzang     ttyV3  50
  553.      eklye     ttyV5  0
  554.      dportein  ttyV6  107
  555.      gierd     ttyD3  1
  556.      dave      ttyD4  0
  557.      brent     ttyp0  286
  558.      dave      ttyq4  1296000
  559.    Another (possibly more practical) example of fixed-width input data
  560. would be the input from a deck of balloting cards.  In some parts of
  561. the United States, voters make their choices by punching holes in
  562. computer cards.  These cards are then processed to count the votes for
  563. any particular candidate or on any particular issue.  Since a voter may
  564. choose not to vote on some issue, any column on the card may be empty.
  565. An `awk' program for processing such data could use the `FIELDWIDTHS'
  566. feature to simplify reading the data.
  567.    This feature is still experimental, and will likely evolve over time.
  568. File: gawk.info,  Node: Multiple Line,  Next: Getline,  Prev: Constant Size,  Up: Reading Files
  569. Multiple-Line Records
  570. =====================
  571.    In some data bases, a single line cannot conveniently hold all the
  572. information in one entry.  In such cases, you can use multi-line
  573. records.
  574.    The first step in doing this is to choose your data format: when
  575. records are not defined as single lines, how do you want to define them?
  576. What should separate records?
  577.    One technique is to use an unusual character or string to separate
  578. records.  For example, you could use the formfeed character (written
  579. `\f' in `awk', as in C) to separate them, making each record a page of
  580. the file.  To do this, just set the variable `RS' to `"\f"' (a string
  581. containing the formfeed character).  Any other character could equally
  582. well be used, as long as it won't be part of the data in a record.
  583.    Another technique is to have blank lines separate records.  By a
  584. special dispensation, a null string as the value of `RS' indicates that
  585. records are separated by one or more blank lines.  If you set `RS' to
  586. the null string, a record always ends at the first blank line
  587. encountered.  And the next record doesn't start until the first nonblank
  588. line that follows--no matter how many blank lines appear in a row, they
  589. are considered one record-separator. (End of file is also considered a
  590. record separator.)
  591.    The second step is to separate the fields in the record.  One way to
  592. do this is to put each field on a separate line: to do this, just set
  593. the variable `FS' to the string `"\n"'.  (This simple regular
  594. expression matches a single newline.)
  595.    Another way to separate fields is to divide each of the lines into
  596. fields in the normal manner.  This happens by default as a result of a
  597. special feature: when `RS' is set to the null string, the newline
  598. character *always* acts as a field separator.  This is in addition to
  599. whatever field separations result from `FS'.
  600.    The original motivation for this special exception was probably so
  601. that you get useful behavior in the default case (i.e., `FS == " "').
  602. This feature can be a problem if you really don't want the newline
  603. character to separate fields, since there is no way to prevent it.
  604. However, you can work around this by using the `split' function to
  605. break up the record manually (*note Built-in Functions for String
  606. Manipulation: String Functions.).
  607. File: gawk.info,  Node: Getline,  Next: Close Input,  Prev: Multiple Line,  Up: Reading Files
  608. Explicit Input with `getline'
  609. =============================
  610.    So far we have been getting our input files from `awk''s main input
  611. stream--either the standard input (usually your terminal) or the files
  612. specified on the command line.  The `awk' language has a special
  613. built-in command called `getline' that can be used to read input under
  614. your explicit control.
  615.    This command is quite complex and should *not* be used by beginners.
  616. It is covered here because this is the chapter on input.  The examples
  617. that follow the explanation of the `getline' command include material
  618. that has not been covered yet.  Therefore, come back and study the
  619. `getline' command *after* you have reviewed the rest of this manual and
  620. have a good knowledge of how `awk' works.
  621.    `getline' returns 1 if it finds a record, and 0 if the end of the
  622. file is encountered.  If there is some error in getting a record, such
  623. as a file that cannot be opened, then `getline' returns -1.  In this
  624. case, `gawk' sets the variable `ERRNO' to a string describing the error
  625. that occurred.
  626.    In the following examples, COMMAND stands for a string value that
  627. represents a shell command.
  628. `getline'
  629.      The `getline' command can be used without arguments to read input
  630.      from the current input file.  All it does in this case is read the
  631.      next input record and split it up into fields.  This is useful if
  632.      you've finished processing the current record, but you want to do
  633.      some special processing *right now* on the next record.  Here's an
  634.      example:
  635.           awk '{
  636.                if (t = index($0, "/*")) {
  637.                     if (t > 1)
  638.                          tmp = substr($0, 1, t - 1)
  639.                     else
  640.                          tmp = ""
  641.                     u = index(substr($0, t + 2), "*/")
  642.                     while (u == 0) {
  643.                          getline
  644.                          t = -1
  645.                          u = index($0, "*/")
  646.                     }
  647.                     if (u <= length($0) - 2)
  648.                          $0 = tmp substr($0, t + u + 3)
  649.                     else
  650.                          $0 = tmp
  651.                }
  652.                print $0
  653.           }'
  654.      This `awk' program deletes all C-style comments, `/* ...  */',
  655.      from the input.  By replacing the `print $0' with other
  656.      statements, you could perform more complicated processing on the
  657.      decommented input, like searching for matches of a regular
  658.      expression.  (This program has a subtle problem--can you spot it?)
  659.      This form of the `getline' command sets `NF' (the number of
  660.      fields; *note Examining Fields: Fields.), `NR' (the number of
  661.      records read so far; *note How Input is Split into Records:
  662.      Records.), `FNR' (the number of records read from this input
  663.      file), and the value of `$0'.
  664.      *Note:* the new value of `$0' is used in testing the patterns of
  665.      any subsequent rules.  The original value of `$0' that triggered
  666.      the rule which executed `getline' is lost.  By contrast, the
  667.      `next' statement reads a new record but immediately begins
  668.      processing it normally, starting with the first rule in the
  669.      program.  *Note The `next' Statement: Next Statement.
  670. `getline VAR'
  671.      This form of `getline' reads a record into the variable VAR.  This
  672.      is useful when you want your program to read the next record from
  673.      the current input file, but you don't want to subject the record
  674.      to the normal input processing.
  675.      For example, suppose the next line is a comment, or a special
  676.      string, and you want to read it, but you must make certain that it
  677.      won't trigger any rules.  This version of `getline' allows you to
  678.      read that line and store it in a variable so that the main
  679.      read-a-line-and-check-each-rule loop of `awk' never sees it.
  680.      The following example swaps every two lines of input.  For
  681.      example, given:
  682.           wan
  683.           tew
  684.           free
  685.           phore
  686.      it outputs:
  687.           tew
  688.           wan
  689.           phore
  690.           free
  691.      Here's the program:
  692.           awk '{
  693.                if ((getline tmp) > 0) {
  694.                     print tmp
  695.                     print $0
  696.                } else
  697.                     print $0
  698.           }'
  699.      The `getline' function used in this way sets only the variables
  700.      `NR' and `FNR' (and of course, VAR).  The record is not split into
  701.      fields, so the values of the fields (including `$0') and the value
  702.      of `NF' do not change.
  703. `getline < FILE'
  704.      This form of the `getline' function takes its input from the file
  705.      FILE.  Here FILE is a string-valued expression that specifies the
  706.      file name.  `< FILE' is called a "redirection" since it directs
  707.      input to come from a different place.
  708.      This form is useful if you want to read your input from a
  709.      particular file, instead of from the main input stream.  For
  710.      example, the following program reads its input record from the
  711.      file `foo.input' when it encounters a first field with a value
  712.      equal to 10 in the current input file.
  713.           awk '{
  714.               if ($1 == 10) {
  715.                    getline < "foo.input"
  716.                    print
  717.               } else
  718.                    print
  719.           }'
  720.      Since the main input stream is not used, the values of `NR' and
  721.      `FNR' are not changed.  But the record read is split into fields in
  722.      the normal manner, so the values of `$0' and other fields are
  723.      changed.  So is the value of `NF'.
  724.      This does not cause the record to be tested against all the
  725.      patterns in the `awk' program, in the way that would happen if the
  726.      record were read normally by the main processing loop of `awk'.
  727.      However the new record is tested against any subsequent rules,
  728.      just as when `getline' is used without a redirection.
  729. `getline VAR < FILE'
  730.      This form of the `getline' function takes its input from the file
  731.      FILE and puts it in the variable VAR.  As above, FILE is a
  732.      string-valued expression that specifies the file from which to
  733.      read.
  734.      In this version of `getline', none of the built-in variables are
  735.      changed, and the record is not split into fields.  The only
  736.      variable changed is VAR.
  737.      For example, the following program copies all the input files to
  738.      the output, except for records that say `@include FILENAME'.  Such
  739.      a record is replaced by the contents of the file FILENAME.
  740.           awk '{
  741.                if (NF == 2 && $1 == "@include") {
  742.                     while ((getline line < $2) > 0)
  743.                          print line
  744.                     close($2)
  745.                } else
  746.                     print
  747.           }'
  748.      Note here how the name of the extra input file is not built into
  749.      the program; it is taken from the data, from the second field on
  750.      the `@include' line.
  751.      The `close' function is called to ensure that if two identical
  752.      `@include' lines appear in the input, the entire specified file is
  753.      included twice.  *Note Closing Input Files and Pipes: Close Input.
  754.      One deficiency of this program is that it does not process nested
  755.      `@include' statements the way a true macro preprocessor would.
  756. `COMMAND | getline'
  757.      You can "pipe" the output of a command into `getline'.  A pipe is
  758.      simply a way to link the output of one program to the input of
  759.      another.  In this case, the string COMMAND is run as a shell
  760.      command and its output is piped into `awk' to be used as input.
  761.      This form of `getline' reads one record from the pipe.
  762.      For example, the following program copies input to output, except
  763.      for lines that begin with `@execute', which are replaced by the
  764.      output produced by running the rest of the line as a shell command:
  765.           awk '{
  766.                if ($1 == "@execute") {
  767.                     tmp = substr($0, 10)
  768.                     while ((tmp | getline) > 0)
  769.                          print
  770.                     close(tmp)
  771.                } else
  772.                     print
  773.           }'
  774.      The `close' function is called to ensure that if two identical
  775.      `@execute' lines appear in the input, the command is run for each
  776.      one.  *Note Closing Input Files and Pipes: Close Input.
  777.      Given the input:
  778.           foo
  779.           bar
  780.           baz
  781.           @execute who
  782.           bletch
  783.      the program might produce:
  784.           foo
  785.           bar
  786.           baz
  787.           hack     ttyv0   Jul 13 14:22
  788.           hack     ttyp0   Jul 13 14:23     (gnu:0)
  789.           hack     ttyp1   Jul 13 14:23     (gnu:0)
  790.           hack     ttyp2   Jul 13 14:23     (gnu:0)
  791.           hack     ttyp3   Jul 13 14:23     (gnu:0)
  792.           bletch
  793.      Notice that this program ran the command `who' and printed the
  794.      result.  (If you try this program yourself, you will get different
  795.      results, showing you who is logged in on your system.)
  796.      This variation of `getline' splits the record into fields, sets the
  797.      value of `NF' and recomputes the value of `$0'.  The values of
  798.      `NR' and `FNR' are not changed.
  799. `COMMAND | getline VAR'
  800.      The output of the command COMMAND is sent through a pipe to
  801.      `getline' and into the variable VAR.  For example, the following
  802.      program reads the current date and time into the variable
  803.      `current_time', using the `date' utility, and then prints it.
  804.           awk 'BEGIN {
  805.                "date" | getline current_time
  806.                close("date")
  807.                print "Report printed on " current_time
  808.           }'
  809.      In this version of `getline', none of the built-in variables are
  810.      changed, and the record is not split into fields.
  811. File: gawk.info,  Node: Close Input,  Prev: Getline,  Up: Reading Files
  812. Closing Input Files and Pipes
  813. =============================
  814.    If the same file name or the same shell command is used with
  815. `getline' more than once during the execution of an `awk' program, the
  816. file is opened (or the command is executed) only the first time.  At
  817. that time, the first record of input is read from that file or command.
  818. The next time the same file or command is used in `getline', another
  819. record is read from it, and so on.
  820.    This implies that if you want to start reading the same file again
  821. from the beginning, or if you want to rerun a shell command (rather than
  822. reading more output from the command), you must take special steps.
  823. What you must do is use the `close' function, as follows:
  824.      close(FILENAME)
  825.      close(COMMAND)
  826.    The argument FILENAME or COMMAND can be any expression.  Its value
  827. must exactly equal the string that was used to open the file or start
  828. the command--for example, if you open a pipe with this:
  829.      "sort -r names" | getline foo
  830. then you must close it with this:
  831.      close("sort -r names")
  832.    Once this function call is executed, the next `getline' from that
  833. file or command will reopen the file or rerun the command.
  834.    `close' returns a value of zero if the close succeeded.  Otherwise,
  835. the value will be non-zero.  In this case, `gawk' sets the variable
  836. `ERRNO' to a string describing the error that occurred.
  837. File: gawk.info,  Node: Printing,  Next: One-liners,  Prev: Reading Files,  Up: Top
  838. Printing Output
  839. ***************
  840.    One of the most common things that actions do is to output or "print"
  841. some or all of the input.  For simple output, use the `print'
  842. statement.  For fancier formatting use the `printf' statement.  Both
  843. are described in this chapter.
  844. * Menu:
  845. * Print::                       The `print' statement.
  846. * Print Examples::              Simple examples of `print' statements.
  847. * Output Separators::           The output separators and how to change them.
  848. * OFMT::                        Controlling Numeric Output With `print'.
  849. * Printf::                      The `printf' statement.
  850. * Redirection::                 How to redirect output to multiple
  851.                                 files and pipes.
  852. * Special Files::               File name interpretation in `gawk'.
  853.                                 `gawk' allows access to
  854.                                 inherited file descriptors.
  855. File: gawk.info,  Node: Print,  Next: Print Examples,  Prev: Printing,  Up: Printing
  856. The `print' Statement
  857. =====================
  858.    The `print' statement does output with simple, standardized
  859. formatting.  You specify only the strings or numbers to be printed, in a
  860. list separated by commas.  They are output, separated by single spaces,
  861. followed by a newline.  The statement looks like this:
  862.      print ITEM1, ITEM2, ...
  863. The entire list of items may optionally be enclosed in parentheses.  The
  864. parentheses are necessary if any of the item expressions uses a
  865. relational operator; otherwise it could be confused with a redirection
  866. (*note Redirecting Output of `print' and `printf': Redirection.).  The
  867. relational operators are `==', `!=', `<', `>', `>=', `<=', `~' and `!~'
  868. (*note Comparison Expressions: Comparison Ops.).
  869.    The items printed can be constant strings or numbers, fields of the
  870. current record (such as `$1'), variables, or any `awk' expressions.
  871. The `print' statement is completely general for computing *what* values
  872. to print.  With two exceptions, you cannot specify *how* to print
  873. them--how many columns, whether to use exponential notation or not, and
  874. so on.  (*Note Output Separators::, and *Note Controlling Numeric
  875. Output with `print': OFMT.) For that, you need the `printf' statement
  876. (*note Using `printf' Statements for Fancier Printing: Printf.).
  877.    The simple statement `print' with no items is equivalent to `print
  878. $0': it prints the entire current record.  To print a blank line, use
  879. `print ""', where `""' is the null, or empty, string.
  880.    To print a fixed piece of text, use a string constant such as
  881. `"Hello there"' as one item.  If you forget to use the double-quote
  882. characters, your text will be taken as an `awk' expression, and you
  883. will probably get an error.  Keep in mind that a space is printed
  884. between any two items.
  885.    Most often, each `print' statement makes one line of output.  But it
  886. isn't limited to one line.  If an item value is a string that contains a
  887. newline, the newline is output along with the rest of the string.  A
  888. single `print' can make any number of lines this way.
  889. File: gawk.info,  Node: Print Examples,  Next: Output Separators,  Prev: Print,  Up: Printing
  890. Examples of `print' Statements
  891. ==============================
  892.    Here is an example of printing a string that contains embedded
  893. newlines:
  894.      awk 'BEGIN { print "line one\nline two\nline three" }'
  895. produces output like this:
  896.      line one
  897.      line two
  898.      line three
  899.    Here is an example that prints the first two fields of each input
  900. record, with a space between them:
  901.      awk '{ print $1, $2 }' inventory-shipped
  902. Its output looks like this:
  903.      Jan 13
  904.      Feb 15
  905.      Mar 15
  906.      ...
  907.    A common mistake in using the `print' statement is to omit the comma
  908. between two items.  This often has the effect of making the items run
  909. together in the output, with no space.  The reason for this is that
  910. juxtaposing two string expressions in `awk' means to concatenate them.
  911. For example, without the comma:
  912.      awk '{ print $1 $2 }' inventory-shipped
  913. prints:
  914.      Jan13
  915.      Feb15
  916.      Mar15
  917.      ...
  918.    Neither example's output makes much sense to someone unfamiliar with
  919. the file `inventory-shipped'.  A heading line at the beginning would
  920. make it clearer.  Let's add some headings to our table of months (`$1')
  921. and green crates shipped (`$2').  We do this using the `BEGIN' pattern
  922. (*note `BEGIN' and `END' Special Patterns: BEGIN/END.) to force the
  923. headings to be printed only once:
  924.      awk 'BEGIN {  print "Month Crates"
  925.                    print "----- ------" }
  926.                 {  print $1, $2 }' inventory-shipped
  927. Did you already guess what happens?  This program prints the following:
  928.      Month Crates
  929.      ----- ------
  930.      Jan 13
  931.      Feb 15
  932.      Mar 15
  933.      ...
  934. The headings and the table data don't line up!  We can fix this by
  935. printing some spaces between the two fields:
  936.      awk 'BEGIN { print "Month Crates"
  937.                   print "----- ------" }
  938.                 { print $1, "     ", $2 }' inventory-shipped
  939.    You can imagine that this way of lining up columns can get pretty
  940. complicated when you have many columns to fix.  Counting spaces for two
  941. or three columns can be simple, but more than this and you can get
  942. "lost" quite easily.  This is why the `printf' statement was created
  943. (*note Using `printf' Statements for Fancier Printing: Printf.); one of
  944. its specialties is lining up columns of data.
  945.