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

  1.              printf format, "----", "------" @}
  2.      @{ printf format, $1, $2 @}' BBS-list
  3. @end example
  4.  
  5. See if you can use the @code{printf} statement to line up the headings and
  6. table data for our @file{inventory-shipped} example covered earlier in the
  7. section on the @code{print} statement (@pxref{Print}).
  8.  
  9. @node Redirection, Special Files, Printf, Printing
  10. @section Redirecting Output of @code{print} and @code{printf}
  11.  
  12. @cindex output redirection
  13. @cindex redirection of output
  14. So far we have been dealing only with output that prints to the standard
  15. output, usually your terminal.  Both @code{print} and @code{printf} can be
  16. told to send their output to other places.  This is called
  17. @dfn{redirection}.@refill
  18.  
  19. A redirection appears after the @code{print} or @code{printf} statement.
  20. Redirections in @code{awk} are written just like redirections in shell
  21. commands, except that they are written inside the @code{awk} program.
  22.  
  23. @menu
  24. * File/Pipe Redirection::       Redirecting Output to Files and Pipes.
  25. * Close Output::                How to close output files and pipes.
  26. @end menu
  27.  
  28. @node File/Pipe Redirection, Close Output, Redirection, Redirection
  29. @subsection Redirecting Output to Files and Pipes
  30.  
  31. Here are the three forms of output redirection.  They are all shown for
  32. the @code{print} statement, but they work identically for @code{printf}
  33. also.
  34.  
  35. @table @code
  36. @item print @var{items} > @var{output-file}
  37. This type of redirection prints the items onto the output file
  38. @var{output-file}.  The file name @var{output-file} can be any
  39. expression.  Its value is changed to a string and then used as a
  40. file name (@pxref{Expressions}).@refill
  41.  
  42. When this type of redirection is used, the @var{output-file} is erased
  43. before the first output is written to it.  Subsequent writes do not
  44. erase @var{output-file}, but append to it.  If @var{output-file} does
  45. not exist, then it is created.@refill
  46.  
  47. For example, here is how one @code{awk} program can write a list of
  48. BBS names to a file @file{name-list} and a list of phone numbers to a
  49. file @file{phone-list}.  Each output file contains one name or number
  50. per line.
  51.  
  52. @example
  53. awk '@{ print $2 > "phone-list"
  54.        print $1 > "name-list" @}' BBS-list
  55. @end example
  56.  
  57. @item print @var{items} >> @var{output-file}
  58. This type of redirection prints the items onto the output file
  59. @var{output-file}.  The difference between this and the
  60. single-@samp{>} redirection is that the old contents (if any) of
  61. @var{output-file} are not erased.  Instead, the @code{awk} output is
  62. appended to the file.
  63.  
  64. @cindex pipes for output
  65. @cindex output, piping
  66. @item print @var{items} | @var{command}
  67. It is also possible to send output through a @dfn{pipe} instead of into a
  68. file.   This type of redirection opens a pipe to @var{command} and writes
  69. the values of @var{items} through this pipe, to another process created
  70. to execute @var{command}.@refill
  71.  
  72. The redirection argument @var{command} is actually an @code{awk}
  73. expression.  Its value is converted to a string, whose contents give the
  74. shell command to be run.
  75.  
  76. For example, this produces two files, one unsorted list of BBS names
  77. and one list sorted in reverse alphabetical order:
  78.  
  79. @example
  80. awk '@{ print $1 > "names.unsorted"
  81.        print $1 | "sort -r > names.sorted" @}' BBS-list
  82. @end example
  83.  
  84. Here the unsorted list is written with an ordinary redirection while
  85. the sorted list is written by piping through the @code{sort} utility.
  86.  
  87. Here is an example that uses redirection to mail a message to a mailing
  88. list @samp{bug-system}.  This might be useful when trouble is encountered
  89. in an @code{awk} script run periodically for system maintenance.
  90.  
  91. @example
  92. print "Awk script failed:", $0 | "mail bug-system"
  93. print "at record number", FNR, "of", FILENAME  | "mail bug-system"
  94. close("mail bug-system")
  95. @end example
  96.  
  97. We call the @code{close} function here because it's a good idea to close
  98. the pipe as soon as all the intended output has been sent to it.
  99. @xref{Close Output}, for more information on this.
  100. @end table
  101.  
  102. Redirecting output using @samp{>}, @samp{>>}, or @samp{|} asks the system
  103. to open a file or pipe only if the particular @var{file} or @var{command}
  104. you've specified has not already been written to by your program.@refill
  105.  
  106. @node Close Output, , File/Pipe Redirection, Redirection
  107. @subsection Closing Output Files and Pipes
  108. @cindex closing output files and pipes
  109. @findex close
  110.  
  111. When a file or pipe is opened, the file name or command associated with
  112. it is remembered by @code{awk} and subsequent writes to the same file or
  113. command are appended to the previous writes.  The file or pipe stays
  114. open until @code{awk} exits.  This is usually convenient.
  115.  
  116. Sometimes there is a reason to close an output file or pipe earlier
  117. than that.  To do this, use the @code{close} function, as follows:
  118.  
  119. @example
  120. close(@var{filename})
  121. @end example
  122.  
  123. @noindent
  124. or
  125.  
  126. @example
  127. close(@var{command})
  128. @end example
  129.  
  130. The argument @var{filename} or @var{command} can be any expression.
  131. Its value must exactly equal the string used to open the file or pipe
  132. to begin with---for example, if you open a pipe with this:
  133.  
  134. @example
  135. print $1 | "sort -r > names.sorted"
  136. @end example
  137.  
  138. @noindent
  139. then you must close it with this:
  140.  
  141. @example
  142. close("sort -r > names.sorted")
  143. @end example
  144.  
  145. Here are some reasons why you might need to close an output file:
  146.  
  147. @itemize @bullet
  148. @item
  149. To write a file and read it back later on in the same @code{awk}
  150. program.  Close the file when you are finished writing it; then
  151. you can start reading it with @code{getline} (@pxref{Getline}).
  152.  
  153. @item
  154. To write numerous files, successively, in the same @code{awk}
  155. program.  If you don't close the files, eventually you will exceed the
  156. system limit on the number of open files in one process.  So close
  157. each one when you are finished writing it.
  158.  
  159. @item
  160. To make a command finish.  When you redirect output through a pipe,
  161. the command reading the pipe normally continues to try to read input
  162. as long as the pipe is open.  Often this means the command cannot
  163. really do its work until the pipe is closed.  For example, if you
  164. redirect output to the @code{mail} program, the message is not
  165. actually sent until the pipe is closed.
  166.  
  167. @item
  168. To run the same program a second time, with the same arguments.
  169. This is not the same thing as giving more input to the first run!
  170.  
  171. For example, suppose you pipe output to the @code{mail} program.  If you
  172. output several lines redirected to this pipe without closing it, they make
  173. a single message of several lines.  By contrast, if you close the pipe
  174. after each line of output, then each line makes a separate message.
  175. @end itemize
  176.  
  177. @node Special Files, , Redirection, Printing
  178. @section Standard I/O Streams
  179. @cindex standard input
  180. @cindex standard output
  181. @cindex standard error output
  182. @cindex file descriptors
  183.  
  184. Running programs conventionally have three input and output streams
  185. already available to them for reading and writing.  These are known as
  186. the @dfn{standard input}, @dfn{standard output}, and @dfn{standard error
  187. output}.  These streams are, by default, terminal input and output, but
  188. they are often redirected with the shell, via the @samp{<}, @samp{<<},
  189. @samp{>}, @samp{>>}, @samp{>&} and @samp{|} operators.  Standard error
  190. is used only for writing error messages; the reason we have two separate
  191. streams, standard output and standard error, is so that they can be
  192. redirected separately.
  193.  
  194. @c @cindex differences between @code{gawk} and @code{awk}
  195. In other implementations of @code{awk}, the only way to write an error
  196. message to standard error in an @code{awk} program is as follows:
  197.  
  198. @example
  199. print "Serious error detected!\n" | "cat 1>&2"
  200. @end example
  201.  
  202. @noindent
  203. This works by opening a pipeline to a shell command which can access the
  204. standard error stream which it inherits from the @code{awk} process.
  205. This is far from elegant, and is also inefficient, since it requires a
  206. separate process.  So people writing @code{awk} programs have often
  207. neglected to do this.  Instead, they have sent the error messages to the
  208. terminal, like this:
  209.  
  210. @example
  211. NF != 4 @{
  212.    printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/tty"
  213. @}
  214. @end example
  215.  
  216. @noindent
  217. This has the same effect most of the time, but not always: although the
  218. standard error stream is usually the terminal, it can be redirected, and
  219. when that happens, writing to the terminal is not correct.  In fact, if
  220. @code{awk} is run from a background job, it may not have a terminal at all.
  221. Then opening @file{/dev/tty} will fail.
  222.  
  223. @code{gawk} provides special file names for accessing the three standard
  224. streams.  When you redirect input or output in @code{gawk}, if the file name
  225. matches one of these special names, then @code{gawk} directly uses the
  226. stream it stands for.
  227.  
  228. @cindex @file{/dev/stdin}
  229. @cindex @file{/dev/stdout}
  230. @cindex @file{/dev/stderr}
  231. @cindex @file{/dev/fd/}
  232. @table @file
  233. @item /dev/stdin
  234. The standard input (file descriptor 0).
  235.  
  236. @item /dev/stdout
  237. The standard output (file descriptor 1).
  238.  
  239. @item /dev/stderr
  240. The standard error output (file descriptor 2).
  241.  
  242. @item /dev/fd/@var{n}
  243. The file associated with file descriptor @var{n}.  Such a file must have
  244. been opened by the program initiating the @code{awk} execution (typically
  245. the shell).  Unless you take special pains, only descriptors 0, 1 and 2
  246. are available.
  247. @end table
  248.  
  249. The file names @file{/dev/stdin}, @file{/dev/stdout}, and @file{/dev/stderr}
  250. are aliases for @file{/dev/fd/0}, @file{/dev/fd/1}, and @file{/dev/fd/2},
  251. respectively, but they are more self-explanatory.
  252.  
  253. The proper way to write an error message in a @code{gawk} program
  254. is to use @file{/dev/stderr}, like this:
  255.  
  256. @example
  257. NF != 4 @{
  258.   printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/stderr"
  259. @}
  260. @end example
  261.  
  262. Recognition of these special file names is disabled if @code{gawk} is in
  263. compatibility mode (@pxref{Command Line}).
  264.  
  265. @node One-liners, Patterns, Printing, Top
  266. @chapter Useful ``One-liners''
  267.  
  268. @cindex one-liners
  269. Useful @code{awk} programs are often short, just a line or two.  Here is a
  270. collection of useful, short programs to get you started.  Some of these
  271. programs contain constructs that haven't been covered yet.  The description
  272. of the program will give you a good idea of what is going on, but please
  273. read the rest of the manual to become an @code{awk} expert!
  274.  
  275. @table @code
  276. @item awk '@{ num_fields = num_fields + NF @}
  277. @itemx @ @ @ @ @ END @{ print num_fields @}'
  278. This program prints the total number of fields in all input lines.
  279.  
  280. @item awk 'length($0) > 80'
  281. This program prints every line longer than 80 characters.  The sole
  282. rule has a relational expression as its pattern, and has no action (so the
  283. default action, printing the record, is used).
  284.  
  285. @item awk 'NF > 0'
  286. This program prints every line that has at least one field.  This is an
  287. easy way to delete blank lines from a file (or rather, to create a new
  288. file similar to the old file but from which the blank lines have been
  289. deleted).
  290.  
  291. @item awk '@{ if (NF > 0) print @}'
  292. This program also prints every line that has at least one field.  Here we
  293. allow the rule to match every line, then decide in the action whether
  294. to print.
  295.  
  296. @item awk@ 'BEGIN@ @{@ for (i = 1; i <= 7; i++)
  297. @itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ print int(101 * rand()) @}'
  298. This program prints 7 random numbers from 0 to 100, inclusive.
  299.  
  300. @item ls -l @var{files} | awk '@{ x += $4 @} ; END @{ print "total bytes: " x @}'
  301. This program prints the total number of bytes used by @var{files}.
  302.  
  303. @item expand@ @var{file}@ |@ awk@ '@{ if (x < length()) x = length() @}
  304. @itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ END @{ print "maximum line length is " x @}'
  305. This program prints the maximum line length of @var{file}.  The input
  306. is piped through the @code{expand} program to change tabs into spaces,
  307. so the widths compared are actually the right-margin columns.
  308. @end table
  309.  
  310. @node Patterns, Actions, One-liners, Top
  311. @chapter Patterns
  312. @cindex pattern, definition of
  313.  
  314. Patterns in @code{awk} control the execution of rules: a rule is
  315. executed when its pattern matches the current input record.  This
  316. chapter tells all about how to write patterns.
  317.  
  318. @menu
  319. * Kinds of Patterns::    A list of all kinds of patterns.
  320.                          The following subsections describe them in detail.
  321.  
  322. * Empty::                The empty pattern, which matches every record.
  323.  
  324. * Regexp::               Regular expressions such as @samp{/foo/}.
  325.  
  326. * Comparison Patterns::  Comparison expressions such as @code{$1 > 10}.
  327.  
  328. * Boolean Patterns::     Combining comparison expressions.
  329.  
  330. * Expression Patterns::  Any expression can be used as a pattern.
  331.  
  332. * Ranges::               Using pairs of patterns to specify record ranges.
  333.  
  334. * BEGIN/END::            Specifying initialization and cleanup rules.
  335. @end menu
  336.  
  337. @node Kinds of Patterns, Empty, Patterns, Patterns
  338. @section Kinds of Patterns
  339. @cindex patterns, types of
  340.  
  341. Here is a summary of the types of patterns supported in @code{awk}.
  342.  
  343. @table @code
  344. @item /@var{regular expression}/
  345. A regular expression as a pattern.  It matches when the text of the
  346. input record fits the regular expression.  (@xref{Regexp, , Regular
  347. Expressions as Patterns}.)
  348.  
  349. @item @var{expression}
  350. A single expression.  It matches when its value, converted to a number,
  351. is nonzero (if a number) or nonnull (if a string).  (@xref{Expression
  352. Patterns}.)
  353.  
  354. @item @var{pat1}, @var{pat2}
  355. A pair of patterns separated by a comma, specifying a range of records.
  356. (@xref{Ranges, , Specifying Record Ranges With Patterns}.)
  357.  
  358. @item BEGIN
  359. @itemx END
  360. Special patterns to supply start-up or clean-up information to
  361. @code{awk}.  (@xref{BEGIN/END}.)
  362.  
  363. @item @var{null}
  364. The empty pattern matches every input record.  (@xref{Empty, , The Empty
  365. Pattern}.)
  366. @end table
  367.  
  368. @node Empty, Regexp, Kinds of Patterns, Patterns
  369. @section The Empty Pattern
  370.  
  371. @cindex empty pattern
  372. @cindex pattern, empty
  373. An empty pattern is considered to match @emph{every} input record.  For
  374. example, the program:@refill
  375.  
  376. @example
  377. awk '@{ print $1 @}' BBS-list
  378. @end example
  379.  
  380. @noindent
  381. prints just the first field of every record.
  382.  
  383. @node Regexp, Comparison Patterns, Empty, Patterns
  384. @section Regular Expressions as Patterns
  385. @cindex pattern, regular expressions
  386. @cindex regexp
  387. @cindex regular expressions as patterns
  388.  
  389. A @dfn{regular expression}, or @dfn{regexp}, is a way of describing a
  390. class of strings.  A regular expression enclosed in slashes (@samp{/})
  391. is an @code{awk} pattern that matches every input record whose text
  392. belongs to that class.
  393.  
  394. The simplest regular expression is a sequence of letters, numbers, or
  395. both.  Such a regexp matches any string that contains that sequence.
  396. Thus, the regexp @samp{foo} matches any string containing @samp{foo}.
  397. Therefore, the pattern @code{/foo/} matches any input record containing
  398. @samp{foo}.  Other kinds of regexps let you specify more complicated
  399. classes of strings.
  400.  
  401. @menu
  402. * Usage: Regexp Usage.          How regexps are used in patterns.
  403. * Operators: Regexp Operators.  How to write a regexp.
  404. * Case-sensitivity::            How to do case-insensitive matching.
  405. @end menu
  406.  
  407. @node Regexp Usage, Regexp Operators, Regexp, Regexp
  408. @subsection How to Use Regular Expressions
  409.  
  410. A regular expression can be used as a pattern by enclosing it in
  411. slashes.  Then the regular expression is matched against the entire text
  412. of each record.  (Normally, it only needs to match some part of the text
  413. in order to succeed.)  For example, this prints the second field of each
  414. record that contains @samp{foo} anywhere:
  415.  
  416. @example
  417. awk '/foo/ @{ print $2 @}' BBS-list
  418. @end example
  419.  
  420. @cindex regular expression matching operators
  421. @cindex string-matching operators
  422. @cindex operators, string-matching
  423. @cindex operators, regular expression matching
  424. @cindex regexp search operators
  425. Regular expressions can also be used in comparison expressions.  Then
  426. you can specify the string to match against; it need not be the entire
  427. current input record.  These comparison expressions can be used as
  428. patterns or in @code{if} and @code{while} statements.
  429.  
  430. @table @code
  431. @item @var{exp} ~ /@var{regexp}/
  432. This is true if the expression @var{exp} (taken as a character string)
  433. is matched by @var{regexp}.  The following example matches, or selects,
  434. all input records with the upper-case letter @samp{J} somewhere in the
  435. first field:@refill
  436.  
  437. @example
  438. awk '$1 ~ /J/' inventory-shipped
  439. @end example
  440.  
  441. So does this:
  442.  
  443. @example
  444. awk '@{ if ($1 ~ /J/) print @}' inventory-shipped
  445. @end example
  446.  
  447. @item @var{exp} !~ /@var{regexp}/
  448. This is true if the expression @var{exp} (taken as a character string)
  449. is @emph{not} matched by @var{regexp}.  The following example matches,
  450. or selects, all input records whose first field @emph{does not} contain
  451. the upper-case letter @samp{J}:@refill
  452.  
  453. @example
  454. awk '$1 !~ /J/' inventory-shipped
  455. @end example
  456. @end table
  457.  
  458. @cindex computed regular expressions
  459. @cindex regular expressions, computed
  460. @cindex dynamic regular expressions
  461. The right hand side of a @samp{~} or @samp{!~} operator need not be a
  462. constant regexp (i.e., a string of characters between slashes).  It may
  463. be any expression.  The expression is evaluated, and converted if
  464. necessary to a string; the contents of the string are used as the
  465. regexp.  A regexp that is computed in this way is called a @dfn{dynamic
  466. regexp}.  For example:
  467.  
  468. @example
  469. identifier_regexp = "[A-Za-z_][A-Za-z_0-9]+"
  470. $0 ~ identifier_regexp
  471. @end example
  472.  
  473. @noindent
  474. sets @code{identifier_regexp} to a regexp that describes @code{awk}
  475. variable names, and tests if the input record matches this regexp.
  476.  
  477. @node Regexp Operators, Case-sensitivity, Regexp Usage, Regexp
  478. @subsection Regular Expression Operators
  479. @cindex metacharacters
  480. @cindex regular expression metacharacters
  481.  
  482. You can combine regular expressions with the following characters,
  483. called @dfn{regular expression operators}, or @dfn{metacharacters}, to
  484. increase the power and versatility of regular expressions.
  485.  
  486. Here is a table of metacharacters.  All characters not listed in the
  487. table stand for themselves.
  488.  
  489. @table @code
  490. @item ^
  491. This matches the beginning of the string or the beginning of a line
  492. within the string.  For example:
  493.  
  494. @example
  495. ^@@chapter
  496. @end example
  497.  
  498. @noindent
  499. matches the @samp{@@chapter} at the beginning of a string, and can be used
  500. to identify chapter beginnings in Texinfo source files.
  501.  
  502. @item $
  503. This is similar to @samp{^}, but it matches only at the end of a string
  504. or the end of a line within the string.  For example:
  505.  
  506. @example
  507. p$
  508. @end example
  509.  
  510. @noindent
  511. matches a record that ends with a @samp{p}.
  512.  
  513. @item .
  514. This matches any single character except a newline.  For example:
  515.  
  516. @example
  517. .P
  518. @end example
  519.  
  520. @noindent
  521. matches any single character followed by a @samp{P} in a string.  Using
  522. concatenation we can make regular expressions like @samp{U.A}, which
  523. matches any three-character sequence that begins with @samp{U} and ends
  524. with @samp{A}.
  525.  
  526. @item [@dots{}]
  527. This is called a @dfn{character set}.  It matches any one of the
  528. characters that are enclosed in the square brackets.  For example:
  529.  
  530. @example
  531. [MVX]
  532. @end example
  533.  
  534. @noindent
  535. matches any of the characters @samp{M}, @samp{V}, or @samp{X} in a
  536. string.@refill
  537.  
  538. Ranges of characters are indicated by using a hyphen between the beginning
  539. and ending characters, and enclosing the whole thing in brackets.  For
  540. example:@refill
  541.  
  542. @example
  543. [0-9]
  544. @end example
  545.  
  546. @noindent
  547. matches any digit.
  548.  
  549. To include the character @samp{\}, @samp{]}, @samp{-} or @samp{^} in a
  550. character set, put a @samp{\} in front of it.  For example:
  551.  
  552. @example
  553. [d\]]
  554. @end example
  555.  
  556. @noindent
  557. matches either @samp{]}, or @samp{d}.@refill
  558.  
  559. This treatment of @samp{\} is compatible with other @code{awk}
  560. implementations but incompatible with the proposed POSIX specification
  561. for @code{awk}.  The current draft specifies the use of the same syntax
  562. used in @code{egrep}.
  563.  
  564. We may change @code{gawk} to fit the standard, once we are sure it will
  565. no longer change.  For the meanwhile, the @samp{-a} option specifies the
  566. traditional @code{awk} syntax described above (which is also the
  567. default), while the @samp{-e} option specifies @code{egrep} syntax.
  568. @xref{Options}.
  569.  
  570. In @code{egrep} syntax, backslash is not syntactically special within
  571. square brackets.  This means that special tricks have to be used to
  572. represent the characters @samp{]}, @samp{-} and @samp{^} as members of a
  573. character set.
  574.  
  575. To match @samp{-}, write it as @samp{---}, which is a range containing
  576. only @samp{-}.  You may also give @samp{-} as the first or last
  577. character in the set.  To match @samp{^}, put it anywhere except as the
  578. first character of a set.  To match a @samp{]}, make it the first
  579. character in the set.  For example:
  580.  
  581. @example
  582. []d^]
  583. @end example
  584.  
  585. @noindent
  586. matches either @samp{]}, @samp{d} or @samp{^}.@refill
  587.  
  588. @item [^ @dots{}]
  589. This is a @dfn{complemented character set}.  The first character after
  590. the @samp{[} @emph{must} be a @samp{^}.  It matches any characters
  591. @emph{except} those in the square brackets.  For example:
  592.  
  593. @example
  594. [^0-9]
  595. @end example
  596.  
  597. @noindent
  598. matches any character that is not a digit.
  599.  
  600. @item |
  601. This is the @dfn{alternation operator} and it is used to specify
  602. alternatives.  For example:
  603.  
  604. @example
  605. ^P|[0-9]
  606. @end example
  607.  
  608. @noindent
  609. matches any string that matches either @samp{^P} or @samp{[0-9]}.  This
  610. means it matches any string that contains a digit or starts with @samp{P}.
  611.  
  612. The alternation applies to the largest possible regexps on either side.
  613. @item (@dots{})
  614. Parentheses are used for grouping in regular expressions as in
  615. arithmetic.  They can be used to concatenate regular expressions
  616. containing the alternation operator, @samp{|}.
  617.  
  618. @item *
  619. This symbol means that the preceding regular expression is to be
  620. repeated as many times as possible to find a match.  For example:
  621.  
  622. @example
  623. ph*
  624. @end example
  625.  
  626. @noindent
  627. applies the @samp{*} symbol to the preceding @samp{h} and looks for matches
  628. to one @samp{p} followed by any number of @samp{h}s.  This will also match
  629. just @samp{p} if no @samp{h}s are present.
  630.  
  631. The @samp{*} repeats the @emph{smallest} possible preceding expression.
  632. (Use parentheses if you wish to repeat a larger expression.)  It finds
  633. as many repetitions as possible.  For example:
  634.  
  635. @example
  636. awk '/\(c[ad][ad]*r x\)/ @{ print @}' sample
  637. @end example
  638.  
  639. @noindent
  640. prints every record in the input containing a string of the form
  641. @samp{(car x)}, @samp{(cdr x)}, @samp{(cadr x)}, and so on.@refill
  642.  
  643. @item +
  644. This symbol is similar to @samp{*}, but the preceding expression must be
  645. matched at least once.  This means that:
  646.  
  647. @example
  648. wh+y
  649. @end example
  650.  
  651. @noindent
  652. would match @samp{why} and @samp{whhy} but not @samp{wy}, whereas
  653. @samp{wh*y} would match all three of these strings.  This is a simpler
  654. way of writing the last @samp{*} example:
  655.  
  656. @example
  657. awk '/\(c[ad]+r x\)/ @{ print @}' sample
  658. @end example
  659.  
  660. @item ?
  661. This symbol is similar to @samp{*}, but the preceding expression can be
  662. matched once or not at all.  For example:
  663.  
  664. @example
  665. fe?d
  666. @end example
  667.  
  668. @noindent
  669. will match @samp{fed} or @samp{fd}, but nothing else.@refill
  670.  
  671. @item \
  672. This is used to suppress the special meaning of a character when
  673. matching.  For example:
  674.  
  675. @example
  676. \$
  677. @end example
  678.  
  679. @noindent
  680. matches the character @samp{$}.
  681.  
  682. The escape sequences used for string constants (@pxref{Constants}) are
  683. valid in regular expressions as well; they are also introduced by a
  684. @samp{\}.
  685. @end table
  686.  
  687. In regular expressions, the @samp{*}, @samp{+}, and @samp{?} operators have
  688. the highest precedence, followed by concatenation, and finally by @samp{|}.
  689. As in arithmetic, parentheses can change how operators are grouped.@refill
  690.  
  691. @node Case-sensitivity,, Regexp Operators, Regexp
  692. @subsection Case-sensitivity in Matching
  693.  
  694. Case is normally significant in regular expressions, both when matching
  695. ordinary characters (i.e., not metacharacters), and inside character
  696. sets.  Thus a @samp{w} in a regular expression matches only a lower case
  697. @samp{w} and not an upper case @samp{W}.
  698.  
  699. The simplest way to do a case-independent match is to use a character
  700. set: @samp{[Ww]}.  However, this can be cumbersome if you need to use it
  701. often; and it can make the regular expressions harder for humans to
  702. read.  There are two other alternatives that you might prefer.
  703.  
  704. One way to do a case-insensitive match at a particular point in the
  705. program is to convert the data to a single case, using the
  706. @code{tolower} or @code{toupper} built-in string functions (which we
  707. haven't discussed yet; @pxref{String Functions}).  For example:
  708.  
  709. @example
  710. tolower($1) ~ /foo/  @{ @dots{} @}
  711. @end example
  712.  
  713. @noindent
  714. converts the first field to lower case before matching against it.
  715.  
  716. Another method is to set the variable @code{IGNORECASE} to a nonzero
  717. value (@pxref{Built-in Variables}).  When @code{IGNORECASE} is not zero,
  718. @emph{all} regexp operations ignore case.  Changing the value of
  719. @code{IGNORECASE} dynamically controls the case sensitivity of your
  720. program as it runs.  Case is significant by default because
  721. @code{IGNORECASE} (like most variables) is initialized to zero.
  722.  
  723. @example
  724. x = "aB"
  725. if (x ~ /ab/) @dots{}   # this test will fail
  726.  
  727. IGNORECASE = 1
  728. if (x ~ /ab/) @dots{}   # now it will succeed
  729. @end example
  730.  
  731. You cannot generally use @code{IGNORECASE} to make certain rules
  732. case-insensitive and other rules case-sensitive, because there is no way
  733. to set @code{IGNORECASE} just for the pattern of a particular rule.  To
  734. do this, you must use character sets or @code{tolower}.  However, one
  735. thing you can do only with @code{IGNORECASE} is turn case-sensitivity on
  736. or off dynamically for all the rules at once.
  737.  
  738. @code{IGNORECASE} can be set on the command line, or in a @code{BEGIN}
  739. rule.  Setting @code{IGNORECASE} from the command line is a way to make
  740. a program case-insensitive without having to edit it.
  741.  
  742. The value of @code{IGNORECASE} has no effect if @code{gawk} is in
  743. compatibility mode (@pxref{Command Line}).  Case is always significant
  744. in compatibility mode.
  745.  
  746. @node Comparison Patterns, Boolean Patterns, Regexp, Patterns
  747. @section Comparison Expressions as Patterns
  748. @cindex comparison expressions as patterns
  749. @cindex pattern, comparison expressions
  750. @cindex relational operators
  751. @cindex operators, relational
  752.  
  753. @dfn{Comparison patterns} test relationships such as equality between
  754. two strings or numbers.  They are a special case of expression patterns
  755. (@pxref{Expression Patterns}).  They are written with @dfn{relational
  756. operators}, which are a superset of those in C.  Here is a table of
  757. them:
  758.  
  759. @table @code
  760. @item @var{x} < @var{y}
  761. True if @var{x} is less than @var{y}.
  762.  
  763. @item @var{x} <= @var{y}
  764. True if @var{x} is less than or equal to @var{y}.
  765.  
  766. @item @var{x} > @var{y}
  767. True if @var{x} is greater than @var{y}.
  768.  
  769. @item @var{x} >= @var{y}
  770. True if @var{x} is greater than or equal to @var{y}.
  771.  
  772. @item @var{x} == @var{y}
  773. True if @var{x} is equal to @var{y}.
  774.  
  775. @item @var{x} != @var{y}
  776. True if @var{x} is not equal to @var{y}.
  777.  
  778. @item @var{x} ~ @var{y}
  779. True if @var{x} matches the regular expression described by @var{y}.
  780.  
  781. @item @var{x} !~ @var{y}
  782. True if @var{x} does not match the regular expression described by @var{y}.
  783. @end table
  784.  
  785. The operands of a relational operator are compared as numbers if they
  786. are both numbers.  Otherwise they are converted to, and compared as,
  787. strings (@pxref{Conversion}).  Strings are compared by comparing the
  788. first character of each, then the second character of each, and so on,
  789. until there is a difference.  If the two strings are equal until the
  790. shorter one runs out, the shorter one is considered to be less than the
  791. longer one.  Thus, @code{"10"} is less than @code{"9"}.
  792.  
  793. The left operand of the @samp{~} and @samp{!~} operators is a string.
  794. The right operand is either a constant regular expression enclosed in
  795. slashes (@code{/@var{regexp}/}), or any expression, whose string value
  796. is used as a dynamic regular expression (@pxref{Regexp Usage}).
  797.  
  798. The following example prints the second field of each input record
  799. whose first field is precisely @samp{foo}.
  800.  
  801. @example
  802. awk '$1 == "foo" @{ print $2 @}' BBS-list
  803. @end example
  804.  
  805. @noindent
  806. Contrast this with the following regular expression match, which would
  807. accept any record with a first field that contains @samp{foo}:
  808.  
  809. @example
  810. awk '$1 ~ "foo" @{ print $2 @}' BBS-list
  811. @end example
  812.  
  813. @noindent
  814. or, equivalently, this one:
  815.  
  816. @example
  817. awk '$1 ~ /foo/ @{ print $2 @}' BBS-list
  818. @end example
  819.  
  820. @node Boolean Patterns, Expression Patterns, Comparison Patterns, Patterns
  821. @section Boolean Operators and Patterns
  822. @cindex patterns, boolean
  823. @cindex boolean patterns
  824.  
  825. A @dfn{boolean pattern} is an expression which combines other patterns
  826. using the @dfn{boolean operators} ``or'' (@samp{||}), ``and''
  827. (@samp{&&}), and ``not'' (@samp{!}).  Whether the boolean pattern
  828. matches an input record depends on whether its subpatterns match.
  829.  
  830. For example, the following command prints all records in the input file
  831. @file{BBS-list} that contain both @samp{2400} and @samp{foo}.@refill
  832.  
  833. @example
  834. awk '/2400/ && /foo/' BBS-list
  835. @end example
  836.  
  837. The following command prints all records in the input file
  838. @file{BBS-list} that contain @emph{either} @samp{2400} or @samp{foo}, or
  839. both.@refill
  840.  
  841. @example
  842. awk '/2400/ || /foo/' BBS-list
  843. @end example
  844.  
  845. The following command prints all records in the input file
  846. @file{BBS-list} that do @emph{not} contain the string @samp{foo}.
  847.  
  848. @example
  849. awk '! /foo/' BBS-list
  850. @end example
  851.  
  852. Note that boolean patterns are a special case of expression patterns
  853. (@pxref{Expression Patterns}); they are expressions that use the boolean
  854. operators.  For complete information on the boolean operators, see
  855. @ref{Boolean Ops}.
  856.  
  857. The subpatterns of a boolean pattern can be constant regular
  858. expressions, comparisons, or any other @code{gawk} expressions.  Range
  859. patterns are not expressions, so they cannot appear inside boolean
  860. patterns.  Likewise, the special patterns @code{BEGIN} and @code{END},
  861. which never match any input record, are not expressions and cannot
  862. appear inside boolean patterns.
  863.  
  864. @node Expression Patterns, Ranges, Boolean Patterns, Patterns
  865. @section Expressions as Patterns
  866.  
  867. Any @code{awk} expression is valid also as a pattern in @code{gawk}.
  868. Then the pattern ``matches'' if the expression's value is nonzero (if a
  869. number) or nonnull (if a string).
  870.  
  871. The expression is reevaluated each time the rule is tested against a new
  872. input record.  If the expression uses fields such as @code{$1}, the
  873. value depends directly on the new input record's text; otherwise, it
  874. depends only on what has happened so far in the execution of the
  875. @code{awk} program, but that may still be useful.
  876.  
  877. Comparison patterns are actually a special case of this.  For
  878. example, the expression @code{$5 == "foo"} has the value 1 when the
  879. value of @code{$5} equals @code{"foo"}, and 0 otherwise; therefore, this
  880. expression as a pattern matches when the two values are equal.
  881.  
  882. Boolean patterns are also special cases of expression patterns.
  883.  
  884. A constant regexp as a pattern is also a special case of an expression
  885. pattern.  @code{/foo/} as an expression has the value 1 if @samp{foo}
  886. appears in the current input record; thus, as a pattern, @code{/foo/}
  887. matches any record containing @samp{foo}.
  888.  
  889. Other implementations of @code{awk} are less general than @code{gawk}:
  890. they allow comparison expressions, and boolean combinations thereof
  891. (optionally with parentheses), but not necessarily other kinds of
  892. expressions.
  893.  
  894. @node Ranges, BEGIN/END, Expression Patterns, Patterns
  895. @section Specifying Record Ranges With Patterns
  896.  
  897. @cindex range pattern
  898. @cindex patterns, range
  899. A @dfn{range pattern} is made of two patterns separated by a comma, of
  900. the form @code{@var{begpat}, @var{endpat}}.  It matches ranges of
  901. consecutive input records.  The first pattern @var{begpat} controls
  902. where the range begins, and the second one @var{endpat} controls where
  903. it ends.  For example,@refill
  904.  
  905. @example
  906. awk '$1 == "on", $1 == "off"'
  907. @end example
  908.  
  909. @noindent
  910. prints every record between @samp{on}/@samp{off} pairs, inclusive.
  911.  
  912. In more detail, a range pattern starts out by matching @var{begpat}
  913. against every input record; when a record matches @var{begpat}, the
  914. range pattern becomes @dfn{turned on}.  The range pattern matches this
  915. record.  As long as it stays turned on, it automatically matches every
  916. input record read.  But meanwhile, it also matches @var{endpat} against
  917. every input record, and when that succeeds, the range pattern is turned
  918. off again for the following record.  Now it goes back to checking
  919. @var{begpat} against each record.
  920.  
  921. The record that turns on the range pattern and the one that turns it
  922. off both match the range pattern.  If you don't want to operate on
  923. these records, you can write @code{if} statements in the rule's action
  924. to distinguish them.
  925.  
  926. It is possible for a pattern to be turned both on and off by the same
  927. record, if both conditions are satisfied by that record.  Then the action is
  928. executed for just that record.
  929.  
  930. @node BEGIN/END,, Ranges, Patterns
  931. @section @code{BEGIN} and @code{END} Special Patterns
  932.  
  933. @cindex @code{BEGIN} special pattern
  934. @cindex patterns, @code{BEGIN}
  935. @cindex @code{END} special pattern
  936. @cindex patterns, @code{END}
  937. @code{BEGIN} and @code{END} are special patterns.  They are not used to
  938. match input records.  Rather, they are used for supplying start-up or
  939. clean-up information to your @code{awk} script.  A @code{BEGIN} rule is
  940. executed, once, before the first input record has been read.  An @code{END}
  941. rule is executed, once, after all the input has been read.  For
  942. example:@refill
  943.  
  944. @group
  945. @example
  946. awk 'BEGIN @{ print "Analysis of `foo'" @}
  947.      /foo/ @{ ++foobar @}
  948.      END   @{ print "`foo' appears " foobar " times." @}' BBS-list
  949. @end example
  950. @end group
  951.  
  952. This program finds out how many times the string @samp{foo} appears in
  953. the input file @file{BBS-list}.  The @code{BEGIN} rule prints a title
  954. for the report.  There is no need to use the @code{BEGIN} rule to
  955. initialize the counter @code{foobar} to zero, as @code{awk} does this
  956. for us automatically (@pxref{Variables}).
  957.  
  958. The second rule increments the variable @code{foobar} every time a
  959. record containing the pattern @samp{foo} is read.  The @code{END} rule
  960. prints the value of @code{foobar} at the end of the run.@refill
  961.  
  962. The special patterns @code{BEGIN} and @code{END} cannot be used in ranges
  963. or with boolean operators.
  964.  
  965. An @code{awk} program may have multiple @code{BEGIN} and/or @code{END}
  966. rules.  They are executed in the order they appear, all the @code{BEGIN}
  967. rules at start-up and all the @code{END} rules at termination.
  968.  
  969. Multiple @code{BEGIN} and @code{END} sections are useful for writing
  970. library functions, since each library can have its own @code{BEGIN} or
  971. @code{END} rule to do its own initialization and/or cleanup.  Note that
  972. the order in which library functions are named on the command line
  973. controls the order in which their @code{BEGIN} and @code{END} rules are
  974. executed.  Therefore you have to be careful to write such rules in
  975. library files so that it doesn't matter what order they are executed in.
  976. @xref{Command Line}, for more information on using library functions.
  977.  
  978. If an @code{awk} program only has a @code{BEGIN} rule, and no other
  979. rules, then the program exits after the @code{BEGIN} rule has been run.
  980. (Older versions of @code{awk} used to keep reading and ignoring input
  981. until end of file was seen.)  However, if an @code{END} rule exists as
  982. well, then the input will be read, even if there are no other rules in
  983. the program.  This is necessary in case the @code{END} rule checks the
  984. @code{NR} variable.
  985.  
  986. @code{BEGIN} and @code{END} rules must have actions; there is no default
  987. action for these rules since there is no current record when they run.
  988.  
  989. @node Actions, Expressions, Patterns, Top
  990. @chapter Actions: Overview
  991. @cindex action, definition of
  992. @cindex curly braces
  993. @cindex action, curly braces
  994. @cindex action, separating statements
  995.  
  996. An @code{awk} @dfn{program} or @dfn{script} consists of a series of
  997. @dfn{rules} and function definitions, interspersed.  (Functions are
  998. described later; see @ref{User-defined}.)
  999.  
  1000. A rule contains a pattern and an @dfn{action}, either of which may be
  1001. omitted.  The purpose of the action is to tell @code{awk} what to do
  1002. once a match for the pattern is found.  Thus, the entire program
  1003. looks somewhat like this:
  1004.  
  1005. @example
  1006. @r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]}
  1007. @r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]}
  1008. @dots{}
  1009. function @var{name} (@var{args}) @{ @dots{} @}
  1010. @dots{}
  1011. @end example
  1012.  
  1013. An action consists of one or more @code{awk} @dfn{statements}, enclosed
  1014. in curly braces (@samp{@{} and @samp{@}}).  Each statement specifies one
  1015. thing to be done.  The statements are separated by newlines or
  1016. semicolons.
  1017.  
  1018. The curly braces around an action must be used even if the action
  1019. contains only one statement, or even if it contains no statements at
  1020. all.  However, if you omit the action entirely, omit the curly braces as
  1021. well.  (An omitted action is equivalent to @samp{@{ print $0 @}}.)
  1022.  
  1023. Here are the kinds of statement supported in @code{awk}:
  1024.  
  1025. @itemize @bullet
  1026. @item
  1027. Expressions, which can call functions or assign values to variables
  1028. (@pxref{Expressions}).  Executing this kind of statement simply computes
  1029. the value of the expression and then ignores it.  This is useful when
  1030. the expression has side effects (@pxref{Assignment Ops}).
  1031.  
  1032. @item
  1033. Control statements, which specify the control flow of @code{awk}
  1034. programs.  The @code{awk} language gives you C-like constructs
  1035. (@code{if}, @code{for}, @code{while}, and so on) as well as a few
  1036. special ones (@pxref{Statements}).@refill
  1037.  
  1038. @item
  1039. Compound statements, which consist of one or more statements enclosed in
  1040. curly braces.  A compound statement is used in order to put several
  1041. statements together in the body of an @code{if}, @code{while}, @code{do}
  1042. or @code{for} statement.
  1043.  
  1044. @item
  1045. Input control, using the @code{getline} function (@pxref{Getline}),
  1046. and the @code{next} statement (@pxref{Next Statement}).
  1047.  
  1048. @item
  1049. Output statements, @code{print} and @code{printf}.  @xref{Printing}.
  1050.  
  1051. @item
  1052. Deletion statements, for deleting array elements.  @xref{Delete}.
  1053. @end itemize
  1054.  
  1055. @iftex
  1056. The next two chapters cover in detail expressions and control
  1057. statements, respectively.  We go on to treat arrays, and built-in
  1058. functions, both of which are used in expressions.  Then we proceed
  1059. to discuss how to define your own functions.
  1060. @end iftex
  1061.  
  1062. @node Expressions, Statements, Actions, Top
  1063. @chapter Actions: Expressions
  1064. @cindex expression
  1065.  
  1066. Expressions are the basic building block of @code{awk} actions.  An
  1067. expression evaluates to a value, which you can print, test, store in a
  1068. variable or pass to a function.
  1069.  
  1070. But, beyond that, an expression can assign a new value to a variable
  1071. or a field, with an assignment operator.
  1072.  
  1073. An expression can serve as a statement on its own.  Most other kinds of
  1074. statement contain one or more expressions which specify data to be
  1075. operated on.  As in other languages, expressions in @code{awk} include
  1076. variables, array references, constants, and function calls, as well as
  1077. combinations of these with various operators.
  1078.  
  1079. @menu
  1080. * Constants::       String, numeric, and regexp constants.
  1081. * Variables::       Variables give names to values for later use.
  1082. * Arithmetic Ops::  Arithmetic operations (@samp{+}, @samp{-}, etc.)
  1083. * Concatenation::   Concatenating strings.
  1084. * Comparison Ops::  Comparison of numbers and strings with @samp{<}, etc.
  1085. * Boolean Ops::     Combining comparison expressions using boolean operators
  1086.                     @samp{||} (``or''), @samp{&&} (``and'') and @samp{!} (``not'').
  1087.  
  1088. * Assignment Ops::  Changing the value of a variable or a field.
  1089. * Increment Ops::   Incrementing the numeric value of a variable.
  1090.  
  1091. * Conversion::      The conversion of strings to numbers and vice versa.
  1092. * Conditional Exp:: Conditional expressions select between two subexpressions
  1093.                     under control of a third subexpression.
  1094. * Function Calls::  A function call is an expression.
  1095. * Precedence::      How various operators nest.
  1096. @end menu
  1097.  
  1098. @node Constants, Variables, Expressions, Expressions
  1099. @section Constant Expressions
  1100. @cindex constants, types of
  1101. @cindex string constants
  1102.  
  1103. The simplest type of expression is the @dfn{constant}, which always has
  1104. the same value.  There are three types of constant: numeric constants,
  1105. string constants, and regular expression constants.
  1106.  
  1107. @cindex numeric constant
  1108. @cindex numeric value
  1109. A @dfn{numeric constant} stands for a number.  This number can be an
  1110. integer, a decimal fraction, or a number in scientific (exponential)
  1111. notation.  Note that all numeric values are represented within
  1112. @code{awk} in double-precision floating point.  Here are some examples
  1113. of numeric constants, which all have the same value:
  1114.  
  1115. @example
  1116. 105
  1117. 1.05e+2
  1118. 1050e-1
  1119. @end example
  1120.  
  1121. A string constant consists of a sequence of characters enclosed in
  1122. double-quote marks.  For example:
  1123.  
  1124. @example
  1125. "parrot"
  1126. @end example
  1127.  
  1128. @noindent
  1129. @c @cindex differences between @code{gawk} and @code{awk}
  1130. represents the string whose contents are @samp{parrot}.  Strings in
  1131. @code{gawk} can be of any length and they can contain all the possible
  1132. 8-bit ASCII characters including ASCII NUL.  Other @code{awk}
  1133. implementations may have difficulty with some character codes.@refill
  1134.  
  1135. @cindex escape sequence notation
  1136. Some characters cannot be included literally in a string constant.  You
  1137. represent them instead with @dfn{escape sequences}, which are character
  1138. sequences beginning with a backslash (@samp{\}).
  1139.  
  1140. One use of an escape sequence is to include a double-quote character in
  1141. a string constant.  Since a plain double-quote would end the string, you
  1142. must use @samp{\"} to represent a single double-quote character as a
  1143. part of the string.  Backslash itself is another character that can't be
  1144. included normally; you write @samp{\\} to put one backslash in the
  1145. string.  Thus, the string whose contents are the two characters
  1146. @samp{"\} must be written @code{"\"\\"}.
  1147.  
  1148. Another use of backslash is to represent unprintable characters
  1149. such as newline.  While there is nothing to stop you from writing most
  1150. of these characters directly in a string constant, they may look ugly.
  1151.  
  1152. Here is a table of all the escape sequences used in @code{awk}:
  1153.  
  1154. @table @code
  1155. @item \\
  1156. Represents a literal backslash, @samp{\}.
  1157.  
  1158. @item \a
  1159. Represents the ``alert'' character, control-g, ASCII code 7.
  1160.  
  1161. @item \b
  1162. Represents a backspace, control-h, ASCII code 8.
  1163.  
  1164. @item \f
  1165. Represents a formfeed, control-l, ASCII code 12.
  1166.  
  1167. @item \n
  1168. Represents a newline, control-j, ASCII code 10.
  1169.  
  1170. @item \r
  1171. Represents a carriage return, control-m, ASCII code 13.
  1172.  
  1173. @item \t
  1174. Represents a horizontal tab, control-i, ASCII code 9.
  1175.  
  1176. @item \v
  1177. Represents a vertical tab, control-k, ASCII code 11.
  1178.  
  1179. @item \@var{nnn}
  1180. Represents the octal value @var{nnn}, where @var{nnn} are one to three
  1181. digits between 0 and 7.  For example, the code for the ASCII ESC
  1182. (escape) character is @samp{\033}.@refill
  1183.  
  1184. @item \x@var{hh@dots{}}
  1185. Represents the hexadecimal value @var{hh}, where @var{hh} are hexadecimal
  1186. digits (@samp{0} through @samp{9} and either @samp{A} through @samp{F} or
  1187. @samp{a} through @samp{f}).  Like the same construct in ANSI C, the escape
  1188. sequence continues until the first non-hexadecimal digit is seen.  However,
  1189. using more than two hexadecimal digits produces undefined results.@refill
  1190. @end table
  1191.  
  1192. A constant regexp is a regular expression description enclosed in
  1193. slashes, such as @code{/^beginning and end$/}.  Most regexps used in
  1194. @code{awk} programs are constant, but the @samp{~} and @samp{!~}
  1195. operators can also match computed or ``dynamic'' regexps (@pxref{Regexp
  1196. Usage}).
  1197.  
  1198. Constant regexps are useful only with the @samp{~} and @samp{!~} operators;
  1199. you cannot assign them to variables or print them.  They are not truly
  1200. expressions in the usual sense.
  1201.  
  1202. @node Variables, Arithmetic Ops, Constants, Expressions
  1203. @section Variables
  1204. @cindex variables, user-defined
  1205. @cindex user-defined variables
  1206.  
  1207. Variables let you give names to values and refer to them later.  You have
  1208. already seen variables in many of the examples.  The name of a variable
  1209. must be a sequence of letters, digits and underscores, but it may not begin
  1210. with a digit.  Case is significant in variable names; @code{a} and @code{A}
  1211. are distinct variables.
  1212.  
  1213. A variable name is a valid expression by itself; it represents the
  1214. variable's current value.  Variables are given new values with
  1215. @dfn{assignment operators} and @dfn{increment operators}.
  1216. @xref{Assignment Ops}.
  1217.  
  1218. A few variables have special built-in meanings, such as @code{FS}, the
  1219. field separator, and @code{NF}, the number of fields in the current
  1220. input record.  @xref{Built-in Variables}, for a list of them.  These
  1221. built-in variables can be used and assigned just like all other
  1222. variables, but their values are also used or changed automatically by
  1223. @code{awk}.  Each built-in variable's name is made entirely of upper case
  1224. letters.
  1225.  
  1226. Variables in @code{awk} can be assigned either numeric values or string
  1227. values.  By default, variables are initialized to the null string, which
  1228. is effectively zero if converted to a number.  So there is no need to
  1229. ``initialize'' each variable explicitly in @code{awk}, the way you would
  1230. need to do in C or most other traditional programming languages.
  1231.  
  1232. @menu
  1233. * Assignment Options::  Setting variables on the command line and a summary
  1234.                         of command line syntax.  This is an advanced method
  1235.                         of input.
  1236. @end menu
  1237.  
  1238. @node Assignment Options,, Variables, Variables
  1239. @subsection Assigning Variables on the Command Line
  1240.  
  1241. You can set any @code{awk} variable by including a @dfn{variable assignment}
  1242. among the arguments on the command line when you invoke @code{awk}
  1243. (@pxref{Command Line}).  Such an assignment has this form:
  1244.  
  1245. @example
  1246. @var{variable}=@var{text}
  1247. @end example
  1248.  
  1249. @noindent
  1250. With it, you can set a variable either at the beginning of the
  1251. @code{awk} run or in between input files.
  1252.  
  1253. If you precede the assignment with the @samp{-v} option, like this:
  1254.  
  1255. @example
  1256. -v @var{variable}=@var{text}
  1257. @end example
  1258.  
  1259. @noindent
  1260. then the variable is set at the very beginning, before even the
  1261. @code{BEGIN} rules are run.  The @samp{-v} option and its assignment
  1262. must precede all the file name arguments.
  1263.  
  1264. Otherwise, the variable assignment is performed at a time determined by
  1265. its position among the input file arguments: after the processing of the
  1266. preceding input file argument.  For example:
  1267.  
  1268. @example
  1269. awk '@{ print $n @}' n=4 inventory-shipped n=2 BBS-list
  1270. @end example
  1271.  
  1272. @noindent
  1273. prints the value of field number @code{n} for all input records.  Before
  1274. the first file is read, the command line sets the variable @code{n}
  1275. equal to 4.  This causes the fourth field to be printed in lines from
  1276. the file @file{inventory-shipped}.  After the first file has finished,
  1277. but before the second file is started, @code{n} is set to 2, so that the
  1278. second field is printed in lines from @file{BBS-list}.
  1279.  
  1280. Command line arguments are made available for explicit examination by
  1281. the @code{awk} program in an array named @code{ARGV} (@pxref{Built-in
  1282. Variables}).
  1283.  
  1284. @node Arithmetic Ops, Concatenation, Variables, Expressions
  1285. @section Arithmetic Operators
  1286. @cindex arithmetic operators
  1287. @cindex operators, arithmetic
  1288. @cindex addition
  1289. @cindex subtraction
  1290. @cindex multiplication
  1291. @cindex division
  1292. @cindex remainder
  1293. @cindex quotient
  1294. @cindex exponentiation
  1295.  
  1296. The @code{awk} language uses the common arithmetic operators when
  1297. evaluating expressions.  All of these arithmetic operators follow normal
  1298. precedence rules, and work as you would expect them to.  This example
  1299. divides field three by field four, adds field two, stores the result
  1300. into field one, and prints the resulting altered input record:
  1301.  
  1302. @example
  1303. awk '@{ $1 = $2 + $3 / $4; print @}' inventory-shipped
  1304. @end example
  1305.  
  1306. The arithmetic operators in @code{awk} are:
  1307.  
  1308. @table @code
  1309. @item @var{x} + @var{y}
  1310. Addition.
  1311.  
  1312. @item @var{x} - @var{y}
  1313. Subtraction.
  1314.  
  1315. @item - @var{x}
  1316. Negation.
  1317.  
  1318. @item @var{x} * @var{y}
  1319. Multiplication.
  1320.  
  1321. @item @var{x} / @var{y}
  1322. Division.  Since all numbers in @code{awk} are double-precision
  1323. floating point, the result is not rounded to an integer: @code{3 / 4}
  1324. has the value 0.75.
  1325.  
  1326. @item @var{x} % @var{y}
  1327. @c @cindex differences between @code{gawk} and @code{awk}
  1328. Remainder.  The quotient is rounded toward zero to an integer,
  1329. multiplied by @var{y} and this result is subtracted from @var{x}.
  1330. This operation is sometimes known as ``trunc-mod''.  The following
  1331. relation always holds:
  1332.  
  1333. @example
  1334. b * int(a / b) + (a % b) == a
  1335. @end example
  1336.  
  1337. One undesirable effect of this definition of remainder is that
  1338. @code{@var{x} % @var{y}} is negative if @var{x} is negative.  Thus,
  1339.  
  1340. @example
  1341. -17 % 8 = -1
  1342. @end example
  1343.  
  1344. In other @code{awk} implementations, the signedness of the remainder
  1345. may be machine dependent.
  1346.  
  1347. @item @var{x} ^ @var{y}
  1348. @itemx @var{x} ** @var{y}
  1349. Exponentiation: @var{x} raised to the @var{y} power.  @code{2 ^ 3} has
  1350. the value 8.  The character sequence @samp{**} is equivalent to
  1351. @samp{^}.
  1352. @end table
  1353.  
  1354. @node Concatenation, Comparison Ops, Arithmetic Ops, Expressions
  1355. @section String Concatenation
  1356.  
  1357. @cindex string operators
  1358. @cindex operators, string
  1359. @cindex concatenation
  1360. There is only one string operation: concatenation.  It does not have a
  1361. specific operator to represent it.  Instead, concatenation is performed by
  1362. writing expressions next to one another, with no operator.  For example:
  1363.  
  1364. @example
  1365. awk '@{ print "Field number one: " $1 @}' BBS-list
  1366. @end example
  1367.  
  1368. @noindent
  1369. produces, for the first record in @file{BBS-list}:
  1370.  
  1371. @example
  1372. Field number one: aardvark
  1373. @end example
  1374.  
  1375. Without the space in the string constant after the @samp{:}, the line
  1376. would run together.  For example:
  1377.  
  1378. @example
  1379. awk '@{ print "Field number one:" $1 @}' BBS-list
  1380. @end example
  1381.  
  1382. @noindent
  1383. produces, for the first record in @file{BBS-list}:
  1384.  
  1385. @example
  1386. Field number one:aardvark
  1387. @end example
  1388.  
  1389. Since string concatenation does not have an explicit operator, it is
  1390.