home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / gnuawk.zip / doc / gawk.info (.txt) < prev    next >
GNU Info File  |  1997-03-15  |  734KB  |  14,608 lines

  1. This is Info file gawk.info, produced by Makeinfo version 1.67 from the
  2. input file ./gawk.texi.
  3. INFO-DIR-SECTION Programming Languages
  4. START-INFO-DIR-ENTRY
  5. * Gawk: (gawk.info).           A Text Scanning and Processing Language.
  6. END-INFO-DIR-ENTRY
  7.    This file documents `awk', a program that you can use to select
  8. particular records in a file and perform operations upon them.
  9.    This is Edition 1.0.3 of `Effective AWK Programming', for the
  10. 3.0.3 version of the GNU implementation of AWK.
  11.    Copyright (C) 1989, 1991, 92, 93, 96, 97 Free Software Foundation,
  12.    Permission is granted to make and distribute verbatim copies of this
  13. manual provided the copyright notice and this permission notice are
  14. preserved on all copies.
  15.    Permission is granted to copy and distribute modified versions of
  16. this manual under the conditions for verbatim copying, provided that
  17. the entire resulting derived work is distributed under the terms of a
  18. permission notice identical to this one.
  19.    Permission is granted to copy and distribute translations of this
  20. manual into another language, under the above conditions for modified
  21. versions, except that this permission notice may be stated in a
  22. translation approved by the Foundation.
  23. File: gawk.info,  Node: Top,  Next: Preface,  Prev: (dir),  Up: (dir)
  24. General Introduction
  25. ********************
  26.    This file documents `awk', a program that you can use to select
  27. particular records in a file and perform operations upon them.
  28.    This is Edition 1.0.3 of `Effective AWK Programming',
  29. for the 3.0.3 version of the GNU implementation
  30. of AWK.
  31. * Menu:
  32. * Preface::                     What this Info file is about; brief
  33.                                 history and acknowledgements.
  34. * What Is Awk::                 What is the `awk' language; using this
  35.                                 Info file.
  36. * Getting Started::             A basic introduction to using `awk'. How
  37.                                 to run an `awk' program. Command line
  38.                                 syntax.
  39. * One-liners::                  Short, sample `awk' programs.
  40. * Regexp::                      All about matching things using regular
  41.                                 expressions.
  42. * Reading Files::               How to read files and manipulate fields.
  43. * Printing::                    How to print using `awk'.  Describes the
  44.                                 `print' and `printf' statements.
  45.                                 Also describes redirection of output.
  46. * Expressions::                 Expressions are the basic building blocks of
  47.                                 statements.
  48. * Patterns and Actions::        Overviews of patterns and actions.
  49. * Statements::                  The various control statements are described
  50.                                 in detail.
  51. * Built-in Variables::          Built-in Variables
  52. * Arrays::                      The description and use of arrays. Also
  53.                                 includes array-oriented control statements.
  54. * Built-in::                    The built-in functions are summarized here.
  55. * User-defined::                User-defined functions are described in
  56.                                 detail.
  57. * Invoking Gawk::               How to run `gawk'.
  58. * Library Functions::           A Library of `awk' Functions.
  59. * Sample Programs::             Many `awk' programs with complete
  60.                                 explanations.
  61. * Language History::            The evolution of the `awk' language.
  62. * Gawk Summary::                `gawk' Options and Language Summary.
  63. * Installation::                Installing `gawk' under various operating
  64.                                 systems.
  65. * Notes::                       Something about the implementation of
  66.                                 `gawk'.
  67. * Glossary::                    An explanation of some unfamiliar terms.
  68. * Copying::                     Your right to copy and distribute `gawk'.
  69. * Index::                       Concept and Variable Index.
  70. * History::                     The history of `gawk' and `awk'.
  71. * Manual History::              Brief history of the GNU project and this
  72.                                 Info file.
  73. * Acknowledgements::            Acknowledgements.
  74. * This Manual::                 Using this Info file. Includes sample
  75.                                 input files that you can use.
  76. * Conventions::                 Typographical Conventions.
  77. * Sample Data Files::           Sample data files for use in the `awk'
  78.                                 programs illustrated in this Info file.
  79. * Names::                       What name to use to find `awk'.
  80. * Running gawk::                How to run `gawk' programs; includes
  81.                                 command line syntax.
  82. * One-shot::                    Running a short throw-away `awk' program.
  83. * Read Terminal::               Using no input files (input from terminal
  84.                                 instead).
  85. * Long::                        Putting permanent `awk' programs in
  86.                                 files.
  87. * Executable Scripts::          Making self-contained `awk' programs.
  88. * Comments::                    Adding documentation to `gawk' programs.
  89. * Very Simple::                 A very simple example.
  90. * Two Rules::                   A less simple one-line example with two rules.
  91. * More Complex::                A more complex example.
  92. * Statements/Lines::            Subdividing or combining statements into
  93.                                 lines.
  94. * Other Features::              Other Features of `awk'.
  95. * When::                        When to use `gawk' and when to use other
  96.                                 things.
  97. * Regexp Usage::                How to Use Regular Expressions.
  98. * Escape Sequences::            How to write non-printing characters.
  99. * Regexp Operators::            Regular Expression Operators.
  100. * GNU Regexp Operators::        Operators specific to GNU software.
  101. * Case-sensitivity::            How to do case-insensitive matching.
  102. * Leftmost Longest::            How much text matches.
  103. * Computed Regexps::            Using Dynamic Regexps.
  104. * Records::                     Controlling how data is split into records.
  105. * Fields::                      An introduction to fields.
  106. * Non-Constant Fields::         Non-constant Field Numbers.
  107. * Changing Fields::             Changing the Contents of a Field.
  108. * Field Separators::            The field separator and how to change it.
  109. * Basic Field Splitting::       How fields are split with single characters or
  110.                                 simple strings.
  111. * Regexp Field Splitting::      Using regexps as the field separator.
  112. * Single Character Fields::     Making each character a separate field.
  113. * Command Line Field Separator:: Setting `FS' from the command line.
  114. * Field Splitting Summary::     Some final points and a summary table.
  115. * Constant Size::               Reading constant width data.
  116. * Multiple Line::               Reading multi-line records.
  117. * Getline::                     Reading files under explicit program control
  118.                                 using the `getline' function.
  119. * Getline Intro::               Introduction to the `getline' function.
  120. * Plain Getline::               Using `getline' with no arguments.
  121. * Getline/Variable::            Using `getline' into a variable.
  122. * Getline/File::                Using `getline' from a file.
  123. * Getline/Variable/File::       Using `getline' into a variable from a
  124.                                 file.
  125. * Getline/Pipe::                Using `getline' from a pipe.
  126. * Getline/Variable/Pipe::       Using `getline' into a variable from a
  127.                                 pipe.
  128. * Getline Summary::             Summary Of `getline' Variants.
  129. * Print::                       The `print' statement.
  130. * Print Examples::              Simple examples of `print' statements.
  131. * Output Separators::           The output separators and how to change them.
  132. * OFMT::                        Controlling Numeric Output With `print'.
  133. * Printf::                      The `printf' statement.
  134. * Basic Printf::                Syntax of the `printf' statement.
  135. * Control Letters::             Format-control letters.
  136. * Format Modifiers::            Format-specification modifiers.
  137. * Printf Examples::             Several examples.
  138. * Redirection::                 How to redirect output to multiple files and
  139.                                 pipes.
  140. * Special Files::               File name interpretation in `gawk'.
  141.                                 `gawk' allows access to inherited file
  142.                                 descriptors.
  143. * Close Files And Pipes::       Closing Input and Output Files and Pipes.
  144. * Constants::                   String, numeric, and regexp constants.
  145. * Scalar Constants::            Numeric and string constants.
  146. * Regexp Constants::            Regular Expression constants.
  147. * Using Constant Regexps::      When and how to use a regexp constant.
  148. * Variables::                   Variables give names to values for later use.
  149. * Using Variables::             Using variables in your programs.
  150. * Assignment Options::          Setting variables on the command line and a
  151.                                 summary of command line syntax. This is an
  152.                                 advanced method of input.
  153. * Conversion::                  The conversion of strings to numbers and vice
  154.                                 versa.
  155. * Arithmetic Ops::              Arithmetic operations (`+', `-',
  156.                                 etc.)
  157. * Concatenation::               Concatenating strings.
  158. * Assignment Ops::              Changing the value of a variable or a field.
  159. * Increment Ops::               Incrementing the numeric value of a variable.
  160. * Truth Values::                What is "true" and what is "false".
  161. * Typing and Comparison::       How variables acquire types, and how this
  162.                                 affects comparison of numbers and strings with
  163.                                 `<', etc.
  164. * Boolean Ops::                 Combining comparison expressions using boolean
  165.                                 operators `||' ("or"), `&&'
  166.                                 ("and") and `!' ("not").
  167. * Conditional Exp::             Conditional expressions select between two
  168.                                 subexpressions under control of a third
  169.                                 subexpression.
  170. * Function Calls::              A function call is an expression.
  171. * Precedence::                  How various operators nest.
  172. * Pattern Overview::            What goes into a pattern.
  173. * Kinds of Patterns::           A list of all kinds of patterns.
  174. * Regexp Patterns::             Using regexps as patterns.
  175. * Expression Patterns::         Any expression can be used as a pattern.
  176. * Ranges::                      Pairs of patterns specify record ranges.
  177. * BEGIN/END::                   Specifying initialization and cleanup rules.
  178. * Using BEGIN/END::             How and why to use BEGIN/END rules.
  179. * I/O And BEGIN/END::           I/O issues in BEGIN/END rules.
  180. * Empty::                       The empty pattern, which matches every record.
  181. * Action Overview::             What goes into an action.
  182. * If Statement::                Conditionally execute some `awk'
  183.                                 statements.
  184. * While Statement::             Loop until some condition is satisfied.
  185. * Do Statement::                Do specified action while looping until some
  186.                                 condition is satisfied.
  187. * For Statement::               Another looping statement, that provides
  188.                                 initialization and increment clauses.
  189. * Break Statement::             Immediately exit the innermost enclosing loop.
  190. * Continue Statement::          Skip to the end of the innermost enclosing
  191.                                 loop.
  192. * Next Statement::              Stop processing the current input record.
  193. * Nextfile Statement::          Stop processing the current file.
  194. * Exit Statement::              Stop execution of `awk'.
  195. * User-modified::               Built-in variables that you change to control
  196.                                 `awk'.
  197. * Auto-set::                    Built-in variables where `awk' gives you
  198.                                 information.
  199. * ARGC and ARGV::               Ways to use `ARGC' and `ARGV'.
  200. * Array Intro::                 Introduction to Arrays
  201. * Reference to Elements::       How to examine one element of an array.
  202. * Assigning Elements::          How to change an element of an array.
  203. * Array Example::               Basic Example of an Array
  204. * Scanning an Array::           A variation of the `for' statement. It
  205.                                 loops through the indices of an array's
  206.                                 existing elements.
  207. * Delete::                      The `delete' statement removes an element
  208.                                 from an array.
  209. * Numeric Array Subscripts::    How to use numbers as subscripts in
  210.                                 `awk'.
  211. * Uninitialized Subscripts::    Using Uninitialized variables as subscripts.
  212. * Multi-dimensional::           Emulating multi-dimensional arrays in
  213.                                 `awk'.
  214. * Multi-scanning::              Scanning multi-dimensional arrays.
  215. * Calling Built-in::            How to call built-in functions.
  216. * Numeric Functions::           Functions that work with numbers, including
  217.                                 `int', `sin' and `rand'.
  218. * String Functions::            Functions for string manipulation, such as
  219.                                 `split', `match', and
  220.                                 `sprintf'.
  221. * I/O Functions::               Functions for files and shell commands.
  222. * Time Functions::              Functions for dealing with time stamps.
  223. * Definition Syntax::           How to write definitions and what they mean.
  224. * Function Example::            An example function definition and what it
  225.                                 does.
  226. * Function Caveats::            Things to watch out for.
  227. * Return Statement::            Specifying the value a function returns.
  228. * Options::                     Command line options and their meanings.
  229. * Other Arguments::             Input file names and variable assignments.
  230. * AWKPATH Variable::            Searching directories for `awk' programs.
  231. * Obsolete::                    Obsolete Options and/or features.
  232. * Undocumented::                Undocumented Options and Features.
  233. * Known Bugs::                  Known Bugs in `gawk'.
  234. * Portability Notes::           What to do if you don't have `gawk'.
  235. * Nextfile Function::           Two implementations of a `nextfile'
  236.                                 function.
  237. * Assert Function::             A function for assertions in `awk'
  238.                                 programs.
  239. * Round Function::              A function for rounding if `sprintf' does
  240.                                 not do it correctly.
  241. * Ordinal Functions::           Functions for using characters as numbers and
  242.                                 vice versa.
  243. * Join Function::               A function to join an array into a string.
  244. * Mktime Function::             A function to turn a date into a timestamp.
  245. * Gettimeofday Function::       A function to get formatted times.
  246. * Filetrans Function::          A function for handling data file transitions.
  247. * Getopt Function::             A function for processing command line
  248.                                 arguments.
  249. * Passwd Functions::            Functions for getting user information.
  250. * Group Functions::             Functions for getting group information.
  251. * Library Names::               How to best name private global variables in
  252.                                 library functions.
  253. * Clones::                      Clones of common utilities.
  254. * Cut Program::                 The `cut' utility.
  255. * Egrep Program::               The `egrep' utility.
  256. * Id Program::                  The `id' utility.
  257. * Split Program::               The `split' utility.
  258. * Tee Program::                 The `tee' utility.
  259. * Uniq Program::                The `uniq' utility.
  260. * Wc Program::                  The `wc' utility.
  261. * Miscellaneous Programs::      Some interesting `awk' programs.
  262. * Dupword Program::             Finding duplicated words in a document.
  263. * Alarm Program::               An alarm clock.
  264. * Translate Program::           A program similar to the `tr' utility.
  265. * Labels Program::              Printing mailing labels.
  266. * Word Sorting::                A program to produce a word usage count.
  267. * History Sorting::             Eliminating duplicate entries from a history
  268.                                 file.
  269. * Extract Program::             Pulling out programs from Texinfo source
  270.                                 files.
  271. * Simple Sed::                  A Simple Stream Editor.
  272. * Igawk Program::               A wrapper for `awk' that includes files.
  273. * V7/SVR3.1::                   The major changes between V7 and System V
  274.                                 Release 3.1.
  275. * SVR4::                        Minor changes between System V Releases 3.1
  276.                                 and 4.
  277. * POSIX::                       New features from the POSIX standard.
  278. * BTL::                         New features from the Bell Laboratories
  279.                                 version of `awk'.
  280. * POSIX/GNU::                   The extensions in `gawk' not in POSIX
  281.                                 `awk'.
  282. * Command Line Summary::        Recapitulation of the command line.
  283. * Language Summary::            A terse review of the language.
  284. * Variables/Fields::            Variables, fields, and arrays.
  285. * Fields Summary::              Input field splitting.
  286. * Built-in Summary::            `awk''s built-in variables.
  287. * Arrays Summary::              Using arrays.
  288. * Data Type Summary::           Values in `awk' are numbers or strings.
  289. * Rules Summary::               Patterns and Actions, and their component
  290.                                 parts.
  291. * Pattern Summary::             Quick overview of patterns.
  292. * Regexp Summary::              Quick overview of regular expressions.
  293. * Actions Summary::             Quick overview of actions.
  294. * Operator Summary::            `awk' operators.
  295. * Control Flow Summary::        The control statements.
  296. * I/O Summary::                 The I/O statements.
  297. * Printf Summary::              A summary of `printf'.
  298. * Special File Summary::        Special file names interpreted internally.
  299. * Built-in Functions Summary::  Built-in numeric and string functions.
  300. * Time Functions Summary::      Built-in time functions.
  301. * String Constants Summary::    Escape sequences in strings.
  302. * Functions Summary::           Defining and calling functions.
  303. * Historical Features::         Some undocumented but supported "features".
  304. * Gawk Distribution::           What is in the `gawk' distribution.
  305. * Getting::                     How to get the distribution.
  306. * Extracting::                  How to extract the distribution.
  307. * Distribution contents::       What is in the distribution.
  308. * Unix Installation::           Installing `gawk' under various versions
  309.                                 of Unix.
  310. * Quick Installation::          Compiling `gawk' under Unix.
  311. * Configuration Philosophy::    How it's all supposed to work.
  312. * VMS Installation::            Installing `gawk' on VMS.
  313. * VMS Compilation::             How to compile `gawk' under VMS.
  314. * VMS Installation Details::    How to install `gawk' under VMS.
  315. * VMS Running::                 How to run `gawk' under VMS.
  316. * VMS POSIX::                   Alternate instructions for VMS POSIX.
  317. * PC Installation::             Installing and Compiling `gawk' on MS-DOS
  318.                                 and OS/2
  319. * Atari Installation::          Installing `gawk' on the Atari ST.
  320. * Atari Compiling::             Compiling `gawk' on Atari
  321. * Atari Using::                 Running `gawk' on Atari
  322. * Amiga Installation::          Installing `gawk' on an Amiga.
  323. * Bugs::                        Reporting Problems and Bugs.
  324. * Other Versions::              Other freely available `awk'
  325.                                 implementations.
  326. * Compatibility Mode::          How to disable certain `gawk' extensions.
  327. * Additions::                   Making Additions To `gawk'.
  328. * Adding Code::                 Adding code to the main body of `gawk'.
  329. * New Ports::                   Porting `gawk' to a new operating system.
  330. * Future Extensions::           New features that may be implemented one day.
  331. * Improvements::                Suggestions for improvements by volunteers.
  332.                   To Miriam, for making me complete.
  333.                   To Chana, for the joy you bring us.
  334.                 To Rivka, for the exponential increase.
  335.                   To Nachum, for the added dimension.
  336. File: gawk.info,  Node: Preface,  Next: What Is Awk,  Prev: Top,  Up: Top
  337. Preface
  338. *******
  339.    This Info file teaches you about the `awk' language and how you can
  340. use it effectively.  You should already be familiar with basic system
  341. commands, such as `cat' and `ls',(1) and basic shell facilities, such
  342. as Input/Output (I/O) redirection and pipes.
  343.    Implementations of the `awk' language are available for many
  344. different computing environments.  This Info file, while describing the
  345. `awk' language in general, also describes a particular implementation
  346. of `awk' called `gawk' (which stands for "GNU Awk").  `gawk' runs on a
  347. broad range of Unix systems, ranging from 80386 PC-based computers, up
  348. through large scale systems, such as Crays. `gawk' has also been ported
  349. to MS-DOS and OS/2 PC's, Atari and Amiga micro-computers, and VMS.
  350. * Menu:
  351. * History::                     The history of `gawk' and `awk'.
  352. * Manual History::              Brief history of the GNU project and this
  353.                                 Info file.
  354. * Acknowledgements::            Acknowledgements.
  355.    ---------- Footnotes ----------
  356.    (1)  These commands are available on POSIX compliant systems, as
  357. well as on traditional Unix based systems. If you are using some other
  358. operating system, you still need to be familiar with the ideas of I/O
  359. redirection and pipes.
  360. File: gawk.info,  Node: History,  Next: Manual History,  Prev: Preface,  Up: Preface
  361. History of `awk' and `gawk'
  362. ===========================
  363.    The name `awk' comes from the initials of its designers: Alfred V.
  364. Aho, Peter J. Weinberger, and Brian W. Kernighan.  The original version
  365. of `awk' was written in 1977 at AT&T Bell Laboratories.  In 1985 a new
  366. version made the programming language more powerful, introducing
  367. user-defined functions, multiple input streams, and computed regular
  368. expressions.  This new version became generally available with Unix
  369. System V Release 3.1.  The version in System V Release 4 added some new
  370. features and also cleaned up the behavior in some of the "dark corners"
  371. of the language.  The specification for `awk' in the POSIX Command
  372. Language and Utilities standard further clarified the language based on
  373. feedback from both the `gawk' designers, and the original Bell Labs
  374. `awk' designers.
  375.    The GNU implementation, `gawk', was written in 1986 by Paul Rubin
  376. and Jay Fenlason, with advice from Richard Stallman.  John Woods
  377. contributed parts of the code as well.  In 1988 and 1989, David
  378. Trueman, with help from Arnold Robbins, thoroughly reworked `gawk' for
  379. compatibility with the newer `awk'.  Current development focuses on bug
  380. fixes, performance improvements, standards compliance, and
  381. occasionally, new features.
  382. File: gawk.info,  Node: Manual History,  Next: Acknowledgements,  Prev: History,  Up: Preface
  383. The GNU Project and This Book
  384. =============================
  385.    The Free Software Foundation (FSF) is a non-profit organization
  386. dedicated to the production and distribution of freely distributable
  387. software.  It was founded by Richard M. Stallman, the author of the
  388. original Emacs editor.  GNU Emacs is the most widely used version of
  389. Emacs today.
  390.    The GNU project is an on-going effort on the part of the Free
  391. Software Foundation to create a complete, freely distributable, POSIX
  392. compliant computing environment.  (GNU stands for "GNU's not Unix".)
  393. The FSF uses the "GNU General Public License" (or GPL) to ensure that
  394. source code for their software is always available to the end user. A
  395. copy of the GPL is included for your reference (*note GNU GENERAL
  396. PUBLIC LICENSE: Copying.).  The GPL applies to the C language source
  397. code for `gawk'.
  398.    A shell, an editor (Emacs), highly portable optimizing C, C++, and
  399. Objective-C compilers, a symbolic debugger, and dozens of large and
  400. small utilities (such as `gawk'), have all been completed and are
  401. freely available.  As of this writing (early 1997), the GNU operating
  402. system kernel (the HURD), has been released, but is still in an early
  403. stage of development.
  404.    Until the GNU operating system is more fully developed, you should
  405. consider using Linux, a freely distributable, Unix-like operating
  406. system for 80386, DEC Alpha, Sun SPARC and other systems.  There are
  407. many books on Linux. One freely available one is `Linux Installation
  408. and Getting Started', by Matt Welsh.  Many Linux distributions are
  409. available, often in computer stores or bundled on CD-ROM with books
  410. about Linux.  (There are three other freely available, Unix-like
  411. operating systems for 80386 and other systems, NetBSD, FreeBSD,and
  412. OpenBSD. All are based on the 4.4-Lite Berkeley Software Distribution,
  413. and they use recent versions of `gawk' for their versions of `awk'.)
  414.    This Info file itself has gone through several previous, preliminary
  415. editions.  I started working on a preliminary draft of `The GAWK
  416. Manual', by Diane Close, Paul Rubin, and Richard Stallman in the fall
  417. of 1988.  It was around 90 pages long, and barely described the
  418. original, "old" version of `awk'. After substantial revision, the first
  419. version of the `The GAWK Manual' to be released was Edition 0.11 Beta in
  420. October of 1989.  The manual then underwent more substantial revision
  421. for Edition 0.13 of December 1991.  David Trueman, Pat Rankin, and
  422. Michal Jaegermann contributed sections of the manual for Edition 0.13.
  423. That edition was published by the FSF as a bound book early in 1992.
  424. Since then there have been several minor revisions, notably Edition
  425. 0.14 of November 1992 that was published by the FSF in January of 1993,
  426. and Edition 0.16 of August 1993.
  427.    Edition 1.0 of `Effective AWK Programming' represents a significant
  428. re-working of `The GAWK Manual', with much additional material.  The
  429. FSF and I agree that I am now the primary author.  I also felt that it
  430. needed a more descriptive title.
  431.    `Effective AWK Programming' will undoubtedly continue to evolve.  An
  432. electronic version comes with the `gawk' distribution from the FSF.  If
  433. you find an error in this Info file, please report it!  *Note Reporting
  434. Problems and Bugs: Bugs, for information on submitting problem reports
  435. electronically, or write to me in care of the FSF.
  436. File: gawk.info,  Node: Acknowledgements,  Prev: Manual History,  Up: Preface
  437. Acknowledgements
  438. ================
  439.    I would like to acknowledge Richard M. Stallman, for his vision of a
  440. better world, and for his courage in founding the FSF and starting the
  441. GNU project.
  442.    The initial draft of `The GAWK Manual' had the following
  443. acknowledgements:
  444.      Many people need to be thanked for their assistance in producing
  445.      this manual.  Jay Fenlason contributed many ideas and sample
  446.      programs.  Richard Mlynarik and Robert Chassell gave helpful
  447.      comments on drafts of this manual.  The paper `A Supplemental
  448.      Document for `awk'' by John W.  Pierce of the Chemistry Department
  449.      at UC San Diego, pinpointed several issues relevant both to `awk'
  450.      implementation and to this manual, that would otherwise have
  451.      escaped us.
  452.    The following people provided many helpful comments on Edition 0.13
  453. of `The GAWK Manual': Rick Adams, Michael Brennan, Rich Burridge, Diane
  454. Close, Christopher ("Topher") Eliot, Michael Lijewski, Pat Rankin,
  455. Miriam Robbins, and Michal Jaegermann.
  456.    The following people provided many helpful comments for Edition 1.0
  457. of `Effective AWK Programming': Karl Berry, Michael Brennan, Darrel
  458. Hankerson, Michal Jaegermann, Michael Lijewski, and Miriam Robbins.
  459. Pat Rankin, Michal Jaegermann, Darrel Hankerson and Scott Deifik
  460. updated their respective sections for Edition 1.0.
  461.    Robert J. Chassell provided much valuable advice on the use of
  462. Texinfo.  He also deserves special thanks for convincing me *not* to
  463. title this Info file `How To Gawk Politely'.  Karl Berry helped
  464. significantly with the TeX part of Texinfo.
  465.    David Trueman deserves special credit; he has done a yeoman job of
  466. evolving `gawk' so that it performs well, and without bugs.  Although
  467. he is no longer involved with `gawk', working with him on this project
  468. was a significant pleasure.
  469.    Scott Deifik, Darrel Hankerson, Kai Uwe Rommel, Pat Rankin, and
  470. Michal Jaegermann (in no particular order) are long time members of the
  471. `gawk' "crack portability team."  Without their hard work and help,
  472. `gawk' would not be nearly the fine program it is today.  It has been
  473. and continues to be a pleasure working with this team of fine people.
  474.    Jeffrey Friedl provided invaluable help in tracking down a number of
  475. last minute problems with regular expressions in `gawk' 3.0.
  476.    David and I would like to thank Brian Kernighan of Bell Labs for
  477. invaluable assistance during the testing and debugging of `gawk', and
  478. for help in clarifying numerous points about the language.  We could
  479. not have done nearly as good a job on either `gawk' or its
  480. documentation without his help.
  481.    I would like to thank Marshall and Elaine Hartholz of Seattle, and
  482. Dr.  Bert and Rita Schreiber of Detroit for large amounts of quiet
  483. vacation time in their homes, which allowed me to make significant
  484. progress on this Info file and on `gawk' itself.  Phil Hughes of SSC
  485. contributed in a very important way by loaning me his laptop Linux
  486. system, not once, but twice, allowing me to do a lot of work while away
  487. from home.
  488.    Finally, I must thank my wonderful wife, Miriam, for her patience
  489. through the many versions of this project, for her proof-reading, and
  490. for sharing me with the computer.  I would like to thank my parents for
  491. their love, and for the grace with which they raised and educated me.
  492. I also must acknowledge my gratitude to G-d, for the many opportunities
  493. He has sent my way, as well as for the gifts He has given me with which
  494. to take advantage of those opportunities.
  495. Arnold Robbins
  496. Atlanta, Georgia
  497. February, 1997
  498. File: gawk.info,  Node: What Is Awk,  Next: Getting Started,  Prev: Preface,  Up: Top
  499. Introduction
  500. ************
  501.    If you are like many computer users, you would frequently like to
  502. make changes in various text files wherever certain patterns appear, or
  503. extract data from parts of certain lines while discarding the rest.  To
  504. write a program to do this in a language such as C or Pascal is a
  505. time-consuming inconvenience that may take many lines of code.  The job
  506. may be easier with `awk'.
  507.    The `awk' utility interprets a special-purpose programming language
  508. that makes it possible to handle simple data-reformatting jobs with
  509. just a few lines of code.
  510.    The GNU implementation of `awk' is called `gawk'; it is fully upward
  511. compatible with the System V Release 4 version of `awk'.  `gawk' is
  512. also upward compatible with the POSIX specification of the `awk'
  513. language.  This means that all properly written `awk' programs should
  514. work with `gawk'.  Thus, we usually don't distinguish between `gawk'
  515. and other `awk' implementations.
  516.    Using `awk' you can:
  517.    * manage small, personal databases
  518.    * generate reports
  519.    * validate data
  520.    * produce indexes, and perform other document preparation tasks
  521.    * even experiment with algorithms that can be adapted later to other
  522.      computer languages
  523. * Menu:
  524. * This Manual::                 Using this Info file. Includes sample
  525.                                 input files that you can use.
  526. * Conventions::                 Typographical Conventions.
  527. * Sample Data Files::           Sample data files for use in the `awk'
  528.                                 programs illustrated in this Info file.
  529. File: gawk.info,  Node: This Manual,  Next: Conventions,  Prev: What Is Awk,  Up: What Is Awk
  530. Using This Book
  531. ===============
  532.    The term `awk' refers to a particular program, and to the language
  533. you use to tell this program what to do.  When we need to be careful,
  534. we call the program "the `awk' utility" and the language "the `awk'
  535. language."  The term `gawk' refers to a version of `awk' developed as
  536. part the GNU project.  The purpose of this Info file is to explain both
  537. the `awk' language and how to run the `awk' utility.
  538.    The main purpose of the Info file is to explain the features of
  539. `awk', as defined in the POSIX standard.  It does so in the context of
  540. one particular implementation, `gawk'. While doing so, it will also
  541. attempt to describe important differences between `gawk' and other
  542. `awk' implementations.  Finally, any `gawk' features that are not in
  543. the POSIX standard for `awk' will be noted.
  544.    The term "`awk' program" refers to a program written by you in the
  545. `awk' programming language.
  546.    *Note Getting Started with `awk': Getting Started, for the bare
  547. essentials you need to know to start using `awk'.
  548.    Some useful "one-liners" are included to give you a feel for the
  549. `awk' language (*note Useful One Line Programs: One-liners.).
  550.    Many sample `awk' programs have been provided for you (*note A
  551. Library of `awk' Functions: Library Functions.; also *note Practical
  552. `awk' Programs: Sample Programs.).
  553.    The entire `awk' language is summarized for quick reference in *Note
  554. `gawk' Summary: Gawk Summary.  Look there if you just need to refresh
  555. your memory about a particular feature.
  556.    If you find terms that you aren't familiar with, try looking them up
  557. in the glossary (*note Glossary::.).
  558.    Most of the time complete `awk' programs are used as examples, but in
  559. some of the more advanced sections, only the part of the `awk' program
  560. that illustrates the concept being described is shown.
  561.    While this Info file is aimed principally at people who have not been
  562. exposed to `awk', there is a lot of information here that even the `awk'
  563. expert should find useful.  In particular, the description of POSIX
  564. `awk', and the example programs in *Note A Library of `awk' Functions:
  565. Library Functions, and *Note Practical `awk' Programs: Sample Programs,
  566. should be of interest.
  567. Dark Corners
  568. ------------
  569.      Who opened that window shade?!?
  570.      Count Dracula
  571.    Until the POSIX standard (and `The Gawk Manual'), many features of
  572. `awk' were either poorly documented, or not documented at all.
  573. Descriptions of such features (often called "dark corners") are noted
  574. in this Info file with "(d.c.)".  They also appear in the index under
  575. the heading "dark corner."
  576. File: gawk.info,  Node: Conventions,  Next: Sample Data Files,  Prev: This Manual,  Up: What Is Awk
  577. Typographical Conventions
  578. =========================
  579.    This Info file is written using Texinfo, the GNU documentation
  580. formatting language.  A single Texinfo source file is used to produce
  581. both the printed and on-line versions of the documentation.  This
  582. section briefly documents the typographical conventions used in Texinfo.
  583.    Examples you would type at the command line are preceded by the
  584. common shell primary and secondary prompts, `$' and `>'.  Output from
  585. the command is preceded by the glyph "-|".  This typically represents
  586. the command's standard output.  Error messages, and other output on the
  587. command's standard error, are preceded by the glyph "error-->".  For
  588. example:
  589.      $ echo hi on stdout
  590.      -| hi on stdout
  591.      $ echo hello on stderr 1>&2
  592.      error--> hello on stderr
  593.    Characters that you type at the keyboard look `like this'.  In
  594. particular, there are special characters called "control characters."
  595. These are characters that you type by holding down both the `CONTROL'
  596. key and another key, at the same time.  For example, a `Control-d' is
  597. typed by first pressing and holding the `CONTROL' key, next pressing
  598. the `d' key, and finally releasing both keys.
  599. File: gawk.info,  Node: Sample Data Files,  Prev: Conventions,  Up: What Is Awk
  600. Data Files for the Examples
  601. ===========================
  602.    Many of the examples in this Info file take their input from two
  603. sample data files.  The first, called `BBS-list', represents a list of
  604. computer bulletin board systems together with information about those
  605. systems.  The second data file, called `inventory-shipped', contains
  606. information about shipments on a monthly basis.  In both files, each
  607. line is considered to be one "record".
  608.    In the file `BBS-list', each record contains the name of a computer
  609. bulletin board, its phone number, the board's baud rate(s), and a code
  610. for the number of hours it is operational.  An `A' in the last column
  611. means the board operates 24 hours a day.  A `B' in the last column
  612. means the board operates evening and weekend hours, only.  A `C' means
  613. the board operates only on weekends.
  614.      aardvark     555-5553     1200/300          B
  615.      alpo-net     555-3412     2400/1200/300     A
  616.      barfly       555-7685     1200/300          A
  617.      bites        555-1675     2400/1200/300     A
  618.      camelot      555-0542     300               C
  619.      core         555-2912     1200/300          C
  620.      fooey        555-1234     2400/1200/300     B
  621.      foot         555-6699     1200/300          B
  622.      macfoo       555-6480     1200/300          A
  623.      sdace        555-3430     2400/1200/300     A
  624.      sabafoo      555-2127     1200/300          C
  625.    The second data file, called `inventory-shipped', represents
  626. information about shipments during the year.  Each record contains the
  627. month of the year, the number of green crates shipped, the number of
  628. red boxes shipped, the number of orange bags shipped, and the number of
  629. blue packages shipped, respectively.  There are 16 entries, covering
  630. the 12 months of one year and four months of the next year.
  631.      Jan  13  25  15 115
  632.      Feb  15  32  24 226
  633.      Mar  15  24  34 228
  634.      Apr  31  52  63 420
  635.      May  16  34  29 208
  636.      Jun  31  42  75 492
  637.      Jul  24  34  67 436
  638.      Aug  15  34  47 316
  639.      Sep  13  55  37 277
  640.      Oct  29  54  68 525
  641.      Nov  20  87  82 577
  642.      Dec  17  35  61 401
  643.      
  644.      Jan  21  36  64 620
  645.      Feb  26  58  80 652
  646.      Mar  24  75  70 495
  647.      Apr  21  70  74 514
  648.    If you are reading this in GNU Emacs using Info, you can copy the
  649. regions of text showing these sample files into your own test files.
  650. This way you can try out the examples shown in the remainder of this
  651. document.  You do this by using the command `M-x write-region' to copy
  652. text from the Info file into a file for use with `awk' (*Note
  653. Miscellaneous File Operations: (emacs)Misc File Ops, for more
  654. information).  Using this information, create your own `BBS-list' and
  655. `inventory-shipped' files, and practice what you learn in this Info
  656. file.
  657.    If you are using the stand-alone version of Info, see *Note
  658. Extracting Programs from Texinfo Source Files: Extract Program, for an
  659. `awk' program that will extract these data files from `gawk.texi', the
  660. Texinfo source file for this Info file.
  661. File: gawk.info,  Node: Getting Started,  Next: One-liners,  Prev: What Is Awk,  Up: Top
  662. Getting Started with `awk'
  663. **************************
  664.    The basic function of `awk' is to search files for lines (or other
  665. units of text) that contain certain patterns.  When a line matches one
  666. of the patterns, `awk' performs specified actions on that line.  `awk'
  667. keeps processing input lines in this way until the end of the input
  668. files are reached.
  669.    Programs in `awk' are different from programs in most other
  670. languages, because `awk' programs are "data-driven"; that is, you
  671. describe the data you wish to work with, and then what to do when you
  672. find it.  Most other languages are "procedural"; you have to describe,
  673. in great detail, every step the program is to take.  When working with
  674. procedural languages, it is usually much harder to clearly describe the
  675. data your program will process.  For this reason, `awk' programs are
  676. often refreshingly easy to both write and read.
  677.    When you run `awk', you specify an `awk' "program" that tells `awk'
  678. what to do.  The program consists of a series of "rules".  (It may also
  679. contain "function definitions", an advanced feature which we will
  680. ignore for now.  *Note User-defined Functions: User-defined.)  Each
  681. rule specifies one pattern to search for, and one action to perform
  682. when that pattern is found.
  683.    Syntactically, a rule consists of a pattern followed by an action.
  684. The action is enclosed in curly braces to separate it from the pattern.
  685. Rules are usually separated by newlines.  Therefore, an `awk' program
  686. looks like this:
  687.      PATTERN { ACTION }
  688.      PATTERN { ACTION }
  689.      ...
  690. * Menu:
  691. * Names::                       What name to use to find `awk'.
  692. * Running gawk::                How to run `gawk' programs; includes
  693.                                 command line syntax.
  694. * Very Simple::                 A very simple example.
  695. * Two Rules::                   A less simple one-line example with two rules.
  696. * More Complex::                A more complex example.
  697. * Statements/Lines::            Subdividing or combining statements into
  698.                                 lines.
  699. * Other Features::              Other Features of `awk'.
  700. * When::                        When to use `gawk' and when to use other
  701.                                 things.
  702. File: gawk.info,  Node: Names,  Next: Running gawk,  Prev: Getting Started,  Up: Getting Started
  703. A Rose By Any Other Name
  704. ========================
  705.    The `awk' language has evolved over the years. Full details are
  706. provided in *Note The Evolution of the `awk' Language: Language History.
  707. The language described in this Info file is often referred to as "new
  708. `awk'."
  709.    Because of this, many systems have multiple versions of `awk'.  Some
  710. systems have an `awk' utility that implements the original version of
  711. the `awk' language, and a `nawk' utility for the new version.  Others
  712. have an `oawk' for the "old `awk'" language, and plain `awk' for the
  713. new one.  Still others only have one version, usually the new one.(1)
  714.    All in all, this makes it difficult for you to know which version of
  715. `awk' you should run when writing your programs.  The best advice we
  716. can give here is to check your local documentation. Look for `awk',
  717. `oawk', and `nawk', as well as for `gawk'. Chances are, you will have
  718. some version of new `awk' on your system, and that is what you should
  719. use when running your programs.  (Of course, if you're reading this
  720. Info file, chances are good that you have `gawk'!)
  721.    Throughout this Info file, whenever we refer to a language feature
  722. that should be available in any complete implementation of POSIX `awk',
  723. we simply use the term `awk'.  When referring to a feature that is
  724. specific to the GNU implementation, we use the term `gawk'.
  725.    ---------- Footnotes ----------
  726.    (1)  Often, these systems use `gawk' for their `awk' implementation!
  727. File: gawk.info,  Node: Running gawk,  Next: Very Simple,  Prev: Names,  Up: Getting Started
  728. How to Run `awk' Programs
  729. =========================
  730.    There are several ways to run an `awk' program.  If the program is
  731. short, it is easiest to include it in the command that runs `awk', like
  732. this:
  733.      awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
  734. where PROGRAM consists of a series of patterns and actions, as
  735. described earlier.  (The reason for the single quotes is described
  736. below, in *Note One-shot Throw-away `awk' Programs: One-shot.)
  737.    When the program is long, it is usually more convenient to put it in
  738. a file and run it with a command like this:
  739.      awk -f PROGRAM-FILE INPUT-FILE1 INPUT-FILE2 ...
  740. * Menu:
  741. * One-shot::                    Running a short throw-away `awk' program.
  742. * Read Terminal::               Using no input files (input from terminal
  743.                                 instead).
  744. * Long::                        Putting permanent `awk' programs in
  745.                                 files.
  746. * Executable Scripts::          Making self-contained `awk' programs.
  747. * Comments::                    Adding documentation to `gawk' programs.
  748. File: gawk.info,  Node: One-shot,  Next: Read Terminal,  Prev: Running gawk,  Up: Running gawk
  749. One-shot Throw-away `awk' Programs
  750. ----------------------------------
  751.    Once you are familiar with `awk', you will often type in simple
  752. programs the moment you want to use them.  Then you can write the
  753. program as the first argument of the `awk' command, like this:
  754.      awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
  755. where PROGRAM consists of a series of PATTERNS and ACTIONS, as
  756. described earlier.
  757.    This command format instructs the "shell", or command interpreter,
  758. to start `awk' and use the PROGRAM to process records in the input
  759. file(s).  There are single quotes around PROGRAM so that the shell
  760. doesn't interpret any `awk' characters as special shell characters.
  761. They also cause the shell to treat all of PROGRAM as a single argument
  762. for `awk' and allow PROGRAM to be more than one line long.
  763.    This format is also useful for running short or medium-sized `awk'
  764. programs from shell scripts, because it avoids the need for a separate
  765. file for the `awk' program.  A self-contained shell script is more
  766. reliable since there are no other files to misplace.
  767.    *Note Useful One Line Programs: One-liners, presents several short,
  768. self-contained programs.
  769.    As an interesting side point, the command
  770.      awk '/foo/' FILES ...
  771. is essentially the same as
  772.      egrep foo FILES ...
  773. File: gawk.info,  Node: Read Terminal,  Next: Long,  Prev: One-shot,  Up: Running gawk
  774. Running `awk' without Input Files
  775. ---------------------------------
  776.    You can also run `awk' without any input files.  If you type the
  777. command line:
  778.      awk 'PROGRAM'
  779. then `awk' applies the PROGRAM to the "standard input", which usually
  780. means whatever you type on the terminal.  This continues until you
  781. indicate end-of-file by typing `Control-d'.  (On other operating
  782. systems, the end-of-file character may be different.  For example, on
  783. OS/2 and MS-DOS, it is `Control-z'.)
  784.    For example, the following program prints a friendly piece of advice
  785. (from Douglas Adams' `The Hitchhiker's Guide to the Galaxy'), to keep
  786. you from worrying about the complexities of computer programming
  787. (`BEGIN' is a feature we haven't discussed yet).
  788.      $ awk "BEGIN { print \"Don't Panic!\" }"
  789.      -| Don't Panic!
  790.    This program does not read any input.  The `\' before each of the
  791. inner double quotes is necessary because of the shell's quoting rules,
  792. in particular because it mixes both single quotes and double quotes.
  793.    This next simple `awk' program emulates the `cat' utility; it copies
  794. whatever you type at the keyboard to its standard output. (Why this
  795. works is explained shortly.)
  796.      $ awk '{ print }'
  797.      Now is the time for all good men
  798.      -| Now is the time for all good men
  799.      to come to the aid of their country.
  800.      -| to come to the aid of their country.
  801.      Four score and seven years ago, ...
  802.      -| Four score and seven years ago, ...
  803.      What, me worry?
  804.      -| What, me worry?
  805.      Control-d
  806. File: gawk.info,  Node: Long,  Next: Executable Scripts,  Prev: Read Terminal,  Up: Running gawk
  807. Running Long Programs
  808. ---------------------
  809.    Sometimes your `awk' programs can be very long.  In this case it is
  810. more convenient to put the program into a separate file.  To tell `awk'
  811. to use that file for its program, you type:
  812.      awk -f SOURCE-FILE INPUT-FILE1 INPUT-FILE2 ...
  813.    The `-f' instructs the `awk' utility to get the `awk' program from
  814. the file SOURCE-FILE.  Any file name can be used for SOURCE-FILE.  For
  815. example, you could put the program:
  816.      BEGIN { print "Don't Panic!" }
  817. into the file `advice'.  Then this command:
  818.      awk -f advice
  819. does the same thing as this one:
  820.      awk "BEGIN { print \"Don't Panic!\" }"
  821. which was explained earlier (*note Running `awk' without Input Files:
  822. Read Terminal.).  Note that you don't usually need single quotes around
  823. the file name that you specify with `-f', because most file names don't
  824. contain any of the shell's special characters.  Notice that in
  825. `advice', the `awk' program did not have single quotes around it.  The
  826. quotes are only needed for programs that are provided on the `awk'
  827. command line.
  828.    If you want to identify your `awk' program files clearly as such,
  829. you can add the extension `.awk' to the file name.  This doesn't affect
  830. the execution of the `awk' program, but it does make "housekeeping"
  831. easier.
  832. File: gawk.info,  Node: Executable Scripts,  Next: Comments,  Prev: Long,  Up: Running gawk
  833. Executable `awk' Programs
  834. -------------------------
  835.    Once you have learned `awk', you may want to write self-contained
  836. `awk' scripts, using the `#!' script mechanism.  You can do this on
  837. many Unix systems(1) (and someday on the GNU system).
  838.    For example, you could update the file `advice' to look like this:
  839.      #! /bin/awk -f
  840.      
  841.      BEGIN    { print "Don't Panic!" }
  842. After making this file executable (with the `chmod' utility), you can
  843. simply type `advice' at the shell, and the system will arrange to run
  844. `awk'(2) as if you had typed `awk -f advice'.
  845.      $ advice
  846.      -| Don't Panic!
  847. Self-contained `awk' scripts are useful when you want to write a
  848. program which users can invoke without their having to know that the
  849. program is written in `awk'.
  850.    Some older systems do not support the `#!' mechanism. You can get a
  851. similar effect using a regular shell script.  It would look something
  852. like this:
  853.      : The colon ensures execution by the standard shell.
  854.      awk 'PROGRAM' "$@"
  855.    Using this technique, it is *vital* to enclose the PROGRAM in single
  856. quotes to protect it from interpretation by the shell.  If you omit the
  857. quotes, only a shell wizard can predict the results.
  858.    The `"$@"' causes the shell to forward all the command line
  859. arguments to the `awk' program, without interpretation.  The first
  860. line, which starts with a colon, is used so that this shell script will
  861. work even if invoked by a user who uses the C shell.  (Not all older
  862. systems obey this convention, but many do.)
  863.    ---------- Footnotes ----------
  864.    (1)  The `#!' mechanism works on Linux systems, Unix systems derived
  865. from Berkeley Unix, System V Release 4, and some System V Release 3
  866. systems.
  867.    (2)  The line beginning with `#!' lists the full file name of an
  868. interpreter to be run, and an optional initial command line argument to
  869. pass to that interpreter.  The operating system then runs the
  870. interpreter with the given argument and the full argument list of the
  871. executed program.  The first argument in the list is the full file name
  872. of the `awk' program.  The rest of the argument list will either be
  873. options to `awk', or data files, or both.
  874. File: gawk.info,  Node: Comments,  Prev: Executable Scripts,  Up: Running gawk
  875. Comments in `awk' Programs
  876. --------------------------
  877.    A "comment" is some text that is included in a program for the sake
  878. of human readers; it is not really part of the program.  Comments can
  879. explain what the program does, and how it works.  Nearly all
  880. programming languages have provisions for comments, because programs are
  881. typically hard to understand without their extra help.
  882.    In the `awk' language, a comment starts with the sharp sign
  883. character, `#', and continues to the end of the line.  The `#' does not
  884. have to be the first character on the line. The `awk' language ignores
  885. the rest of a line following a sharp sign.  For example, we could have
  886. put the following into `advice':
  887.      # This program prints a nice friendly message.  It helps
  888.      # keep novice users from being afraid of the computer.
  889.      BEGIN    { print "Don't Panic!" }
  890.    You can put comment lines into keyboard-composed throw-away `awk'
  891. programs also, but this usually isn't very useful; the purpose of a
  892. comment is to help you or another person understand the program at a
  893. later time.
  894. File: gawk.info,  Node: Very Simple,  Next: Two Rules,  Prev: Running gawk,  Up: Getting Started
  895. A Very Simple Example
  896. =====================
  897.    The following command runs a simple `awk' program that searches the
  898. input file `BBS-list' for the string of characters: `foo'.  (A string
  899. of characters is usually called a "string".  The term "string" is
  900. perhaps based on similar usage in English, such as "a string of
  901. pearls," or, "a string of cars in a train.")
  902.      awk '/foo/ { print $0 }' BBS-list
  903. When lines containing `foo' are found, they are printed, because
  904. `print $0' means print the current line.  (Just `print' by itself means
  905. the same thing, so we could have written that instead.)
  906.    You will notice that slashes, `/', surround the string `foo' in the
  907. `awk' program.  The slashes indicate that `foo' is a pattern to search
  908. for.  This type of pattern is called a "regular expression", and is
  909. covered in more detail later (*note Regular Expressions: Regexp.).  The
  910. pattern is allowed to match parts of words.  There are single-quotes
  911. around the `awk' program so that the shell won't interpret any of it as
  912. special shell characters.
  913.    Here is what this program prints:
  914.      $ awk '/foo/ { print $0 }' BBS-list
  915.      -| fooey        555-1234     2400/1200/300     B
  916.      -| foot         555-6699     1200/300          B
  917.      -| macfoo       555-6480     1200/300          A
  918.      -| sabafoo      555-2127     1200/300          C
  919.    In an `awk' rule, either the pattern or the action can be omitted,
  920. but not both.  If the pattern is omitted, then the action is performed
  921. for *every* input line.  If the action is omitted, the default action
  922. is to print all lines that match the pattern.
  923.    Thus, we could leave out the action (the `print' statement and the
  924. curly braces) in the above example, and the result would be the same:
  925. all lines matching the pattern `foo' would be printed.  By comparison,
  926. omitting the `print' statement but retaining the curly braces makes an
  927. empty action that does nothing; then no lines would be printed.
  928. File: gawk.info,  Node: Two Rules,  Next: More Complex,  Prev: Very Simple,  Up: Getting Started
  929. An Example with Two Rules
  930. =========================
  931.    The `awk' utility reads the input files one line at a time.  For
  932. each line, `awk' tries the patterns of each of the rules.  If several
  933. patterns match then several actions are run, in the order in which they
  934. appear in the `awk' program.  If no patterns match, then no actions are
  935.    After processing all the rules (perhaps none) that match the line,
  936. `awk' reads the next line (however, *note The `next' Statement: Next
  937. Statement., and also *note The `nextfile' Statement: Nextfile
  938. Statement.).  This continues until the end of the file is reached.
  939.    For example, the `awk' program:
  940.      /12/  { print $0 }
  941.      /21/  { print $0 }
  942. contains two rules.  The first rule has the string `12' as the pattern
  943. and `print $0' as the action.  The second rule has the string `21' as
  944. the pattern and also has `print $0' as the action.  Each rule's action
  945. is enclosed in its own pair of braces.
  946.    This `awk' program prints every line that contains the string `12'
  947. *or* the string `21'.  If a line contains both strings, it is printed
  948. twice, once by each rule.
  949.    This is what happens if we run this program on our two sample data
  950. files, `BBS-list' and `inventory-shipped', as shown here:
  951.      $ awk '/12/ { print $0 }
  952.      >      /21/ { print $0 }' BBS-list inventory-shipped
  953.      -| aardvark     555-5553     1200/300          B
  954.      -| alpo-net     555-3412     2400/1200/300     A
  955.      -| barfly       555-7685     1200/300          A
  956.      -| bites        555-1675     2400/1200/300     A
  957.      -| core         555-2912     1200/300          C
  958.      -| fooey        555-1234     2400/1200/300     B
  959.      -| foot         555-6699     1200/300          B
  960.      -| macfoo       555-6480     1200/300          A
  961.      -| sdace        555-3430     2400/1200/300     A
  962.      -| sabafoo      555-2127     1200/300          C
  963.      -| sabafoo      555-2127     1200/300          C
  964.      -| Jan  21  36  64 620
  965.      -| Apr  21  70  74 514
  966. Note how the line in `BBS-list' beginning with `sabafoo' was printed
  967. twice, once for each rule.
  968. File: gawk.info,  Node: More Complex,  Next: Statements/Lines,  Prev: Two Rules,  Up: Getting Started
  969. A More Complex Example
  970. ======================
  971.    Here is an example to give you an idea of what typical `awk'
  972. programs do.  This example shows how `awk' can be used to summarize,
  973. select, and rearrange the output of another utility.  It uses features
  974. that haven't been covered yet, so don't worry if you don't understand
  975. all the details.
  976.      ls -lg | awk '$6 == "Nov" { sum += $5 }
  977.                   END { print sum }'
  978.    This command prints the total number of bytes in all the files in the
  979. current directory that were last modified in November (of any year).
  980. (In the C shell you would need to type a semicolon and then a backslash
  981. at the end of the first line; in a POSIX-compliant shell, such as the
  982. Bourne shell or Bash, the GNU Bourne-Again shell, you can type the
  983. example as shown.)
  984.    The `ls -lg' part of this example is a system command that gives you
  985. a listing of the files in a directory, including file size and the date
  986. the file was last modified. Its output looks like this:
  987.      -rw-r--r--  1 arnold   user   1933 Nov  7 13:05 Makefile
  988.      -rw-r--r--  1 arnold   user  10809 Nov  7 13:03 gawk.h
  989.      -rw-r--r--  1 arnold   user    983 Apr 13 12:14 gawk.tab.h
  990.      -rw-r--r--  1 arnold   user  31869 Jun 15 12:20 gawk.y
  991.      -rw-r--r--  1 arnold   user  22414 Nov  7 13:03 gawk1.c
  992.      -rw-r--r--  1 arnold   user  37455 Nov  7 13:03 gawk2.c
  993.      -rw-r--r--  1 arnold   user  27511 Dec  9 13:07 gawk3.c
  994.      -rw-r--r--  1 arnold   user   7989 Nov  7 13:03 gawk4.c
  995. The first field contains read-write permissions, the second field
  996. contains the number of links to the file, and the third field
  997. identifies the owner of the file. The fourth field identifies the group
  998. of the file.  The fifth field contains the size of the file in bytes.
  999. The sixth, seventh and eighth fields contain the month, day, and time,
  1000. respectively, that the file was last modified.  Finally, the ninth field
  1001. contains the name of the file.
  1002.    The `$6 == "Nov"' in our `awk' program is an expression that tests
  1003. whether the sixth field of the output from `ls -lg' matches the string
  1004. `Nov'.  Each time a line has the string `Nov' for its sixth field, the
  1005. action `sum += $5' is performed.  This adds the fifth field (the file
  1006. size) to the variable `sum'.  As a result, when `awk' has finished
  1007. reading all the input lines, `sum' is the sum of the sizes of files
  1008. whose lines matched the pattern.  (This works because `awk' variables
  1009. are automatically initialized to zero.)
  1010.    After the last line of output from `ls' has been processed, the
  1011. `END' rule is executed, and the value of `sum' is printed.  In this
  1012. example, the value of `sum' would be 80600.
  1013.    These more advanced `awk' techniques are covered in later sections
  1014. (*note Overview of Actions: Action Overview.).  Before you can move on
  1015. to more advanced `awk' programming, you have to know how `awk'
  1016. interprets your input and displays your output.  By manipulating fields
  1017. and using `print' statements, you can produce some very useful and
  1018. impressive looking reports.
  1019. File: gawk.info,  Node: Statements/Lines,  Next: Other Features,  Prev: More Complex,  Up: Getting Started
  1020. `awk' Statements Versus Lines
  1021. =============================
  1022.    Most often, each line in an `awk' program is a separate statement or
  1023. separate rule, like this:
  1024.      awk '/12/  { print $0 }
  1025.           /21/  { print $0 }' BBS-list inventory-shipped
  1026.    However, `gawk' will ignore newlines after any of the following:
  1027.      ,    {    ?    :    ||    &&    do    else
  1028. A newline at any other point is considered the end of the statement.
  1029. (Splitting lines after `?' and `:' is a minor `gawk' extension.  The
  1030. `?' and `:' referred to here is the three operand conditional
  1031. expression described in *Note Conditional Expressions: Conditional Exp.)
  1032.    If you would like to split a single statement into two lines at a
  1033. point where a newline would terminate it, you can "continue" it by
  1034. ending the first line with a backslash character, `\'.  The backslash
  1035. must be the final character on the line to be recognized as a
  1036. continuation character.  This is allowed absolutely anywhere in the
  1037. statement, even in the middle of a string or regular expression.  For
  1038. example:
  1039.      awk '/This regular expression is too long, so continue it\
  1040.       on the next line/ { print $1 }'
  1041. We have generally not used backslash continuation in the sample programs
  1042. in this Info file.  Since in `gawk' there is no limit on the length of
  1043. a line, it is never strictly necessary; it just makes programs more
  1044. readable.  For this same reason, as well as for clarity, we have kept
  1045. most statements short in the sample programs presented throughout the
  1046. Info file.  Backslash continuation is most useful when your `awk'
  1047. program is in a separate source file, instead of typed in on the
  1048. command line.  You should also note that many `awk' implementations are
  1049. more particular about where you may use backslash continuation. For
  1050. example, they may not allow you to split a string constant using
  1051. backslash continuation.  Thus, for maximal portability of your `awk'
  1052. programs, it is best not to split your lines in the middle of a regular
  1053. expression or a string.
  1054.    *Caution: backslash continuation does not work as described above
  1055. with the C shell.*  Continuation with backslash works for `awk'
  1056. programs in files, and also for one-shot programs *provided* you are
  1057. using a POSIX-compliant shell, such as the Bourne shell or Bash, the
  1058. GNU Bourne-Again shell.  But the C shell (`csh') behaves differently!
  1059. There, you must use two backslashes in a row, followed by a newline.
  1060. Note also that when using the C shell, *every* newline in your awk
  1061. program must be escaped with a backslash. To illustrate:
  1062.      % awk 'BEGIN { \
  1063.      ?   print \\
  1064.      ?       "hello, world" \
  1065.      ? }'
  1066.      -| hello, world
  1067. Here, the `%' and `?' are the C shell's primary and secondary prompts,
  1068. analogous to the standard shell's `$' and `>'.
  1069.    `awk' is a line-oriented language.  Each rule's action has to begin
  1070. on the same line as the pattern.  To have the pattern and action on
  1071. separate lines, you *must* use backslash continuation--there is no
  1072. other way.
  1073.    Note that backslash continuation and comments do not mix. As soon as
  1074. `awk' sees the `#' that starts a comment, it ignores *everything* on
  1075. the rest of the line. For example:
  1076.      $ gawk 'BEGIN { print "dont panic" # a friendly \
  1077.      >                                    BEGIN rule
  1078.      > }'
  1079.      error--> gawk: cmd. line:2:                BEGIN rule
  1080.      error--> gawk: cmd. line:2:                ^ parse error
  1081. Here, it looks like the backslash would continue the comment onto the
  1082. next line. However, the backslash-newline combination is never even
  1083. noticed, since it is "hidden" inside the comment. Thus, the `BEGIN' is
  1084. noted as a syntax error.
  1085.    When `awk' statements within one rule are short, you might want to
  1086. put more than one of them on a line.  You do this by separating the
  1087. statements with a semicolon, `;'.
  1088.    This also applies to the rules themselves.  Thus, the previous
  1089. program could have been written:
  1090.      /12/ { print $0 } ; /21/ { print $0 }
  1091. *Note:* the requirement that rules on the same line must be separated
  1092. with a semicolon was not in the original `awk' language; it was added
  1093. for consistency with the treatment of statements within an action.
  1094. File: gawk.info,  Node: Other Features,  Next: When,  Prev: Statements/Lines,  Up: Getting Started
  1095. Other Features of `awk'
  1096. =======================
  1097.    The `awk' language provides a number of predefined, or built-in
  1098. variables, which your programs can use to get information from `awk'.
  1099. There are other variables your program can set to control how `awk'
  1100. processes your data.
  1101.    In addition, `awk' provides a number of built-in functions for doing
  1102. common computational and string related operations.
  1103.    As we develop our presentation of the `awk' language, we introduce
  1104. most of the variables and many of the functions. They are defined
  1105. systematically in *Note Built-in Variables::, and *Note Built-in
  1106. Functions: Built-in.
  1107. File: gawk.info,  Node: When,  Prev: Other Features,  Up: Getting Started
  1108. When to Use `awk'
  1109. =================
  1110.    You might wonder how `awk' might be useful for you.  Using utility
  1111. programs, advanced patterns, field separators, arithmetic statements,
  1112. and other selection criteria, you can produce much more complex output.
  1113. The `awk' language is very useful for producing reports from large
  1114. amounts of raw data, such as summarizing information from the output of
  1115. other utility programs like `ls'.  (*Note A More Complex Example: More
  1116. Complex.)
  1117.    Programs written with `awk' are usually much smaller than they would
  1118. be in other languages.  This makes `awk' programs easy to compose and
  1119. use.  Often, `awk' programs can be quickly composed at your terminal,
  1120. used once, and thrown away.  Since `awk' programs are interpreted, you
  1121. can avoid the (usually lengthy) compilation part of the typical
  1122. edit-compile-test-debug cycle of software development.
  1123.    Complex programs have been written in `awk', including a complete
  1124. retargetable assembler for eight-bit microprocessors (*note
  1125. Glossary::., for more information) and a microcode assembler for a
  1126. special purpose Prolog computer.  However, `awk''s capabilities are
  1127. strained by tasks of such complexity.
  1128.    If you find yourself writing `awk' scripts of more than, say, a few
  1129. hundred lines, you might consider using a different programming
  1130. language.  Emacs Lisp is a good choice if you need sophisticated string
  1131. or pattern matching capabilities.  The shell is also good at string and
  1132. pattern matching; in addition, it allows powerful use of the system
  1133. utilities.  More conventional languages, such as C, C++, and Lisp, offer
  1134. better facilities for system programming and for managing the complexity
  1135. of large programs.  Programs in these languages may require more lines
  1136. of source code than the equivalent `awk' programs, but they are easier
  1137. to maintain and usually run more efficiently.
  1138. File: gawk.info,  Node: One-liners,  Next: Regexp,  Prev: Getting Started,  Up: Top
  1139. Useful One Line Programs
  1140. ************************
  1141.    Many useful `awk' programs are short, just a line or two.  Here is a
  1142. collection of useful, short programs to get you started.  Some of these
  1143. programs contain constructs that haven't been covered yet.  The
  1144. description of the program will give you a good idea of what is going
  1145. on, but please read the rest of the Info file to become an `awk' expert!
  1146.    Most of the examples use a data file named `data'.  This is just a
  1147. placeholder; if you were to use these programs yourself, you would
  1148. substitute your own file names for `data'.
  1149.    Since you are reading this in Info, each line of the example code is
  1150. enclosed in quotes, to represent text that you would type literally.
  1151. The examples themselves represent shell commands that use single quotes
  1152. to keep the shell from interpreting the contents of the program.  When
  1153. reading the examples, focus on the text between the open and close
  1154. quotes.
  1155. `awk '{ if (length($0) > max) max = length($0) }'
  1156. `     END { print max }' data'
  1157.      This program prints the length of the longest input line.
  1158. `awk 'length($0) > 80' data'
  1159.      This program prints every line that is longer than 80 characters.
  1160.      The sole rule has a relational expression as its pattern, and has
  1161.      no action (so the default action, printing the record, is used).
  1162. `expand data | awk '{ if (x < length()) x = length() }'
  1163. `                   END { print "maximum line length is " x }''
  1164.      This program prints the length of the longest line in `data'.  The
  1165.      input is processed by the `expand' program to change tabs into
  1166.      spaces, so the widths compared are actually the right-margin
  1167.      columns.
  1168. `awk 'NF > 0' data'
  1169.      This program prints every line that has at least one field.  This
  1170.      is an easy way to delete blank lines from a file (or rather, to
  1171.      create a new file similar to the old file but from which the blank
  1172.      lines have been deleted).
  1173. `awk 'BEGIN { for (i = 1; i <= 7; i++)'
  1174. `               print int(101 * rand()) }''
  1175.      This program prints seven random numbers from zero to 100,
  1176.      inclusive.
  1177. `ls -lg FILES | awk '{ x += $5 } ; END { print "total bytes: " x }''
  1178.      This program prints the total number of bytes used by FILES.
  1179. `ls -lg FILES | awk '{ x += $5 }'
  1180. `                 END { print "total K-bytes: " (x + 1023)/1024 }''
  1181.      This program prints the total number of kilobytes used by FILES.
  1182. `awk -F: '{ print $1 }' /etc/passwd | sort'
  1183.      This program prints a sorted list of the login names of all users.
  1184. `awk 'END { print NR }' data'
  1185.      This program counts lines in a file.
  1186. `awk 'NR % 2 == 0' data'
  1187.      This program prints the even numbered lines in the data file.  If
  1188.      you were to use the expression `NR % 2 == 1' instead, it would
  1189.      print the odd numbered lines.
  1190. File: gawk.info,  Node: Regexp,  Next: Reading Files,  Prev: One-liners,  Up: Top
  1191. Regular Expressions
  1192. *******************
  1193.    A "regular expression", or "regexp", is a way of describing a set of
  1194. strings.  Because regular expressions are such a fundamental part of
  1195. `awk' programming, their format and use deserve a separate chapter.
  1196.    A regular expression enclosed in slashes (`/') is an `awk' pattern
  1197. that matches every input record whose text belongs to that set.
  1198.    The simplest regular expression is a sequence of letters, numbers, or
  1199. both.  Such a regexp matches any string that contains that sequence.
  1200. Thus, the regexp `foo' matches any string containing `foo'.  Therefore,
  1201. the pattern `/foo/' matches any input record containing the three
  1202. characters `foo', *anywhere* in the record.  Other kinds of regexps let
  1203. you specify more complicated classes of strings.
  1204. * Menu:
  1205. * Regexp Usage::                How to Use Regular Expressions.
  1206. * Escape Sequences::            How to write non-printing characters.
  1207. * Regexp Operators::            Regular Expression Operators.
  1208. * GNU Regexp Operators::        Operators specific to GNU software.
  1209. * Case-sensitivity::            How to do case-insensitive matching.
  1210. * Leftmost Longest::            How much text matches.
  1211. * Computed Regexps::            Using Dynamic Regexps.
  1212. File: gawk.info,  Node: Regexp Usage,  Next: Escape Sequences,  Prev: Regexp,  Up: Regexp
  1213. How to Use Regular Expressions
  1214. ==============================
  1215.    A regular expression can be used as a pattern by enclosing it in
  1216. slashes.  Then the regular expression is tested against the entire text
  1217. of each record.  (Normally, it only needs to match some part of the
  1218. text in order to succeed.)  For example, this prints the second field
  1219. of each record that contains the three characters `foo' anywhere in it:
  1220.      $ awk '/foo/ { print $2 }' BBS-list
  1221.      -| 555-1234
  1222.      -| 555-6699
  1223.      -| 555-6480
  1224.      -| 555-2127
  1225.    Regular expressions can also be used in matching expressions.  These
  1226. expressions allow you to specify the string to match against; it need
  1227. not be the entire current input record.  The two operators, `~' and
  1228. `!~', perform regular expression comparisons.  Expressions using these
  1229. operators can be used as patterns or in `if', `while', `for', and `do'
  1230. statements.  (*Note Control Statements in Actions: Statements.)
  1231. `EXP ~ /REGEXP/'
  1232.      This is true if the expression EXP (taken as a string) is matched
  1233.      by REGEXP.  The following example matches, or selects, all input
  1234.      records with the upper-case letter `J' somewhere in the first
  1235.      field:
  1236.           $ awk '$1 ~ /J/' inventory-shipped
  1237.           -| Jan  13  25  15 115
  1238.           -| Jun  31  42  75 492
  1239.           -| Jul  24  34  67 436
  1240.           -| Jan  21  36  64 620
  1241.      So does this:
  1242.           awk '{ if ($1 ~ /J/) print }' inventory-shipped
  1243. `EXP !~ /REGEXP/'
  1244.      This is true if the expression EXP (taken as a character string)
  1245.      is *not* matched by REGEXP.  The following example matches, or
  1246.      selects, all input records whose first field *does not* contain
  1247.      the upper-case letter `J':
  1248.           $ awk '$1 !~ /J/' inventory-shipped
  1249.           -| Feb  15  32  24 226
  1250.           -| Mar  15  24  34 228
  1251.           -| Apr  31  52  63 420
  1252.           -| May  16  34  29 208
  1253.           ...
  1254.    When a regexp is written enclosed in slashes, like `/foo/', we call
  1255. it a "regexp constant", much like `5.27' is a numeric constant, and
  1256. `"foo"' is a string constant.
  1257. File: gawk.info,  Node: Escape Sequences,  Next: Regexp Operators,  Prev: Regexp Usage,  Up: Regexp
  1258. Escape Sequences
  1259. ================
  1260.    Some characters cannot be included literally in string constants
  1261. (`"foo"') or regexp constants (`/foo/').  You represent them instead
  1262. with "escape sequences", which are character sequences beginning with a
  1263. backslash (`\').
  1264.    One use of an escape sequence is to include a double-quote character
  1265. in a string constant.  Since a plain double-quote would end the string,
  1266. you must use `\"' to represent an actual double-quote character as a
  1267. part of the string.  For example:
  1268.      $ awk 'BEGIN { print "He said \"hi!\" to her." }'
  1269.      -| He said "hi!" to her.
  1270.    The  backslash character itself is another character that cannot be
  1271. included normally; you write `\\' to put one backslash in the string or
  1272. regexp.  Thus, the string whose contents are the two characters `"' and
  1273. `\' must be written `"\"\\"'.
  1274.    Another use of backslash is to represent unprintable characters such
  1275. as tab or newline.  While there is nothing to stop you from entering
  1276. most unprintable characters directly in a string constant or regexp
  1277. constant, they may look ugly.
  1278.    Here is a table of all the escape sequences used in `awk', and what
  1279. they represent. Unless noted otherwise, all of these escape sequences
  1280. apply to both string constants and regexp constants.
  1281.      A literal backslash, `\'.
  1282.      The "alert" character, `Control-g', ASCII code 7 (BEL).
  1283.      Backspace, `Control-h', ASCII code 8 (BS).
  1284.      Formfeed, `Control-l', ASCII code 12 (FF).
  1285.      Newline, `Control-j', ASCII code 10 (LF).
  1286.      Carriage return, `Control-m', ASCII code 13 (CR).
  1287.      Horizontal tab, `Control-i', ASCII code 9 (HT).
  1288.      Vertical tab, `Control-k', ASCII code 11 (VT).
  1289. `\NNN'
  1290.      The octal value NNN, where NNN are one to three digits between `0'
  1291.      and `7'.  For example, the code for the ASCII ESC (escape)
  1292.      character is `\033'.
  1293. `\xHH...'
  1294.      The hexadecimal value HH, where HH are hexadecimal digits (`0'
  1295.      through `9' and either `A' through `F' or `a' through `f').  Like
  1296.      the same construct in ANSI C, the escape sequence continues until
  1297.      the first non-hexadecimal digit is seen.  However, using more than
  1298.      two hexadecimal digits produces undefined results. (The `\x'
  1299.      escape sequence is not allowed in POSIX `awk'.)
  1300.      A literal slash (necessary for regexp constants only).  You use
  1301.      this when you wish to write a regexp constant that contains a
  1302.      slash. Since the regexp is delimited by slashes, you need to
  1303.      escape the slash that is part of the pattern, in order to tell
  1304.      `awk' to keep processing the rest of the regexp.
  1305.      A literal double-quote (necessary for string constants only).  You
  1306.      use this when you wish to write a string constant that contains a
  1307.      double-quote. Since the string is delimited by double-quotes, you
  1308.      need to escape the quote that is part of the string, in order to
  1309.      tell `awk' to keep processing the rest of the string.
  1310.    In `gawk', there are additional two character sequences that begin
  1311. with backslash that have special meaning in regexps.  *Note Additional
  1312. Regexp Operators Only in `gawk': GNU Regexp Operators.
  1313.    In a string constant, what happens if you place a backslash before
  1314. something that is not one of the characters listed above?  POSIX `awk'
  1315. purposely leaves this case undefined.  There are two choices.
  1316.    * Strip the backslash out.  This is what Unix `awk' and `gawk' both
  1317.      do.  For example, `"a\qc"' is the same as `"aqc"'.
  1318.    * Leave the backslash alone.  Some other `awk' implementations do
  1319.      this.  In such implementations, `"a\qc"' is the same as if you had
  1320.      typed `"a\\qc"'.
  1321.    In a regexp, a backslash before any character that is not in the
  1322. above table, and not listed in *Note Additional Regexp Operators Only
  1323. in `gawk': GNU Regexp Operators, means that the next character should
  1324. be taken literally, even if it would normally be a regexp operator.
  1325. E.g., `/a\+b/' matches the three characters `a+b'.
  1326.    For complete portability, do not use a backslash before any
  1327. character not listed in the table above.
  1328.    Another interesting question arises. Suppose you use an octal or
  1329. hexadecimal escape to represent a regexp metacharacter (*note Regular
  1330. Expression Operators: Regexp Operators.).  Does `awk' treat the
  1331. character as literal character, or as a regexp operator?
  1332.    It turns out that historically, such characters were taken literally
  1333. (d.c.).  However, the POSIX standard indicates that they should be
  1334. treated as real metacharacters, and this is what `gawk' does.  However,
  1335. in compatibility mode (*note Command Line Options: Options.), `gawk'
  1336. treats the characters represented by octal and hexadecimal escape
  1337. sequences literally when used in regexp constants. Thus, `/a\52b/' is
  1338. equivalent to `/a\*b/'.
  1339.    To summarize:
  1340.   1. The escape sequences in the table above are always processed first,
  1341.      for both string constants and regexp constants. This happens very
  1342.      early, as soon as `awk' reads your program.
  1343.   2. `gawk' processes both regexp constants and dynamic regexps (*note
  1344.      Using Dynamic Regexps: Computed Regexps.), for the special
  1345.      operators listed in *Note Additional Regexp Operators Only in
  1346.      `gawk': GNU Regexp Operators.
  1347.   3. A backslash before any other character means to treat that
  1348.      character literally.
  1349. File: gawk.info,  Node: Regexp Operators,  Next: GNU Regexp Operators,  Prev: Escape Sequences,  Up: Regexp
  1350. Regular Expression Operators
  1351. ============================
  1352.    You can combine regular expressions with the following characters,
  1353. called "regular expression operators", or "metacharacters", to increase
  1354. the power and versatility of regular expressions.
  1355.    The escape sequences described in *Note Escape Sequences::, are
  1356. valid inside a regexp.  They are introduced by a `\'.  They are
  1357. recognized and converted into the corresponding real characters as the
  1358. very first step in processing regexps.
  1359.    Here is a table of metacharacters.  All characters that are not
  1360. escape sequences and that are not listed in the table stand for
  1361. themselves.
  1362.      This is used to suppress the special meaning of a character when
  1363.      matching.  For example:
  1364.           \$
  1365.      matches the character `$'.
  1366.      This matches the beginning of a string.  For example:
  1367.           ^@chapter
  1368.      matches the `@chapter' at the beginning of a string, and can be
  1369.      used to identify chapter beginnings in Texinfo source files.  The
  1370.      `^' is known as an "anchor", since it anchors the pattern to
  1371.      matching only at the beginning of the string.
  1372.      It is important to realize that `^' does not match the beginning of
  1373.      a line embedded in a string.  In this example the condition is not
  1374.      true:
  1375.           if ("line1\nLINE 2" ~ /^L/) ...
  1376.      This is similar to `^', but it matches only at the end of a string.
  1377.      For example:
  1378.           p$
  1379.      matches a record that ends with a `p'.  The `$' is also an anchor,
  1380.      and also does not match the end of a line embedded in a string.
  1381.      In this example the condition is not true:
  1382.           if ("line1\nLINE 2" ~ /1$/) ...
  1383.      The period, or dot, matches any single character, *including* the
  1384.      newline character.  For example:
  1385.           .P
  1386.      matches any single character followed by a `P' in a string.  Using
  1387.      concatenation we can make a regular expression like `U.A', which
  1388.      matches any three-character sequence that begins with `U' and ends
  1389.      with `A'.
  1390.      In strict POSIX mode (*note Command Line Options: Options.), `.'
  1391.      does not match the NUL character, which is a character with all
  1392.      bits equal to zero.  Otherwise, NUL is just another character.
  1393.      Other versions of `awk' may not be able to match the NUL character.
  1394. `[...]'
  1395.      This is called a "character list".  It matches any *one* of the
  1396.      characters that are enclosed in the square brackets.  For example:
  1397.           [MVX]
  1398.      matches any one of the characters `M', `V', or `X' in a string.
  1399.      Ranges of characters are indicated by using a hyphen between the
  1400.      beginning and ending characters, and enclosing the whole thing in
  1401.      brackets.  For example:
  1402.           [0-9]
  1403.      matches any digit.  Multiple ranges are allowed. E.g., the list
  1404.      `[A-Za-z0-9]' is a common way to express the idea of "all
  1405.      alphanumeric characters."
  1406.      To include one of the characters `\', `]', `-' or `^' in a
  1407.      character list, put a `\' in front of it.  For example:
  1408.           [d\]]
  1409.      matches either `d', or `]'.
  1410.      This treatment of `\' in character lists is compatible with other
  1411.      `awk' implementations, and is also mandated by POSIX.  The regular
  1412.      expressions in `awk' are a superset of the POSIX specification for
  1413.      Extended Regular Expressions (EREs).  POSIX EREs are based on the
  1414.      regular expressions accepted by the traditional `egrep' utility.
  1415.      "Character classes" are a new feature introduced in the POSIX
  1416.      standard.  A character class is a special notation for describing
  1417.      lists of characters that have a specific attribute, but where the
  1418.      actual characters themselves can vary from country to country
  1419.      and/or from character set to character set.  For example, the
  1420.      notion of what is an alphabetic character differs in the USA and
  1421.      in France.
  1422.      A character class is only valid in a regexp *inside* the brackets
  1423.      of a character list.  Character classes consist of `[:', a keyword
  1424.      denoting the class, and `:]'.  Here are the character classes
  1425.      defined by the POSIX standard.
  1426.     `[:alnum:]'
  1427.           Alphanumeric characters.
  1428.     `[:alpha:]'
  1429.           Alphabetic characters.
  1430.     `[:blank:]'
  1431.           Space and tab characters.
  1432.     `[:cntrl:]'
  1433.           Control characters.
  1434.     `[:digit:]'
  1435.           Numeric characters.
  1436.     `[:graph:]'
  1437.           Characters that are printable and are also visible.  (A space
  1438.           is printable, but not visible, while an `a' is both.)
  1439.     `[:lower:]'
  1440.           Lower-case alphabetic characters.
  1441.     `[:print:]'
  1442.           Printable characters (characters that are not control
  1443.           characters.)
  1444.     `[:punct:]'
  1445.           Punctuation characters (characters that are not letter,
  1446.           digits, control characters, or space characters).
  1447.     `[:space:]'
  1448.           Space characters (such as space, tab, and formfeed, to name a
  1449.           few).
  1450.     `[:upper:]'
  1451.           Upper-case alphabetic characters.
  1452.     `[:xdigit:]'
  1453.           Characters that are hexadecimal digits.
  1454.      For example, before the POSIX standard, to match alphanumeric
  1455.      characters, you had to write `/[A-Za-z0-9]/'.  If your character
  1456.      set had other alphabetic characters in it, this would not match
  1457.      them.  With the POSIX character classes, you can write
  1458.      `/[[:alnum:]]/', and this will match *all* the alphabetic and
  1459.      numeric characters in your character set.
  1460.      Two additional special sequences can appear in character lists.
  1461.      These apply to non-ASCII character sets, which can have single
  1462.      symbols (called "collating elements") that are represented with
  1463.      more than one character, as well as several characters that are
  1464.      equivalent for "collating", or sorting, purposes.  (E.g., in
  1465.      French, a plain "e" and a grave-accented "`e" are equivalent.)
  1466.     Collating Symbols
  1467.           A "collating symbol" is a multi-character collating element
  1468.           enclosed in `[.' and `.]'.  For example, if `ch' is a
  1469.           collating element, then `[[.ch.]]' is a regexp that matches
  1470.           this collating element, while `[ch]' is a regexp that matches
  1471.           either `c' or `h'.
  1472.     Equivalence Classes
  1473.           An "equivalence class" is a locale-specific name for a list of
  1474.           characters that are equivalent. The name is enclosed in `[='
  1475.           and `=]'.  For example, the name `e' might be used to
  1476.           represent all of "e," "`e," and "'e." In this case, `[[=e]]'
  1477.           is a regexp that matches any of `e', `'e',  or ``e'.
  1478.      These features are very valuable in non-English speaking locales.
  1479.      *Caution:* The library functions that `gawk' uses for regular
  1480.      expression matching currently only recognize POSIX character
  1481.      classes; they do not recognize collating symbols or equivalence
  1482.      classes.
  1483. `[^ ...]'
  1484.      This is a "complemented character list".  The first character after
  1485.      the `[' *must* be a `^'.  It matches any characters *except* those
  1486.      in the square brackets.  For example:
  1487.           [^0-9]
  1488.      matches any character that is not a digit.
  1489.      This is the "alternation operator", and it is used to specify
  1490.      alternatives.  For example:
  1491.           ^P|[0-9]
  1492.      matches any string that matches either `^P' or `[0-9]'.  This
  1493.      means it matches any string that starts with `P' or contains a
  1494.      digit.
  1495.      The alternation applies to the largest possible regexps on either
  1496.      side.  In other words, `|' has the lowest precedence of all the
  1497.      regular expression operators.
  1498. `(...)'
  1499.      Parentheses are used for grouping in regular expressions as in
  1500.      arithmetic.  They can be used to concatenate regular expressions
  1501.      containing the alternation operator, `|'.  For example,
  1502.      `@(samp|code)\{[^}]+\}' matches both `@code{foo}' and
  1503.      `@samp{bar}'. (These are Texinfo formatting control sequences.)
  1504.      This symbol means that the preceding regular expression is to be
  1505.      repeated as many times as necessary to find a match.  For example:
  1506.           ph*
  1507.      applies the `*' symbol to the preceding `h' and looks for matches
  1508.      of one `p' followed by any number of `h's.  This will also match
  1509.      just `p' if no `h's are present.
  1510.      The `*' repeats the *smallest* possible preceding expression.
  1511.      (Use parentheses if you wish to repeat a larger expression.)  It
  1512.      finds as many repetitions as possible.  For example:
  1513.           awk '/\(c[ad][ad]*r x\)/ { print }' sample
  1514.      prints every record in `sample' containing a string of the form
  1515.      `(car x)', `(cdr x)', `(cadr x)', and so on.  Notice the escaping
  1516.      of the parentheses by preceding them with backslashes.
  1517.      This symbol is similar to `*', but the preceding expression must be
  1518.      matched at least once.  This means that:
  1519.           wh+y
  1520.      would match `why' and `whhy' but not `wy', whereas `wh*y' would
  1521.      match all three of these strings.  This is a simpler way of
  1522.      writing the last `*' example:
  1523.           awk '/\(c[ad]+r x\)/ { print }' sample
  1524.      This symbol is similar to `*', but the preceding expression can be
  1525.      matched either once or not at all.  For example:
  1526.           fe?d
  1527.      will match `fed' and `fd', but nothing else.
  1528. `{N}'
  1529. `{N,}'
  1530. `{N,M}'
  1531.      One or two numbers inside braces denote an "interval expression".
  1532.      If there is one number in the braces, the preceding regexp is
  1533.      repeated N times.  If there are two numbers separated by a comma,
  1534.      the preceding regexp is repeated N to M times.  If there is one
  1535.      number followed by a comma, then the preceding regexp is repeated
  1536.      at least N times.
  1537.     `wh{3}y'
  1538.           matches `whhhy' but not `why' or `whhhhy'.
  1539.     `wh{3,5}y'
  1540.           matches `whhhy' or `whhhhy' or `whhhhhy', only.
  1541.     `wh{2,}y'
  1542.           matches `whhy' or `whhhy', and so on.
  1543.      Interval expressions were not traditionally available in `awk'.
  1544.      As part of the POSIX standard they were added, to make `awk' and
  1545.      `egrep' consistent with each other.
  1546.      However, since old programs may use `{' and `}' in regexp
  1547.      constants, by default `gawk' does *not* match interval expressions
  1548.      in regexps.  If either `--posix' or `--re-interval' are specified
  1549.      (*note Command Line Options: Options.), then interval expressions
  1550.      are allowed in regexps.
  1551.    In regular expressions, the `*', `+', and `?' operators, as well as
  1552. the braces `{' and `}', have the highest precedence, followed by
  1553. concatenation, and finally by `|'.  As in arithmetic, parentheses can
  1554. change how operators are grouped.
  1555.    If `gawk' is in compatibility mode (*note Command Line Options:
  1556. Options.), character classes and interval expressions are not available
  1557. in regular expressions.
  1558.    The next node discusses the GNU-specific regexp operators, and
  1559. provides more detail concerning how command line options affect the way
  1560. `gawk' interprets the characters in regular expressions.
  1561. File: gawk.info,  Node: GNU Regexp Operators,  Next: Case-sensitivity,  Prev: Regexp Operators,  Up: Regexp
  1562. Additional Regexp Operators Only in `gawk'
  1563. ==========================================
  1564.    GNU software that deals with regular expressions provides a number of
  1565. additional regexp operators.  These operators are described in this
  1566. section, and are specific to `gawk'; they are not available in other
  1567. `awk' implementations.
  1568.    Most of the additional operators are for dealing with word matching.
  1569. For our purposes, a "word" is a sequence of one or more letters, digits,
  1570. or underscores (`_').
  1571.      This operator matches any word-constituent character, i.e. any
  1572.      letter, digit, or underscore. Think of it as a short-hand for
  1573.      `[[:alnum:]_]'.
  1574.      This operator matches any character that is not word-constituent.
  1575.      Think of it as a short-hand for `[^[:alnum:]_]'.
  1576.      This operator matches the empty string at the beginning of a word.
  1577.      For example, `/\<away/' matches `away', but not `stowaway'.
  1578.      This operator matches the empty string at the end of a word.  For
  1579.      example, `/stow\>/' matches `stow', but not `stowaway'.
  1580.      This operator matches the empty string at either the beginning or
  1581.      the end of a word (the word boundar*y*).  For example, `\yballs?\y'
  1582.      matches either `ball' or `balls' as a separate word.
  1583.      This operator matches the empty string within a word. In other
  1584.      words, `\B' matches the empty string that occurs between two
  1585.      word-constituent characters. For example, `/\Brat\B/' matches
  1586.      `crate', but it does not match `dirty rat'.  `\B' is essentially
  1587.      the opposite of `\y'.
  1588.    There are two other operators that work on buffers.  In Emacs, a
  1589. "buffer" is, naturally, an Emacs buffer.  For other programs, the
  1590. regexp library routines that `gawk' uses consider the entire string to
  1591. be matched as the buffer.
  1592.    For `awk', since `^' and `$' always work in terms of the beginning
  1593. and end of strings, these operators don't add any new capabilities.
  1594. They are provided for compatibility with other GNU software.
  1595.      This operator matches the empty string at the beginning of the
  1596.      buffer.
  1597.      This operator matches the empty string at the end of the buffer.
  1598.    In other GNU software, the word boundary operator is `\b'. However,
  1599. that conflicts with the `awk' language's definition of `\b' as
  1600. backspace, so `gawk' uses a different letter.
  1601.    An alternative method would have been to require two backslashes in
  1602. the GNU operators, but this was deemed to be too confusing, and the
  1603. current method of using `\y' for the GNU `\b' appears to be the lesser
  1604. of two evils.
  1605.    The various command line options (*note Command Line Options:
  1606. Options.) control how `gawk' interprets characters in regexps.
  1607. No options
  1608.      In the default case, `gawk' provide all the facilities of POSIX
  1609.      regexps and the GNU regexp operators described in *Note Regular
  1610.      Expression Operators: Regexp Operators.  However, interval
  1611.      expressions are not supported.
  1612. `--posix'
  1613.      Only POSIX regexps are supported, the GNU operators are not special
  1614.      (e.g., `\w' matches a literal `w').  Interval expressions are
  1615.      allowed.
  1616. `--traditional'
  1617.      Traditional Unix `awk' regexps are matched. The GNU operators are
  1618.      not special, interval expressions are not available, and neither
  1619.      are the POSIX character classes (`[[:alnum:]]' and so on).
  1620.      Characters described by octal and hexadecimal escape sequences are
  1621.      treated literally, even if they represent regexp metacharacters.
  1622. `--re-interval'
  1623.      Allow interval expressions in regexps, even if `--traditional' has
  1624.      been provided.
  1625. File: gawk.info,  Node: Case-sensitivity,  Next: Leftmost Longest,  Prev: GNU Regexp Operators,  Up: Regexp
  1626. Case-sensitivity in Matching
  1627. ============================
  1628.    Case is normally significant in regular expressions, both when
  1629. matching ordinary characters (i.e. not metacharacters), and inside
  1630. character sets.  Thus a `w' in a regular expression matches only a
  1631. lower-case `w' and not an upper-case `W'.
  1632.    The simplest way to do a case-independent match is to use a character
  1633. list: `[Ww]'.  However, this can be cumbersome if you need to use it
  1634. often; and it can make the regular expressions harder to read.  There
  1635. are two alternatives that you might prefer.
  1636.    One way to do a case-insensitive match at a particular point in the
  1637. program is to convert the data to a single case, using the `tolower' or
  1638. `toupper' built-in string functions (which we haven't discussed yet;
  1639. *note Built-in Functions for String Manipulation: String Functions.).
  1640. For example:
  1641.      tolower($1) ~ /foo/  { ... }
  1642. converts the first field to lower-case before matching against it.
  1643. This will work in any POSIX-compliant implementation of `awk'.
  1644.    Another method, specific to `gawk', is to set the variable
  1645. `IGNORECASE' to a non-zero value (*note Built-in Variables::.).  When
  1646. `IGNORECASE' is not zero, *all* regexp and string operations ignore
  1647. case.  Changing the value of `IGNORECASE' dynamically controls the case
  1648. sensitivity of your program as it runs.  Case is significant by default
  1649. because `IGNORECASE' (like most variables) is initialized to zero.
  1650.      x = "aB"
  1651.      if (x ~ /ab/) ...   # this test will fail
  1652.      
  1653.      IGNORECASE = 1
  1654.      if (x ~ /ab/) ...   # now it will succeed
  1655.    In general, you cannot use `IGNORECASE' to make certain rules
  1656. case-insensitive and other rules case-sensitive, because there is no way
  1657. to set `IGNORECASE' just for the pattern of a particular rule.  To do
  1658. this, you must use character lists or `tolower'.  However, one thing
  1659. you can do only with `IGNORECASE' is turn case-sensitivity on or off
  1660. dynamically for all the rules at once.
  1661.    `IGNORECASE' can be set on the command line, or in a `BEGIN' rule
  1662. (*note Other Command Line Arguments: Other Arguments.; also *note
  1663. Startup and Cleanup Actions: Using BEGIN/END.).  Setting `IGNORECASE'
  1664. from the command line is a way to make a program case-insensitive
  1665. without having to edit it.
  1666.    Prior to version 3.0 of `gawk', the value of `IGNORECASE' only
  1667. affected regexp operations. It did not affect string comparison with
  1668. `==', `!=', and so on.  Beginning with version 3.0, both regexp and
  1669. string comparison operations are affected by `IGNORECASE'.
  1670.    Beginning with version 3.0 of `gawk', the equivalences between
  1671. upper-case and lower-case characters are based on the ISO-8859-1 (ISO
  1672. Latin-1) character set. This character set is a superset of the
  1673. traditional 128 ASCII characters, that also provides a number of
  1674. characters suitable for use with European languages.
  1675.    The value of `IGNORECASE' has no effect if `gawk' is in
  1676. compatibility mode (*note Command Line Options: Options.).  Case is
  1677. always significant in compatibility mode.
  1678. File: gawk.info,  Node: Leftmost Longest,  Next: Computed Regexps,  Prev: Case-sensitivity,  Up: Regexp
  1679. How Much Text Matches?
  1680. ======================
  1681.    Consider the following example:
  1682.      echo aaaabcd | awk '{ sub(/a+/, "<A>"); print }'
  1683.    This example uses the `sub' function (which we haven't discussed yet,
  1684. *note Built-in Functions for String Manipulation: String Functions.) to
  1685. make a change to the input record. Here, the regexp `/a+/' indicates
  1686. "one or more `a' characters," and the replacement text is `<A>'.
  1687.    The input contains four `a' characters.  What will the output be?
  1688. In other words, how many is "one or more"--will `awk' match two, three,
  1689. or all four `a' characters?
  1690.    The answer is, `awk' (and POSIX) regular expressions always match
  1691. the leftmost, *longest* sequence of input characters that can match.
  1692. Thus, in this example, all four `a' characters are replaced with `<A>'.
  1693.      $ echo aaaabcd | awk '{ sub(/a+/, "<A>"); print }'
  1694.      -| <A>bcd
  1695.    For simple match/no-match tests, this is not so important. But when
  1696. doing regexp-based field and record splitting, and text matching and
  1697. substitutions with the `match', `sub', `gsub', and `gensub' functions,
  1698. it is very important.  *Note Built-in Functions for String
  1699. Manipulation: String Functions, for more information on these functions.
  1700. Understanding this principle is also important for regexp-based record
  1701. and field splitting (*note How Input is Split into Records: Records.,
  1702. and also *note Specifying How Fields are Separated: Field Separators.).
  1703. File: gawk.info,  Node: Computed Regexps,  Prev: Leftmost Longest,  Up: Regexp
  1704. Using Dynamic Regexps
  1705. =====================
  1706.    The right hand side of a `~' or `!~' operator need not be a regexp
  1707. constant (i.e. a string of characters between slashes).  It may be any
  1708. expression.  The expression is evaluated, and converted if necessary to
  1709. a string; the contents of the string are used as the regexp.  A regexp
  1710. that is computed in this way is called a "dynamic regexp".  For example:
  1711.      BEGIN { identifier_regexp = "[A-Za-z_][A-Za-z_0-9]+" }
  1712.      $0 ~ identifier_regexp    { print }
  1713. sets `identifier_regexp' to a regexp that describes `awk' variable
  1714. names, and tests if the input record matches this regexp.
  1715.    *Caution:* When using the `~' and `!~' operators, there is a
  1716. difference between a regexp constant enclosed in slashes, and a string
  1717. constant enclosed in double quotes.  If you are going to use a string
  1718. constant, you have to understand that the string is in essence scanned
  1719. *twice*; the first time when `awk' reads your program, and the second
  1720. time when it goes to match the string on the left-hand side of the
  1721. operator with the pattern on the right.  This is true of any string
  1722. valued expression (such as `identifier_regexp' above), not just string
  1723. constants.
  1724.    What difference does it make if the string is scanned twice? The
  1725. answer has to do with escape sequences, and particularly with
  1726. backslashes.  To get a backslash into a regular expression inside a
  1727. string, you have to type two backslashes.
  1728.    For example, `/\*/' is a regexp constant for a literal `*'.  Only
  1729. one backslash is needed.  To do the same thing with a string, you would
  1730. have to type `"\\*"'.  The first backslash escapes the second one, so
  1731. that the string actually contains the two characters `\' and `*'.
  1732.    Given that you can use both regexp and string constants to describe
  1733. regular expressions, which should you use?  The answer is "regexp
  1734. constants," for several reasons.
  1735.   1. String constants are more complicated to write, and more difficult
  1736.      to read. Using regexp constants makes your programs less
  1737.      error-prone.  Not understanding the difference between the two
  1738.      kinds of constants is a common source of errors.
  1739.   2. It is also more efficient to use regexp constants: `awk' can note
  1740.      that you have supplied a regexp and store it internally in a form
  1741.      that makes pattern matching more efficient.  When using a string
  1742.      constant, `awk' must first convert the string into this internal
  1743.      form, and then perform the pattern matching.
  1744.   3. Using regexp constants is better style; it shows clearly that you
  1745.      intend a regexp match.
  1746. File: gawk.info,  Node: Reading Files,  Next: Printing,  Prev: Regexp,  Up: Top
  1747. Reading Input Files
  1748. *******************
  1749.    In the typical `awk' program, all input is read either from the
  1750. standard input (by default the keyboard, but often a pipe from another
  1751. command) or from files whose names you specify on the `awk' command
  1752. line.  If you specify input files, `awk' reads them in order, reading
  1753. all the data from one before going on to the next.  The name of the
  1754. current input file can be found in the built-in variable `FILENAME'
  1755. (*note Built-in Variables::.).
  1756.    The input is read in units called "records", and processed by the
  1757. rules of your program one record at a time.  By default, each record is
  1758. one line.  Each record is automatically split into chunks called
  1759. "fields".  This makes it more convenient for programs to work on the
  1760. parts of a record.
  1761.    On rare occasions you will need to use the `getline' command.  The
  1762. `getline' command is valuable, both because it can do explicit input
  1763. from any number of files, and because the files used with it do not
  1764. have to be named on the `awk' command line (*note Explicit Input with
  1765. `getline': Getline.).
  1766. * Menu:
  1767. * Records::                     Controlling how data is split into records.
  1768. * Fields::                      An introduction to fields.
  1769. * Non-Constant Fields::         Non-constant Field Numbers.
  1770. * Changing Fields::             Changing the Contents of a Field.
  1771. * Field Separators::            The field separator and how to change it.
  1772. * Constant Size::               Reading constant width data.
  1773. * Multiple Line::               Reading multi-line records.
  1774. * Getline::                     Reading files under explicit program control
  1775.                                 using the `getline' function.
  1776. File: gawk.info,  Node: Records,  Next: Fields,  Prev: Reading Files,  Up: Reading Files
  1777. How Input is Split into Records
  1778. ===============================
  1779.    The `awk' utility divides the input for your `awk' program into
  1780. records and fields.  Records are separated by a character called the
  1781. "record separator".  By default, the record separator is the newline
  1782. character.  This is why records are, by default, single lines.  You can
  1783. use a different character for the record separator by assigning the
  1784. character to the built-in variable `RS'.
  1785.    You can change the value of `RS' in the `awk' program, like any
  1786. other variable, with the assignment operator, `=' (*note Assignment
  1787. Expressions: Assignment Ops.).  The new record-separator character
  1788. should be enclosed in quotation marks, which indicate a string
  1789. constant.  Often the right time to do this is at the beginning of
  1790. execution, before any input has been processed, so that the very first
  1791. record will be read with the proper separator.  To do this, use the
  1792. special `BEGIN' pattern (*note The `BEGIN' and `END' Special Patterns:
  1793. BEGIN/END.).  For example:
  1794.      awk 'BEGIN { RS = "/" } ; { print $0 }' BBS-list
  1795. changes the value of `RS' to `"/"', before reading any input.  This is
  1796. a string whose first character is a slash; as a result, records are
  1797. separated by slashes.  Then the input file is read, and the second rule
  1798. in the `awk' program (the action with no pattern) prints each record.
  1799. Since each `print' statement adds a newline at the end of its output,
  1800. the effect of this `awk' program is to copy the input with each slash
  1801. changed to a newline.  Here are the results of running the program on
  1802. `BBS-list':
  1803.      $ awk 'BEGIN { RS = "/" } ; { print $0 }' BBS-list
  1804.      -| aardvark     555-5553     1200
  1805.      -| 300          B
  1806.      -| alpo-net     555-3412     2400
  1807.      -| 1200
  1808.      -| 300     A
  1809.      -| barfly       555-7685     1200
  1810.      -| 300          A
  1811.      -| bites        555-1675     2400
  1812.      -| 1200
  1813.      -| 300     A
  1814.      -| camelot      555-0542     300               C
  1815.      -| core         555-2912     1200
  1816.      -| 300          C
  1817.      -| fooey        555-1234     2400
  1818.      -| 1200
  1819.      -| 300     B
  1820.      -| foot         555-6699     1200
  1821.      -| 300          B
  1822.      -| macfoo       555-6480     1200
  1823.      -| 300          A
  1824.      -| sdace        555-3430     2400
  1825.      -| 1200
  1826.      -| 300     A
  1827.      -| sabafoo      555-2127     1200
  1828.      -| 300          C
  1829.      -|
  1830. Note that the entry for the `camelot' BBS is not split.  In the
  1831. original data file (*note Data Files for the Examples: Sample Data
  1832. Files.), the line looks like this:
  1833.      camelot      555-0542     300               C
  1834. It only has one baud rate; there are no slashes in the record.
  1835.    Another way to change the record separator is on the command line,
  1836. using the variable-assignment feature (*note Other Command Line
  1837. Arguments: Other Arguments.).
  1838.      awk '{ print $0 }' RS="/" BBS-list
  1839. This sets `RS' to `/' before processing `BBS-list'.
  1840.    Using an unusual character such as `/' for the record separator
  1841. produces correct behavior in the vast majority of cases.  However, the
  1842. following (extreme) pipeline prints a surprising `1'.  There is one
  1843. field, consisting of a newline.  The value of the built-in variable
  1844. `NF' is the number of fields in the current record.
  1845.      $ echo | awk 'BEGIN { RS = "a" } ; { print NF }'
  1846.      -| 1
  1847. Reaching the end of an input file terminates the current input record,
  1848. even if the last character in the file is not the character in `RS'
  1849. (d.c.).
  1850.    The empty string, `""' (a string of no characters), has a special
  1851. meaning as the value of `RS': it means that records are separated by
  1852. one or more blank lines, and nothing else.  *Note Multiple-Line
  1853. Records: Multiple Line, for more details.
  1854.    If you change the value of `RS' in the middle of an `awk' run, the
  1855. new value is used to delimit subsequent records, but the record
  1856. currently being processed (and records already processed) are not
  1857. affected.
  1858.    After the end of the record has been determined, `gawk' sets the
  1859. variable `RT' to the text in the input that matched `RS'.
  1860.    The value of `RS' is in fact not limited to a one-character string.
  1861. It can be any regular expression (*note Regular Expressions: Regexp.).
  1862. In general, each record ends at the next string that matches the
  1863. regular expression; the next record starts at the end of the matching
  1864. string.  This general rule is actually at work in the usual case, where
  1865. `RS' contains just a newline: a record ends at the beginning of the
  1866. next matching string (the next newline in the input) and the following
  1867. record starts just after the end of this string (at the first character
  1868. of the following line).  The newline, since it matches `RS', is not
  1869. part of either record.
  1870.    When `RS' is a single character, `RT' will contain the same single
  1871. character. However, when `RS' is a regular expression, then `RT'
  1872. becomes more useful; it contains the actual input text that matched the
  1873. regular expression.
  1874.    The following example illustrates both of these features.  It sets
  1875. `RS' equal to a regular expression that matches either a newline, or a
  1876. series of one or more upper-case letters with optional leading and/or
  1877. trailing white space (*note Regular Expressions: Regexp.).
  1878.      $ echo record 1 AAAA record 2 BBBB record 3 |
  1879.      > gawk 'BEGIN { RS = "\n|( *[[:upper:]]+ *)" }
  1880.      >             { print "Record =", $0, "and RT =", RT }'
  1881.      -| Record = record 1 and RT =  AAAA
  1882.      -| Record = record 2 and RT =  BBBB
  1883.      -| Record = record 3 and RT =
  1884.      -|
  1885. The final line of output has an extra blank line. This is because the
  1886. value of `RT' is a newline, and then the `print' statement supplies its
  1887. own terminating newline.
  1888.    *Note A Simple Stream Editor: Simple Sed, for a more useful example
  1889. of `RS' as a regexp and `RT'.
  1890.    The use of `RS' as a regular expression and the `RT' variable are
  1891. `gawk' extensions; they are not available in compatibility mode (*note
  1892. Command Line Options: Options.).  In compatibility mode, only the first
  1893. character of the value of `RS' is used to determine the end of the
  1894. record.
  1895.    The `awk' utility keeps track of the number of records that have
  1896. been read so far from the current input file.  This value is stored in a
  1897. built-in variable called `FNR'.  It is reset to zero when a new file is
  1898. started.  Another built-in variable, `NR', is the total number of input
  1899. records read so far from all data files.  It starts at zero but is
  1900. never automatically reset to zero.
  1901. File: gawk.info,  Node: Fields,  Next: Non-Constant Fields,  Prev: Records,  Up: Reading Files
  1902. Examining Fields
  1903. ================
  1904.    When `awk' reads an input record, the record is automatically
  1905. separated or "parsed" by the interpreter into chunks called "fields".
  1906. By default, fields are separated by whitespace, like words in a line.
  1907. Whitespace in `awk' means any string of one or more spaces, tabs or
  1908. newlines;(1) other characters such as formfeed, and so on, that are
  1909. considered whitespace by other languages are *not* considered
  1910. whitespace by `awk'.
  1911.    The purpose of fields is to make it more convenient for you to refer
  1912. to these pieces of the record.  You don't have to use them--you can
  1913. operate on the whole record if you wish--but fields are what make
  1914. simple `awk' programs so powerful.
  1915.    To refer to a field in an `awk' program, you use a dollar-sign, `$',
  1916. followed by the number of the field you want.  Thus, `$1' refers to the
  1917. first field, `$2' to the second, and so on.  For example, suppose the
  1918. following is a line of input:
  1919.      This seems like a pretty nice example.
  1920. Here the first field, or `$1', is `This'; the second field, or `$2', is
  1921. `seems'; and so on.  Note that the last field, `$7', is `example.'.
  1922. Because there is no space between the `e' and the `.', the period is
  1923. considered part of the seventh field.
  1924.    `NF' is a built-in variable whose value is the number of fields in
  1925. the current record.  `awk' updates the value of `NF' automatically,
  1926. each time a record is read.
  1927.    No matter how many fields there are, the last field in a record can
  1928. be represented by `$NF'.  So, in the example above, `$NF' would be the
  1929. same as `$7', which is `example.'.  Why this works is explained below
  1930. (*note Non-constant Field Numbers: Non-Constant Fields.).  If you try
  1931. to reference a field beyond the last one, such as `$8' when the record
  1932. has only seven fields, you get the empty string.
  1933.    `$0', which looks like a reference to the "zeroth" field, is a
  1934. special case: it represents the whole input record.  `$0' is used when
  1935. you are not interested in fields.
  1936.    Here are some more examples:
  1937.      $ awk '$1 ~ /foo/ { print $0 }' BBS-list
  1938.      -| fooey        555-1234     2400/1200/300     B
  1939.      -| foot         555-6699     1200/300          B
  1940.      -| macfoo       555-6480     1200/300          A
  1941.      -| sabafoo      555-2127     1200/300          C
  1942. This example prints each record in the file `BBS-list' whose first
  1943. field contains the string `foo'.  The operator `~' is called a
  1944. "matching operator" (*note How to Use Regular Expressions: Regexp
  1945. Usage.); it tests whether a string (here, the field `$1') matches a
  1946. given regular expression.
  1947.    By contrast, the following example looks for `foo' in *the entire
  1948. record* and prints the first field and the last field for each input
  1949. record containing a match.
  1950.      $ awk '/foo/ { print $1, $NF }' BBS-list
  1951.      -| fooey B
  1952.      -| foot B
  1953.      -| macfoo A
  1954.      -| sabafoo C
  1955.    ---------- Footnotes ----------
  1956.    (1)  In POSIX `awk', newlines are not considered whitespace for
  1957. separating fields.
  1958. File: gawk.info,  Node: Non-Constant Fields,  Next: Changing Fields,  Prev: Fields,  Up: Reading Files
  1959. Non-constant Field Numbers
  1960. ==========================
  1961.    The number of a field does not need to be a constant.  Any
  1962. expression in the `awk' language can be used after a `$' to refer to a
  1963. field.  The value of the expression specifies the field number.  If the
  1964. value is a string, rather than a number, it is converted to a number.
  1965. Consider this example:
  1966.      awk '{ print $NR }'
  1967. Recall that `NR' is the number of records read so far: one in the first
  1968. record, two in the second, etc.  So this example prints the first field
  1969. of the first record, the second field of the second record, and so on.
  1970. For the twentieth record, field number 20 is printed; most likely, the
  1971. record has fewer than 20 fields, so this prints a blank line.
  1972.    Here is another example of using expressions as field numbers:
  1973.      awk '{ print $(2*2) }' BBS-list
  1974.    `awk' must evaluate the expression `(2*2)' and use its value as the
  1975. number of the field to print.  The `*' sign represents multiplication,
  1976. so the expression `2*2' evaluates to four.  The parentheses are used so
  1977. that the multiplication is done before the `$' operation; they are
  1978. necessary whenever there is a binary operator in the field-number
  1979. expression.  This example, then, prints the hours of operation (the
  1980. fourth field) for every line of the file `BBS-list'.  (All of the `awk'
  1981. operators are listed, in order of decreasing precedence, in *Note
  1982. Operator Precedence (How Operators Nest): Precedence.)
  1983.    If the field number you compute is zero, you get the entire record.
  1984. Thus, `$(2-2)' has the same value as `$0'.  Negative field numbers are
  1985. not allowed; trying to reference one will usually terminate your
  1986. running `awk' program.  (The POSIX standard does not define what
  1987. happens when you reference a negative field number.  `gawk' will notice
  1988. this and terminate your program.  Other `awk' implementations may
  1989. behave differently.)
  1990.    As mentioned in *Note Examining Fields: Fields, the number of fields
  1991. in the current record is stored in the built-in variable `NF' (also
  1992. *note Built-in Variables::.).  The expression `$NF' is not a special
  1993. feature: it is the direct consequence of evaluating `NF' and using its
  1994. value as a field number.
  1995. File: gawk.info,  Node: Changing Fields,  Next: Field Separators,  Prev: Non-Constant Fields,  Up: Reading Files
  1996. Changing the Contents of a Field
  1997. ================================
  1998.    You can change the contents of a field as seen by `awk' within an
  1999. `awk' program; this changes what `awk' perceives as the current input
  2000. record.  (The actual input is untouched; `awk' *never* modifies the
  2001. input file.)
  2002.    Consider this example and its output:
  2003.      $ awk '{ $3 = $2 - 10; print $2, $3 }' inventory-shipped
  2004.      -| 13 3
  2005.      -| 15 5
  2006.      -| 15 5
  2007.      ...
  2008. The `-' sign represents subtraction, so this program reassigns field
  2009. three, `$3', to be the value of field two minus ten, `$2 - 10'.  (*Note
  2010. Arithmetic Operators: Arithmetic Ops.) Then field two, and the new
  2011. value for field three, are printed.
  2012.    In order for this to work, the text in field `$2' must make sense as
  2013. a number; the string of characters must be converted to a number in
  2014. order for the computer to do arithmetic on it.  The number resulting
  2015. from the subtraction is converted back to a string of characters which
  2016. then becomes field three.  *Note Conversion of Strings and Numbers:
  2017. Conversion.
  2018.    When you change the value of a field (as perceived by `awk'), the
  2019. text of the input record is recalculated to contain the new field where
  2020. the old one was.  Therefore, `$0' changes to reflect the altered field.
  2021. Thus, this program prints a copy of the input file, with 10 subtracted
  2022. from the second field of each line.
  2023.      $ awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
  2024.      -| Jan 3 25 15 115
  2025.      -| Feb 5 32 24 226
  2026.      -| Mar 5 24 34 228
  2027.      ...
  2028.    You can also assign contents to fields that are out of range.  For
  2029. example:
  2030.      $ awk '{ $6 = ($5 + $4 + $3 + $2)
  2031.      >        print $6 }' inventory-shipped
  2032.      -| 168
  2033.      -| 297
  2034.      -| 301
  2035.      ...
  2036. We've just created `$6', whose value is the sum of fields `$2', `$3',
  2037. `$4', and `$5'.  The `+' sign represents addition.  For the file
  2038. `inventory-shipped', `$6' represents the total number of parcels
  2039. shipped for a particular month.
  2040.    Creating a new field changes `awk''s internal copy of the current
  2041. input record--the value of `$0'.  Thus, if you do `print $0' after
  2042. adding a field, the record printed includes the new field, with the
  2043. appropriate number of field separators between it and the previously
  2044. existing fields.
  2045.    This recomputation affects and is affected by `NF' (the number of
  2046. fields; *note Examining Fields: Fields.), and by a feature that has not
  2047. been discussed yet, the "output field separator", `OFS', which is used
  2048. to separate the fields (*note Output Separators::.).  For example, the
  2049. value of `NF' is set to the number of the highest field you create.
  2050.    Note, however, that merely *referencing* an out-of-range field does
  2051. *not* change the value of either `$0' or `NF'.  Referencing an
  2052. out-of-range field only produces an empty string.  For example:
  2053.      if ($(NF+1) != "")
  2054.          print "can't happen"
  2055.      else
  2056.          print "everything is normal"
  2057. should print `everything is normal', because `NF+1' is certain to be
  2058. out of range.  (*Note The `if'-`else' Statement: If Statement, for more
  2059. information about `awk''s `if-else' statements.  *Note Variable Typing
  2060. and Comparison Expressions: Typing and Comparison, for more information
  2061. about the `!=' operator.)
  2062.    It is important to note that making an assignment to an existing
  2063. field will change the value of `$0', but will not change the value of
  2064. `NF', even when you assign the empty string to a field.  For example:
  2065.      $ echo a b c d | awk '{ OFS = ":"; $2 = ""
  2066.      >                       print $0; print NF }'
  2067.      -| a::c:d
  2068.      -| 4
  2069. The field is still there; it just has an empty value.  You can tell
  2070. because there are two colons in a row.
  2071.    This example shows what happens if you create a new field.
  2072.      $ echo a b c d | awk '{ OFS = ":"; $2 = ""; $6 = "new"
  2073.      >                       print $0; print NF }'
  2074.      -| a::c:d::new
  2075.      -| 6
  2076. The intervening field, `$5' is created with an empty value (indicated
  2077. by the second pair of adjacent colons), and `NF' is updated with the
  2078. value six.
  2079.    Finally, decrementing `NF' will lose the values of the fields after
  2080. the new value of `NF', and `$0' will be recomputed.  Here is an example:
  2081.      $ echo a b c d e f | ../gawk '{ print "NF =", NF;
  2082.      >                               NF = 3; print $0 }'
  2083.      -| NF = 6
  2084.      -| a b c
  2085. File: gawk.info,  Node: Field Separators,  Next: Constant Size,  Prev: Changing Fields,  Up: Reading Files
  2086. Specifying How Fields are Separated
  2087. ===================================
  2088.    This section is rather long; it describes one of the most fundamental
  2089. operations in `awk'.
  2090. * Menu:
  2091. * Basic Field Splitting::        How fields are split with single characters
  2092.                                  or simple strings.
  2093. * Regexp Field Splitting::       Using regexps as the field separator.
  2094. * Single Character Fields::      Making each character a separate field.
  2095. * Command Line Field Separator:: Setting `FS' from the command line.
  2096. * Field Splitting Summary::      Some final points and a summary table.
  2097. File: gawk.info,  Node: Basic Field Splitting,  Next: Regexp Field Splitting,  Prev: Field Separators,  Up: Field Separators
  2098. The Basics of Field Separating
  2099. ------------------------------
  2100.    The "field separator", which is either a single character or a
  2101. regular expression, controls the way `awk' splits an input record into
  2102. fields.  `awk' scans the input record for character sequences that
  2103. match the separator; the fields themselves are the text between the
  2104. matches.
  2105.    In the examples below, we use the bullet symbol "*" to represent
  2106. spaces in the output.
  2107.    If the field separator is `oo', then the following line:
  2108.      moo goo gai pan
  2109. would be split into three fields: `m', `*g' and `*gai*pan'.  Note the
  2110. leading spaces in the values of the second and third fields.
  2111.    The field separator is represented by the built-in variable `FS'.
  2112. Shell programmers take note!  `awk' does *not* use the name `IFS' which
  2113. is used by the POSIX compatible shells (such as the Bourne shell, `sh',
  2114. or the GNU Bourne-Again Shell, Bash).
  2115.    You can change the value of `FS' in the `awk' program with the
  2116. assignment operator, `=' (*note Assignment Expressions: Assignment
  2117. Ops.).  Often the right time to do this is at the beginning of
  2118. execution, before any input has been processed, so that the very first
  2119. record will be read with the proper separator.  To do this, use the
  2120. special `BEGIN' pattern (*note The `BEGIN' and `END' Special Patterns:
  2121. BEGIN/END.).  For example, here we set the value of `FS' to the string
  2122. `","':
  2123.      awk 'BEGIN { FS = "," } ; { print $2 }'
  2124. Given the input line,
  2125.      John Q. Smith, 29 Oak St., Walamazoo, MI 42139
  2126. this `awk' program extracts and prints the string `*29*Oak*St.'.
  2127.    Sometimes your input data will contain separator characters that
  2128. don't separate fields the way you thought they would.  For instance, the
  2129. person's name in the example we just used might have a title or suffix
  2130. attached, such as `John Q. Smith, LXIX'.  From input containing such a
  2131. name:
  2132.      John Q. Smith, LXIX, 29 Oak St., Walamazoo, MI 42139
  2133. the above program would extract `*LXIX', instead of `*29*Oak*St.'.  If
  2134. you were expecting the program to print the address, you would be
  2135. surprised.  The moral is: choose your data layout and separator
  2136. characters carefully to prevent such problems.
  2137.    Normally, fields are separated by whitespace sequences (spaces, tabs
  2138. and newlines), not by single spaces: two spaces in a row do not delimit
  2139. an empty field.  The default value of the field separator `FS' is a
  2140. string containing a single space, `" "'.  If this value were
  2141. interpreted in the usual way, each space character would separate
  2142. fields, so two spaces in a row would make an empty field between them.
  2143. The reason this does not happen is that a single space as the value of
  2144. `FS' is a special case: it is taken to specify the default manner of
  2145. delimiting fields.
  2146.    If `FS' is any other single character, such as `","', then each
  2147. occurrence of that character separates two fields.  Two consecutive
  2148. occurrences delimit an empty field.  If the character occurs at the
  2149. beginning or the end of the line, that too delimits an empty field.  The
  2150. space character is the only single character which does not follow these
  2151. rules.
  2152. File: gawk.info,  Node: Regexp Field Splitting,  Next: Single Character Fields,  Prev: Basic Field Splitting,  Up: Field Separators
  2153. Using Regular Expressions to Separate Fields
  2154. --------------------------------------------
  2155.    The previous node discussed the use of single characters or simple
  2156. strings as the value of `FS'.  More generally, the value of `FS' may be
  2157. a string containing any regular expression.  In this case, each match
  2158. in the record for the regular expression separates fields.  For
  2159. example, the assignment:
  2160.      FS = ", \t"
  2161. makes every area of an input line that consists of a comma followed by a
  2162. space and a tab, into a field separator.  (`\t' is an "escape sequence"
  2163. that stands for a tab; *note Escape Sequences::., for the complete list
  2164. of similar escape sequences.)
  2165.    For a less trivial example of a regular expression, suppose you want
  2166. single spaces to separate fields the way single commas were used above.
  2167. You can set `FS' to `"[ ]"' (left bracket, space, right bracket).  This
  2168. regular expression matches a single space and nothing else (*note
  2169. Regular Expressions: Regexp.).
  2170.    There is an important difference between the two cases of `FS = " "'
  2171. (a single space) and `FS = "[ \t\n]+"' (left bracket, space, backslash,
  2172. "t", backslash, "n", right bracket, which is a regular expression
  2173. matching one or more spaces, tabs, or newlines).  For both values of
  2174. `FS', fields are separated by runs of spaces, tabs and/or newlines.
  2175. However, when the value of `FS' is `" "', `awk' will first strip
  2176. leading and trailing whitespace from the record, and then decide where
  2177. the fields are.
  2178.    For example, the following pipeline prints `b':
  2179.      $ echo ' a b c d ' | awk '{ print $2 }'
  2180.      -| b
  2181. However, this pipeline prints `a' (note the extra spaces around each
  2182. letter):
  2183.      $ echo ' a  b  c  d ' | awk 'BEGIN { FS = "[ \t]+" }
  2184.      >                                  { print $2 }'
  2185.      -| a
  2186. In this case, the first field is "null", or empty.
  2187.    The stripping of leading and trailing whitespace also comes into
  2188. play whenever `$0' is recomputed.  For instance, study this pipeline:
  2189.      $ echo '   a b c d' | awk '{ print; $2 = $2; print }'
  2190.      -|    a b c d
  2191.      -| a b c d
  2192. The first `print' statement prints the record as it was read, with
  2193. leading whitespace intact.  The assignment to `$2' rebuilds `$0' by
  2194. concatenating `$1' through `$NF' together, separated by the value of
  2195. `OFS'.  Since the leading whitespace was ignored when finding `$1', it
  2196. is not part of the new `$0'.  Finally, the last `print' statement
  2197. prints the new `$0'.
  2198. File: gawk.info,  Node: Single Character Fields,  Next: Command Line Field Separator,  Prev: Regexp Field Splitting,  Up: Field Separators
  2199. Making Each Character a Separate Field
  2200. --------------------------------------
  2201.    There are times when you may want to examine each character of a
  2202. record separately.  In `gawk', this is easy to do, you simply assign
  2203. the null string (`""') to `FS'. In this case, each individual character
  2204. in the record will become a separate field.  Here is an example:
  2205.      $ echo a b | gawk 'BEGIN { FS = "" }
  2206.      >                  {
  2207.      >                      for (i = 1; i <= NF; i = i + 1)
  2208.      >                          print "Field", i, "is", $i
  2209.      >                  }'
  2210.      -| Field 1 is a
  2211.      -| Field 2 is
  2212.      -| Field 3 is b
  2213.    Traditionally, the behavior for `FS' equal to `""' was not defined.
  2214. In this case, Unix `awk' would simply treat the entire record as only
  2215. having one field (d.c.).  In compatibility mode (*note Command Line
  2216. Options: Options.), if `FS' is the null string, then `gawk' will also
  2217. behave this way.
  2218. File: gawk.info,  Node: Command Line Field Separator,  Next: Field Splitting Summary,  Prev: Single Character Fields,  Up: Field Separators
  2219. Setting `FS' from the Command Line
  2220. ----------------------------------
  2221.    `FS' can be set on the command line.  You use the `-F' option to do
  2222. so.  For example:
  2223.      awk -F, 'PROGRAM' INPUT-FILES
  2224. sets `FS' to be the `,' character.  Notice that the option uses a
  2225. capital `F'.  Contrast this with `-f', which specifies a file
  2226. containing an `awk' program.  Case is significant in command line
  2227. options: the `-F' and `-f' options have nothing to do with each other.
  2228. You can use both options at the same time to set the `FS' variable
  2229. *and* get an `awk' program from a file.
  2230.    The value used for the argument to `-F' is processed in exactly the
  2231. same way as assignments to the built-in variable `FS'.  This means that
  2232. if the field separator contains special characters, they must be escaped
  2233. appropriately.  For example, to use a `\' as the field separator, you
  2234. would have to type:
  2235.      # same as FS = "\\"
  2236.      awk -F\\\\ '...' files ...
  2237. Since `\' is used for quoting in the shell, `awk' will see `-F\\'.
  2238. Then `awk' processes the `\\' for escape characters (*note Escape
  2239. Sequences::.), finally yielding a single `\' to be used for the field
  2240. separator.
  2241.    As a special case, in compatibility mode (*note Command Line
  2242. Options: Options.), if the argument to `-F' is `t', then `FS' is set to
  2243. the tab character.  This is because if you type `-F\t' at the shell,
  2244. without any quotes, the `\' gets deleted, so `awk' figures that you
  2245. really want your fields to be separated with tabs, and not `t's.  Use
  2246. `-v FS="t"' on the command line if you really do want to separate your
  2247. fields with `t's (*note Command Line Options: Options.).
  2248.    For example, let's use an `awk' program file called `baud.awk' that
  2249. contains the pattern `/300/', and the action `print $1'.  Here is the
  2250. program:
  2251.      /300/   { print $1 }
  2252.    Let's also set `FS' to be the `-' character, and run the program on
  2253. the file `BBS-list'.  The following command prints a list of the names
  2254. of the bulletin boards that operate at 300 baud and the first three
  2255. digits of their phone numbers:
  2256.      $ awk -F- -f baud.awk BBS-list
  2257.      -| aardvark     555
  2258.      -| alpo
  2259.      -| barfly       555
  2260.      ...
  2261. Note the second line of output.  In the original file (*note Data Files
  2262. for the Examples: Sample Data Files.), the second line looked like this:
  2263.      alpo-net     555-3412     2400/1200/300     A
  2264.    The `-' as part of the system's name was used as the field
  2265. separator, instead of the `-' in the phone number that was originally
  2266. intended.  This demonstrates why you have to be careful in choosing
  2267. your field and record separators.
  2268.    On many Unix systems, each user has a separate entry in the system
  2269. password file, one line per user.  The information in these lines is
  2270. separated by colons.  The first field is the user's logon name, and the
  2271. second is the user's encrypted password.  A password file entry might
  2272. look like this:
  2273.      arnold:xyzzy:2076:10:Arnold Robbins:/home/arnold:/bin/sh
  2274.    The following program searches the system password file, and prints
  2275. the entries for users who have no password:
  2276.      awk -F: '$2 == ""' /etc/passwd
  2277. File: gawk.info,  Node: Field Splitting Summary,  Prev: Command Line Field Separator,  Up: Field Separators
  2278. Field Splitting Summary
  2279. -----------------------
  2280.    According to the POSIX standard, `awk' is supposed to behave as if
  2281. each record is split into fields at the time that it is read.  In
  2282. particular, this means that you can change the value of `FS' after a
  2283. record is read, and the value of the fields (i.e. how they were split)
  2284. should reflect the old value of `FS', not the new one.
  2285.    However, many implementations of `awk' do not work this way.
  2286. Instead, they defer splitting the fields until a field is actually
  2287. referenced.  The fields will be split using the *current* value of
  2288. `FS'! (d.c.) This behavior can be difficult to diagnose. The following
  2289. example illustrates the difference between the two methods.  (The
  2290. `sed'(1) command prints just the first line of `/etc/passwd'.)
  2291.      sed 1q /etc/passwd | awk '{ FS = ":" ; print $1 }'
  2292. will usually print
  2293.      root
  2294. on an incorrect implementation of `awk', while `gawk' will print
  2295. something like
  2296.      root:nSijPlPhZZwgE:0:0:Root:/:
  2297.    The following table summarizes how fields are split, based on the
  2298. value of `FS'. (`==' means "is equal to.")
  2299. `FS == " "'
  2300.      Fields are separated by runs of whitespace.  Leading and trailing
  2301.      whitespace are ignored.  This is the default.
  2302. `FS == ANY OTHER SINGLE CHARACTER'
  2303.      Fields are separated by each occurrence of the character.  Multiple
  2304.      successive occurrences delimit empty fields, as do leading and
  2305.      trailing occurrences.  The character can even be a regexp
  2306.      metacharacter; it does not need to be escaped.
  2307. `FS == REGEXP'
  2308.      Fields are separated by occurrences of characters that match
  2309.      REGEXP.  Leading and trailing matches of REGEXP delimit empty
  2310.      fields.
  2311. `FS == ""'
  2312.      Each individual character in the record becomes a separate field.
  2313.    ---------- Footnotes ----------
  2314.    (1)  The `sed' utility is a "stream editor." Its behavior is also
  2315. defined by the POSIX standard.
  2316. File: gawk.info,  Node: Constant Size,  Next: Multiple Line,  Prev: Field Separators,  Up: Reading Files
  2317. Reading Fixed-width Data
  2318. ========================
  2319.    (This section discusses an advanced, experimental feature.  If you
  2320. are a novice `awk' user, you may wish to skip it on the first reading.)
  2321.    `gawk' version 2.13 introduced a new facility for dealing with
  2322. fixed-width fields with no distinctive field separator.  Data of this
  2323. nature arises, for example, in  the input for old FORTRAN programs where
  2324. numbers are run together; or in the output of programs that did not
  2325. anticipate the use of their output as input for other programs.
  2326.    An example of the latter is a table where all the columns are lined
  2327. up by the use of a variable number of spaces and *empty fields are just
  2328. spaces*.  Clearly, `awk''s normal field splitting based on `FS' will
  2329. not work well in this case.  Although a portable `awk' program can use
  2330. a series of `substr' calls on `$0' (*note Built-in Functions for String
  2331. Manipulation: String Functions.), this is awkward and inefficient for a
  2332. large number of fields.
  2333.    The splitting of an input record into fixed-width fields is
  2334. specified by assigning a string containing space-separated numbers to
  2335. the built-in variable `FIELDWIDTHS'.  Each number specifies the width
  2336. of the field *including* columns between fields.  If you want to ignore
  2337. the columns between fields, you can specify the width as a separate
  2338. field that is subsequently ignored.
  2339.    The following data is the output of the Unix `w' utility.  It is
  2340. useful to illustrate the use of `FIELDWIDTHS'.
  2341.       10:06pm  up 21 days, 14:04,  23 users
  2342.      User     tty       login  idle   JCPU   PCPU  what
  2343.      hzuo     ttyV0     8:58pm            9      5  vi p24.tex
  2344.      hzang    ttyV3     6:37pm    50                -csh
  2345.      eklye    ttyV5     9:53pm            7      1  em thes.tex
  2346.      dportein ttyV6     8:17pm  1:47                -csh
  2347.      gierd    ttyD3    10:00pm     1                elm
  2348.      dave     ttyD4     9:47pm            4      4  w
  2349.      brent    ttyp0    26Jun91  4:46  26:46   4:41  bash
  2350.      dave     ttyq4    26Jun9115days     46     46  wnewmail
  2351.    The following program takes the above input, converts the idle time
  2352. to number of seconds and prints out the first two fields and the
  2353. calculated idle time.  (This program uses a number of `awk' features
  2354. that haven't been introduced yet.)
  2355.      BEGIN  { FIELDWIDTHS = "9 6 10 6 7 7 35" }
  2356.      NR > 2 {
  2357.          idle = $4
  2358.          sub(/^  */, "", idle)   # strip leading spaces
  2359.          if (idle == "")
  2360.              idle = 0
  2361.          if (idle ~ /:/) {
  2362.              split(idle, t, ":")
  2363.              idle = t[1] * 60 + t[2]
  2364.          }
  2365.          if (idle ~ /days/)
  2366.              idle *= 24 * 60 * 60
  2367.      
  2368.          print $1, $2, idle
  2369.      }
  2370.    Here is the result of running the program on the data:
  2371.      hzuo      ttyV0  0
  2372.      hzang     ttyV3  50
  2373.      eklye     ttyV5  0
  2374.      dportein  ttyV6  107
  2375.      gierd     ttyD3  1
  2376.      dave      ttyD4  0
  2377.      brent     ttyp0  286
  2378.      dave      ttyq4  1296000
  2379.    Another (possibly more practical) example of fixed-width input data
  2380. would be the input from a deck of balloting cards.  In some parts of
  2381. the United States, voters mark their choices by punching holes in
  2382. computer cards.  These cards are then processed to count the votes for
  2383. any particular candidate or on any particular issue.  Since a voter may
  2384. choose not to vote on some issue, any column on the card may be empty.
  2385. An `awk' program for processing such data could use the `FIELDWIDTHS'
  2386. feature to simplify reading the data.  (Of course, getting `gawk' to
  2387. run on a system with card readers is another story!)
  2388.    Assigning a value to `FS' causes `gawk' to return to using `FS' for
  2389. field splitting.  Use `FS = FS' to make this happen, without having to
  2390. know the current value of `FS'.
  2391.    This feature is still experimental, and may evolve over time.  Note
  2392. that in particular, `gawk' does not attempt to verify the sanity of the
  2393. values used in the value of `FIELDWIDTHS'.
  2394. File: gawk.info,  Node: Multiple Line,  Next: Getline,  Prev: Constant Size,  Up: Reading Files
  2395. Multiple-Line Records
  2396. =====================
  2397.    In some data bases, a single line cannot conveniently hold all the
  2398. information in one entry.  In such cases, you can use multi-line
  2399. records.
  2400.    The first step in doing this is to choose your data format: when
  2401. records are not defined as single lines, how do you want to define them?
  2402. What should separate records?
  2403.    One technique is to use an unusual character or string to separate
  2404. records.  For example, you could use the formfeed character (written
  2405. `\f' in `awk', as in C) to separate them, making each record a page of
  2406. the file.  To do this, just set the variable `RS' to `"\f"' (a string
  2407. containing the formfeed character).  Any other character could equally
  2408. well be used, as long as it won't be part of the data in a record.
  2409.    Another technique is to have blank lines separate records.  By a
  2410. special dispensation, an empty string as the value of `RS' indicates
  2411. that records are separated by one or more blank lines.  If you set `RS'
  2412. to the empty string, a record always ends at the first blank line
  2413. encountered.  And the next record doesn't start until the first
  2414. non-blank line that follows--no matter how many blank lines appear in a
  2415. row, they are considered one record-separator.
  2416.    You can achieve the same effect as `RS = ""' by assigning the string
  2417. `"\n\n+"' to `RS'. This regexp matches the newline at the end of the
  2418. record, and one or more blank lines after the record.  In addition, a
  2419. regular expression always matches the longest possible sequence when
  2420. there is a choice (*note How Much Text Matches?: Leftmost Longest.).
  2421. So the next record doesn't start until the first non-blank line that
  2422. follows--no matter how many blank lines appear in a row, they are
  2423. considered one record-separator.
  2424.    There is an important difference between `RS = ""' and `RS =
  2425. "\n\n+"'. In the first case, leading newlines in the input data file
  2426. are ignored, and if a file ends without extra blank lines after the
  2427. last record, the final newline is removed from the record.  In the
  2428. second case, this special processing is not done (d.c.).
  2429.    Now that the input is separated into records, the second step is to
  2430. separate the fields in the record.  One way to do this is to divide each
  2431. of the lines into fields in the normal manner.  This happens by default
  2432. as the result of a special feature: when `RS' is set to the empty
  2433. string, the newline character *always* acts as a field separator.  This
  2434. is in addition to whatever field separations result from `FS'.
  2435.    The original motivation for this special exception was probably to
  2436. provide useful behavior in the default case (i.e. `FS' is equal to
  2437. `" "').  This feature can be a problem if you really don't want the
  2438. newline character to separate fields, since there is no way to prevent
  2439. it.  However, you can work around this by using the `split' function to
  2440. break up the record manually (*note Built-in Functions for String
  2441. Manipulation: String Functions.).
  2442.    Another way to separate fields is to put each field on a separate
  2443. line: to do this, just set the variable `FS' to the string `"\n"'.
  2444. (This simple regular expression matches a single newline.)
  2445.    A practical example of a data file organized this way might be a
  2446. mailing list, where each entry is separated by blank lines.  If we have
  2447. a mailing list in a file named `addresses', that looks like this:
  2448.      Jane Doe
  2449.      123 Main Street
  2450.      Anywhere, SE 12345-6789
  2451.      
  2452.      John Smith
  2453.      456 Tree-lined Avenue
  2454.      Smallville, MW 98765-4321
  2455.      
  2456.      ...
  2457. A simple program to process this file would look like this:
  2458.      # addrs.awk --- simple mailing list program
  2459.      
  2460.      # Records are separated by blank lines.
  2461.      # Each line is one field.
  2462.      BEGIN { RS = "" ; FS = "\n" }
  2463.      
  2464.      {
  2465.            print "Name is:", $1
  2466.            print "Address is:", $2
  2467.            print "City and State are:", $3
  2468.            print ""
  2469.      }
  2470.    Running the program produces the following output:
  2471.      $ awk -f addrs.awk addresses
  2472.      -| Name is: Jane Doe
  2473.      -| Address is: 123 Main Street
  2474.      -| City and State are: Anywhere, SE 12345-6789
  2475.      -|
  2476.      -| Name is: John Smith
  2477.      -| Address is: 456 Tree-lined Avenue
  2478.      -| City and State are: Smallville, MW 98765-4321
  2479.      -|
  2480.      ...
  2481.    *Note Printing Mailing Labels: Labels Program, for a more realistic
  2482. program that deals with address lists.
  2483.    The following table summarizes how records are split, based on the
  2484. value of `RS'. (`==' means "is equal to.")
  2485. `RS == "\n"'
  2486.      Records are separated by the newline character (`\n').  In effect,
  2487.      every line in the data file is a separate record, including blank
  2488.      lines.  This is the default.
  2489. `RS == ANY SINGLE CHARACTER'
  2490.      Records are separated by each occurrence of the character.
  2491.      Multiple successive occurrences delimit empty records.
  2492. `RS == ""'
  2493.      Records are separated by runs of blank lines.  The newline
  2494.      character always serves as a field separator, in addition to
  2495.      whatever value `FS' may have. Leading and trailing newlines in a
  2496.      file are ignored.
  2497. `RS == REGEXP'
  2498.      Records are separated by occurrences of characters that match
  2499.      REGEXP.  Leading and trailing matches of REGEXP delimit empty
  2500.      records.
  2501.    In all cases, `gawk' sets `RT' to the input text that matched the
  2502. value specified by `RS'.
  2503. File: gawk.info,  Node: Getline,  Prev: Multiple Line,  Up: Reading Files
  2504. Explicit Input with `getline'
  2505. =============================
  2506.    So far we have been getting our input data from `awk''s main input
  2507. stream--either the standard input (usually your terminal, sometimes the
  2508. output from another program) or from the files specified on the command
  2509. line.  The `awk' language has a special built-in command called
  2510. `getline' that can be used to read input under your explicit control.
  2511. * Menu:
  2512. * Getline Intro::            Introduction to the `getline' function.
  2513. * Plain Getline::            Using `getline' with no arguments.
  2514. * Getline/Variable::         Using `getline' into a variable.
  2515. * Getline/File::             Using `getline' from a file.
  2516. * Getline/Variable/File::    Using `getline' into a variable from a
  2517.                              file.
  2518. * Getline/Pipe::             Using `getline' from a pipe.
  2519. * Getline/Variable/Pipe::    Using `getline' into a variable from a
  2520.                              pipe.
  2521. * Getline Summary::          Summary Of `getline' Variants.
  2522. File: gawk.info,  Node: Getline Intro,  Next: Plain Getline,  Prev: Getline,  Up: Getline
  2523. Introduction to `getline'
  2524. -------------------------
  2525.    This command is used in several different ways, and should *not* be
  2526. used by beginners.  It is covered here because this is the chapter on
  2527. input.  The examples that follow the explanation of the `getline'
  2528. command include material that has not been covered yet.  Therefore,
  2529. come back and study the `getline' command *after* you have reviewed the
  2530. rest of this Info file and have a good knowledge of how `awk' works.
  2531.    `getline' returns one if it finds a record, and zero if the end of
  2532. the file is encountered.  If there is some error in getting a record,
  2533. such as a file that cannot be opened, then `getline' returns -1.  In
  2534. this case, `gawk' sets the variable `ERRNO' to a string describing the
  2535. error that occurred.
  2536.    In the following examples, COMMAND stands for a string value that
  2537. represents a shell command.
  2538. File: gawk.info,  Node: Plain Getline,  Next: Getline/Variable,  Prev: Getline Intro,  Up: Getline
  2539. Using `getline' with No Arguments
  2540. ---------------------------------
  2541.    The `getline' command can be used without arguments to read input
  2542. from the current input file.  All it does in this case is read the next
  2543. input record and split it up into fields.  This is useful if you've
  2544. finished processing the current record, but you want to do some special
  2545. processing *right now* on the next record.  Here's an example:
  2546.      awk '{
  2547.           if ((t = index($0, "/*")) != 0) {
  2548.                # value will be "" if t is 1
  2549.                tmp = substr($0, 1, t - 1)
  2550.                u = index(substr($0, t + 2), "*/")
  2551.                while (u == 0) {
  2552.                     if (getline <= 0) {
  2553.                          m = "unexpected EOF or error"
  2554.                          m = (m ": " ERRNO)
  2555.                          print m > "/dev/stderr"
  2556.                          exit
  2557.                     }
  2558.                     t = -1
  2559.                     u = index($0, "*/")
  2560.                }
  2561.                # substr expression will be "" if */
  2562.                # occurred at end of line
  2563.                $0 = tmp substr($0, t + u + 3)
  2564.           }
  2565.           print $0
  2566.      }'
  2567.    This `awk' program deletes all C-style comments, `/* ...  */', from
  2568. the input.  By replacing the `print $0' with other statements, you
  2569. could perform more complicated processing on the decommented input,
  2570. like searching for matches of a regular expression.  This program has a
  2571. subtle problem--it does not work if one comment ends and another begins
  2572. on the same line.
  2573.    This form of the `getline' command sets `NF' (the number of fields;
  2574. *note Examining Fields: Fields.), `NR' (the number of records read so
  2575. far; *note How Input is Split into Records: Records.), `FNR' (the
  2576. number of records read from this input file), and the value of `$0'.
  2577.    *Note:* the new value of `$0' is used in testing the patterns of any
  2578. subsequent rules.  The original value of `$0' that triggered the rule
  2579. which executed `getline' is lost (d.c.).  By contrast, the `next'
  2580. statement reads a new record but immediately begins processing it
  2581. normally, starting with the first rule in the program.  *Note The
  2582. `next' Statement: Next Statement.
  2583. File: gawk.info,  Node: Getline/Variable,  Next: Getline/File,  Prev: Plain Getline,  Up: Getline
  2584. Using `getline' Into a Variable
  2585. -------------------------------
  2586.    You can use `getline VAR' to read the next record from `awk''s input
  2587. into the variable VAR.  No other processing is done.
  2588.    For example, suppose the next line is a comment, or a special string,
  2589. and you want to read it, without triggering any rules.  This form of
  2590. `getline' allows you to read that line and store it in a variable so
  2591. that the main read-a-line-and-check-each-rule loop of `awk' never sees
  2592.    The following example swaps every two lines of input.  For example,
  2593. given:
  2594.      wan
  2595.      tew
  2596.      free
  2597.      phore
  2598. it outputs:
  2599.      tew
  2600.      wan
  2601.      phore
  2602.      free
  2603. Here's the program:
  2604.      awk '{
  2605.           if ((getline tmp) > 0) {
  2606.                print tmp
  2607.                print $0
  2608.           } else
  2609.                print $0
  2610.      }'
  2611.    The `getline' command used in this way sets only the variables `NR'
  2612. and `FNR' (and of course, VAR).  The record is not split into fields,
  2613. so the values of the fields (including `$0') and the value of `NF' do
  2614. not change.
  2615. File: gawk.info,  Node: Getline/File,  Next: Getline/Variable/File,  Prev: Getline/Variable,  Up: Getline
  2616. Using `getline' from a File
  2617. ---------------------------
  2618.    Use `getline < FILE' to read the next record from the file FILE.
  2619. Here FILE is a string-valued expression that specifies the file name.
  2620. `< FILE' is called a "redirection" since it directs input to come from
  2621. a different place.
  2622.    For example, the following program reads its input record from the
  2623. file `secondary.input' when it encounters a first field with a value
  2624. equal to 10 in the current input file.
  2625.      awk '{
  2626.          if ($1 == 10) {
  2627.               getline < "secondary.input"
  2628.               print
  2629.          } else
  2630.               print
  2631.      }'
  2632.    Since the main input stream is not used, the values of `NR' and
  2633. `FNR' are not changed.  But the record read is split into fields in the
  2634. normal manner, so the values of `$0' and other fields are changed.  So
  2635. is the value of `NF'.
  2636.    According to POSIX, `getline < EXPRESSION' is ambiguous if
  2637. EXPRESSION contains unparenthesized operators other than `$'; for
  2638. example, `getline < dir "/" file' is ambiguous because the
  2639. concatenation operator is not parenthesized, and you should write it as
  2640. `getline < (dir "/" file)' if you want your program to be portable to
  2641. other `awk' implementations.
  2642. File: gawk.info,  Node: Getline/Variable/File,  Next: Getline/Pipe,  Prev: Getline/File,  Up: Getline
  2643. Using `getline' Into a Variable from a File
  2644. -------------------------------------------
  2645.    Use `getline VAR < FILE' to read input the file FILE and put it in
  2646. the variable VAR.  As above, FILE is a string-valued expression that
  2647. specifies the file from which to read.
  2648.    In this version of `getline', none of the built-in variables are
  2649. changed, and the record is not split into fields.  The only variable
  2650. changed is VAR.
  2651.    According to POSIX, `getline VAR < EXPRESSION' is ambiguous if
  2652. EXPRESSION contains unparenthesized operators other than `$'; for
  2653. example, `getline < dir "/" file' is ambiguous because the
  2654. concatenation operator is not parenthesized, and you should write it as
  2655. `getline < (dir "/" file)' if you want your program to be portable to
  2656. other `awk' implementations.
  2657.    For example, the following program copies all the input files to the
  2658. output, except for records that say `@include FILENAME'.  Such a record
  2659. is replaced by the contents of the file FILENAME.
  2660.      awk '{
  2661.           if (NF == 2 && $1 == "@include") {
  2662.                while ((getline line < $2) > 0)
  2663.                     print line
  2664.                close($2)
  2665.           } else
  2666.                print
  2667.      }'
  2668.    Note here how the name of the extra input file is not built into the
  2669. program; it is taken directly from the data, from the second field on
  2670. the `@include' line.
  2671.    The `close' function is called to ensure that if two identical
  2672. `@include' lines appear in the input, the entire specified file is
  2673. included twice.  *Note Closing Input and Output Files and Pipes: Close
  2674. Files And Pipes.
  2675.    One deficiency of this program is that it does not process nested
  2676. `@include' statements (`@include' statements in included files) the way
  2677. a true macro preprocessor would.  *Note An Easy Way to Use Library
  2678. Functions: Igawk Program, for a program that does handle nested
  2679. `@include' statements.
  2680. File: gawk.info,  Node: Getline/Pipe,  Next: Getline/Variable/Pipe,  Prev: Getline/Variable/File,  Up: Getline
  2681. Using `getline' from a Pipe
  2682. ---------------------------
  2683.    You can pipe the output of a command into `getline', using `COMMAND
  2684. | getline'.  In this case, the string COMMAND is run as a shell command
  2685. and its output is piped into `awk' to be used as input.  This form of
  2686. `getline' reads one record at a time from the pipe.
  2687.    For example, the following program copies its input to its output,
  2688. except for lines that begin with `@execute', which are replaced by the
  2689. output produced by running the rest of the line as a shell command:
  2690.      awk '{
  2691.           if ($1 == "@execute") {
  2692.                tmp = substr($0, 10)
  2693.                while ((tmp | getline) > 0)
  2694.                     print
  2695.                close(tmp)
  2696.           } else
  2697.                print
  2698.      }'
  2699. The `close' function is called to ensure that if two identical
  2700. `@execute' lines appear in the input, the command is run for each one.
  2701. *Note Closing Input and Output Files and Pipes: Close Files And Pipes.
  2702.    Given the input:
  2703.      foo
  2704.      bar
  2705.      baz
  2706.      @execute who
  2707.      bletch
  2708. the program might produce:
  2709.      foo
  2710.      bar
  2711.      baz
  2712.      arnold     ttyv0   Jul 13 14:22
  2713.      miriam     ttyp0   Jul 13 14:23     (murphy:0)
  2714.      bill       ttyp1   Jul 13 14:23     (murphy:0)
  2715.      bletch
  2716. Notice that this program ran the command `who' and printed the result.
  2717. (If you try this program yourself, you will of course get different
  2718. results, showing you who is logged in on your system.)
  2719.    This variation of `getline' splits the record into fields, sets the
  2720. value of `NF' and recomputes the value of `$0'.  The values of `NR' and
  2721. `FNR' are not changed.
  2722.    According to POSIX, `EXPRESSION | getline' is ambiguous if
  2723. EXPRESSION contains unparenthesized operators other than `$'; for
  2724. example, `"echo " "date" | getline' is ambiguous because the
  2725. concatenation operator is not parenthesized, and you should write it as
  2726. `("echo " "date") | getline' if you want your program to be portable to
  2727. other `awk' implementations.
  2728. File: gawk.info,  Node: Getline/Variable/Pipe,  Next: Getline Summary,  Prev: Getline/Pipe,  Up: Getline
  2729. Using `getline' Into a Variable from a Pipe
  2730. -------------------------------------------
  2731.    When you use `COMMAND | getline VAR', the output of the command
  2732. COMMAND is sent through a pipe to `getline' and into the variable VAR.
  2733. For example, the following program reads the current date and time into
  2734. the variable `current_time', using the `date' utility, and then prints
  2735.      awk 'BEGIN {
  2736.           "date" | getline current_time
  2737.           close("date")
  2738.           print "Report printed on " current_time
  2739.      }'
  2740.    In this version of `getline', none of the built-in variables are
  2741. changed, and the record is not split into fields.
  2742.    According to POSIX, `EXPRESSION | getline VAR' is ambiguous if
  2743. EXPRESSION contains unparenthesized operators other than `$'; for
  2744. example, `"echo " "date" | getline VAR' is ambiguous because the
  2745. concatenation operator is not parenthesized, and you should write it as
  2746. `("echo " "date") | getline VAR' if you want your program to be
  2747. portable to other `awk' implementations.
  2748. File: gawk.info,  Node: Getline Summary,  Prev: Getline/Variable/Pipe,  Up: Getline
  2749. Summary of `getline' Variants
  2750. -----------------------------
  2751.    With all the forms of `getline', even though `$0' and `NF', may be
  2752. updated, the record will not be tested against all the patterns in the
  2753. `awk' program, in the way that would happen if the record were read
  2754. normally by the main processing loop of `awk'.  However the new record
  2755. is tested against any subsequent rules.
  2756.    Many `awk' implementations limit the number of pipelines an `awk'
  2757. program may have open to just one!  In `gawk', there is no such limit.
  2758. You can open as many pipelines as the underlying operating system will
  2759. permit.
  2760.    An interesting side-effect occurs if you use `getline' (without a
  2761. redirection) inside a `BEGIN' rule. Since an unredirected `getline'
  2762. reads from the command line data files, the first `getline' command
  2763. causes `awk' to set the value of `FILENAME'. Normally, `FILENAME' does
  2764. not have a value inside `BEGIN' rules, since you have not yet started
  2765. to process the command line data files (d.c.).  (*Note The `BEGIN' and
  2766. `END' Special Patterns: BEGIN/END, also *note Built-in Variables that
  2767. Convey Information: Auto-set..)
  2768.    The following table summarizes the six variants of `getline',
  2769. listing which built-in variables are set by each one.
  2770. `getline'
  2771.      sets `$0', `NF', `FNR', and `NR'.
  2772. `getline VAR'
  2773.      sets VAR, `FNR', and `NR'.
  2774. `getline < FILE'
  2775.      sets `$0', and `NF'.
  2776. `getline VAR < FILE'
  2777.      sets VAR.
  2778. `COMMAND | getline'
  2779.      sets `$0', and `NF'.
  2780. `COMMAND | getline VAR'
  2781.      sets VAR.
  2782. File: gawk.info,  Node: Printing,  Next: Expressions,  Prev: Reading Files,  Up: Top
  2783. Printing Output
  2784. ***************
  2785.    One of the most common actions is to "print", or output, some or all
  2786. of the input.  You use the `print' statement for simple output.  You
  2787. use the `printf' statement for fancier formatting.  Both are described
  2788. in this chapter.
  2789. * Menu:
  2790. * Print::                       The `print' statement.
  2791. * Print Examples::              Simple examples of `print' statements.
  2792. * Output Separators::           The output separators and how to change them.
  2793. * OFMT::                        Controlling Numeric Output With `print'.
  2794. * Printf::                      The `printf' statement.
  2795. * Redirection::                 How to redirect output to multiple files and
  2796.                                 pipes.
  2797. * Special Files::               File name interpretation in `gawk'.
  2798.                                 `gawk' allows access to inherited file
  2799.                                 descriptors.
  2800. * Close Files And Pipes::       Closing Input and Output Files and Pipes.
  2801. File: gawk.info,  Node: Print,  Next: Print Examples,  Prev: Printing,  Up: Printing
  2802. The `print' Statement
  2803. =====================
  2804.    The `print' statement does output with simple, standardized
  2805. formatting.  You specify only the strings or numbers to be printed, in a
  2806. list separated by commas.  They are output, separated by single spaces,
  2807. followed by a newline.  The statement looks like this:
  2808.      print ITEM1, ITEM2, ...
  2809. The entire list of items may optionally be enclosed in parentheses.  The
  2810. parentheses are necessary if any of the item expressions uses the `>'
  2811. relational operator; otherwise it could be confused with a redirection
  2812. (*note Redirecting Output of `print' and `printf': Redirection.).
  2813.    The items to be printed can be constant strings or numbers, fields
  2814. of the current record (such as `$1'), variables, or any `awk'
  2815. expressions.  Numeric values are converted to strings, and then printed.
  2816.    The `print' statement is completely general for computing *what*
  2817. values to print. However, with two exceptions, you cannot specify *how*
  2818. to print them--how many columns, whether to use exponential notation or
  2819. not, and so on.  (For the exceptions, *note Output Separators::., and
  2820. *Note Controlling Numeric Output with `print': OFMT.) For that, you
  2821. need the `printf' statement (*note Using `printf' Statements for
  2822. Fancier Printing: Printf.).
  2823.    The simple statement `print' with no items is equivalent to `print
  2824. $0': it prints the entire current record.  To print a blank line, use
  2825. `print ""', where `""' is the empty string.
  2826.    To print a fixed piece of text, use a string constant such as
  2827. `"Don't Panic"' as one item.  If you forget to use the double-quote
  2828. characters, your text will be taken as an `awk' expression, and you
  2829. will probably get an error.  Keep in mind that a space is printed
  2830. between any two items.
  2831.    Each `print' statement makes at least one line of output.  But it
  2832. isn't limited to one line.  If an item value is a string that contains a
  2833. newline, the newline is output along with the rest of the string.  A
  2834. single `print' can make any number of lines this way.
  2835. File: gawk.info,  Node: Print Examples,  Next: Output Separators,  Prev: Print,  Up: Printing
  2836. Examples of `print' Statements
  2837. ==============================
  2838.    Here is an example of printing a string that contains embedded
  2839. newlines (the `\n' is an escape sequence, used to represent the newline
  2840. character; see *Note Escape Sequences::):
  2841.      $ awk 'BEGIN { print "line one\nline two\nline three" }'
  2842.      -| line one
  2843.      -| line two
  2844.      -| line three
  2845.    Here is an example that prints the first two fields of each input
  2846. record, with a space between them:
  2847.      $ awk '{ print $1, $2 }' inventory-shipped
  2848.      -| Jan 13
  2849.      -| Feb 15
  2850.      -| Mar 15
  2851.      ...
  2852.    A common mistake in using the `print' statement is to omit the comma
  2853. between two items.  This often has the effect of making the items run
  2854. together in the output, with no space.  The reason for this is that
  2855. juxtaposing two string expressions in `awk' means to concatenate them.
  2856. Here is the same program, without the comma:
  2857.      $ awk '{ print $1 $2 }' inventory-shipped
  2858.      -| Jan13
  2859.      -| Feb15
  2860.      -| Mar15
  2861.      ...
  2862.    To someone unfamiliar with the file `inventory-shipped', neither
  2863. example's output makes much sense.  A heading line at the beginning
  2864. would make it clearer.  Let's add some headings to our table of months
  2865. (`$1') and green crates shipped (`$2').  We do this using the `BEGIN'
  2866. pattern (*note The `BEGIN' and `END' Special Patterns: BEGIN/END.) to
  2867. force the headings to be printed only once:
  2868.      awk 'BEGIN {  print "Month Crates"
  2869.                    print "----- ------" }
  2870.                 {  print $1, $2 }' inventory-shipped
  2871. Did you already guess what happens? When run, the program prints the
  2872. following:
  2873.      Month Crates
  2874.      ----- ------
  2875.      Jan 13
  2876.      Feb 15
  2877.      Mar 15
  2878.      ...
  2879. The headings and the table data don't line up!  We can fix this by
  2880. printing some spaces between the two fields:
  2881.      awk 'BEGIN { print "Month Crates"
  2882.                   print "----- ------" }
  2883.                 { print $1, "     ", $2 }' inventory-shipped
  2884.    You can imagine that this way of lining up columns can get pretty
  2885. complicated when you have many columns to fix.  Counting spaces for two
  2886. or three columns can be simple, but more than this and you can get lost
  2887. quite easily.  This is why the `printf' statement was created (*note
  2888. Using `printf' Statements for Fancier Printing: Printf.); one of its
  2889. specialties is lining up columns of data.
  2890.    As a side point, you can continue either a `print' or `printf'
  2891. statement simply by putting a newline after any comma (*note `awk'
  2892. Statements Versus Lines: Statements/Lines.).
  2893. File: gawk.info,  Node: Output Separators,  Next: OFMT,  Prev: Print Examples,  Up: Printing
  2894. Output Separators
  2895. =================
  2896.    As mentioned previously, a `print' statement contains a list of
  2897. items, separated by commas.  In the output, the items are normally
  2898. separated by single spaces.  This need not be the case; a single space
  2899. is only the default.  You can specify any string of characters to use
  2900. as the "output field separator" by setting the built-in variable `OFS'.
  2901. The initial value of this variable is the string `" "', that is, a
  2902. single space.
  2903.    The output from an entire `print' statement is called an "output
  2904. record".  Each `print' statement outputs one output record and then
  2905. outputs a string called the "output record separator".  The built-in
  2906. variable `ORS' specifies this string.  The initial value of `ORS' is
  2907. the string `"\n"', i.e. a newline character; thus, normally each
  2908. `print' statement makes a separate line.
  2909.    You can change how output fields and records are separated by
  2910. assigning new values to the variables `OFS' and/or `ORS'.  The usual
  2911. place to do this is in the `BEGIN' rule (*note The `BEGIN' and `END'
  2912. Special Patterns: BEGIN/END.), so that it happens before any input is
  2913. processed.  You may also do this with assignments on the command line,
  2914. before the names of your input files, or using the `-v' command line
  2915. option (*note Command Line Options: Options.).
  2916.    The following example prints the first and second fields of each
  2917. input record separated by a semicolon, with a blank line added after
  2918. each line:
  2919.      $ awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
  2920.      >            { print $1, $2 }' BBS-list
  2921.      -| aardvark;555-5553
  2922.      -|
  2923.      -| alpo-net;555-3412
  2924.      -|
  2925.      -| barfly;555-7685
  2926.      ...
  2927.    If the value of `ORS' does not contain a newline, all your output
  2928. will be run together on a single line, unless you output newlines some
  2929. other way.
  2930. File: gawk.info,  Node: OFMT,  Next: Printf,  Prev: Output Separators,  Up: Printing
  2931. Controlling Numeric Output with `print'
  2932. =======================================
  2933.    When you use the `print' statement to print numeric values, `awk'
  2934. internally converts the number to a string of characters, and prints
  2935. that string.  `awk' uses the `sprintf' function to do this conversion
  2936. (*note Built-in Functions for String Manipulation: String Functions.).
  2937. For now, it suffices to say that the `sprintf' function accepts a
  2938. "format specification" that tells it how to format numbers (or
  2939. strings), and that there are a number of different ways in which
  2940. numbers can be formatted.  The different format specifications are
  2941. discussed more fully in *Note Format-Control Letters: Control Letters.
  2942.    The built-in variable `OFMT' contains the default format
  2943. specification that `print' uses with `sprintf' when it wants to convert
  2944. a number to a string for printing.  The default value of `OFMT' is
  2945. `"%.6g"'.  By supplying different format specifications as the value of
  2946. `OFMT', you can change how `print' will print your numbers.  As a brief
  2947. example:
  2948.      $ awk 'BEGIN {
  2949.      >   OFMT = "%.0f"  # print numbers as integers (rounds)
  2950.      >   print 17.23 }'
  2951.      -| 17
  2952. According to the POSIX standard, `awk''s behavior will be undefined if
  2953. `OFMT' contains anything but a floating point conversion specification
  2954. (d.c.).
  2955. File: gawk.info,  Node: Printf,  Next: Redirection,  Prev: OFMT,  Up: Printing
  2956. Using `printf' Statements for Fancier Printing
  2957. ==============================================
  2958.    If you want more precise control over the output format than `print'
  2959. gives you, use `printf'.  With `printf' you can specify the width to
  2960. use for each item, and you can specify various formatting choices for
  2961. numbers (such as what radix to use, whether to print an exponent,
  2962. whether to print a sign, and how many digits to print after the decimal
  2963. point).  You do this by supplying a string, called the "format string",
  2964. which controls how and where to print the other arguments.
  2965. * Menu:
  2966. * Basic Printf::                Syntax of the `printf' statement.
  2967. * Control Letters::             Format-control letters.
  2968. * Format Modifiers::            Format-specification modifiers.
  2969. * Printf Examples::             Several examples.
  2970. File: gawk.info,  Node: Basic Printf,  Next: Control Letters,  Prev: Printf,  Up: Printf
  2971. Introduction to the `printf' Statement
  2972. --------------------------------------
  2973.    The `printf' statement looks like this:
  2974.      printf FORMAT, ITEM1, ITEM2, ...
  2975. The entire list of arguments may optionally be enclosed in parentheses.
  2976. The parentheses are necessary if any of the item expressions use the
  2977. `>' relational operator; otherwise it could be confused with a
  2978. redirection (*note Redirecting Output of `print' and `printf':
  2979. Redirection.).
  2980.    The difference between `printf' and `print' is the FORMAT argument.
  2981. This is an expression whose value is taken as a string; it specifies
  2982. how to output each of the other arguments.  It is called the "format
  2983. string".
  2984.    The format string is very similar to that in the ANSI C library
  2985. function `printf'.  Most of FORMAT is text to be output verbatim.
  2986. Scattered among this text are "format specifiers", one per item.  Each
  2987. format specifier says to output the next item in the argument list at
  2988. that place in the format.
  2989.    The `printf' statement does not automatically append a newline to its
  2990. output.  It outputs only what the format string specifies.  So if you
  2991. want a newline, you must include one in the format string.  The output
  2992. separator variables `OFS' and `ORS' have no effect on `printf'
  2993. statements. For example:
  2994.      BEGIN {
  2995.         ORS = "\nOUCH!\n"; OFS = "!"
  2996.         msg = "Don't Panic!"; printf "%s\n", msg
  2997.      }
  2998.    This program still prints the familiar `Don't Panic!' message.
  2999. File: gawk.info,  Node: Control Letters,  Next: Format Modifiers,  Prev: Basic Printf,  Up: Printf
  3000. Format-Control Letters
  3001. ----------------------
  3002.    A format specifier starts with the character `%' and ends with a
  3003. "format-control letter"; it tells the `printf' statement how to output
  3004. one item.  (If you actually want to output a `%', write `%%'.)  The
  3005. format-control letter specifies what kind of value to print.  The rest
  3006. of the format specifier is made up of optional "modifiers" which are
  3007. parameters to use, such as the field width.
  3008.    Here is a list of the format-control letters:
  3009.      This prints a number as an ASCII character.  Thus, `printf "%c",
  3010.      65' outputs the letter `A'.  The output for a string value is the
  3011.      first character of the string.
  3012.      These are equivalent. They both print a decimal integer.  The `%i'
  3013.      specification is for compatibility with ANSI C.
  3014.      This prints a number in scientific (exponential) notation.  For
  3015.      example,
  3016.           printf "%4.3e\n", 1950
  3017.      prints `1.950e+03', with a total of four significant figures of
  3018.      which three follow the decimal point.  The `4.3' are modifiers,
  3019.      discussed below. `%E' uses `E' instead of `e' in the output.
  3020.      This prints a number in floating point notation.  For example,
  3021.           printf "%4.3f", 1950
  3022.      prints `1950.000', with a total of four significant figures of
  3023.      which three follow the decimal point.  The `4.3' are modifiers,
  3024.      discussed below.
  3025.      This prints a number in either scientific notation or floating
  3026.      point notation, whichever uses fewer characters. If the result is
  3027.      printed in scientific notation, `%G' uses `E' instead of `e'.
  3028.      This prints an unsigned octal integer.  (In octal, or base-eight
  3029.      notation, the digits run from `0' to `7'; the decimal number eight
  3030.      is represented as `10' in octal.)
  3031.      This prints a string.
  3032.      This prints an unsigned hexadecimal integer.  (In hexadecimal, or
  3033.      base-16 notation, the digits are `0' through `9' and `a' through
  3034.      `f'.  The hexadecimal digit `f' represents the decimal number 15.)
  3035.      `%X' uses the letters `A' through `F' instead of `a' through `f'.
  3036.      This isn't really a format-control letter, but it does have a
  3037.      meaning when used after a `%': the sequence `%%' outputs one `%'.
  3038.      It does not consume an argument, and it ignores any modifiers.
  3039.    When using the integer format-control letters for values that are
  3040. outside the range of a C `long' integer, `gawk' will switch to the `%g'
  3041. format specifier. Other versions of `awk' may print invalid values, or
  3042. do something else entirely (d.c.).
  3043. File: gawk.info,  Node: Format Modifiers,  Next: Printf Examples,  Prev: Control Letters,  Up: Printf
  3044. Modifiers for `printf' Formats
  3045. ------------------------------
  3046.    A format specification can also include "modifiers" that can control
  3047. how much of the item's value is printed and how much space it gets.  The
  3048. modifiers come between the `%' and the format-control letter.  In the
  3049. examples below, we use the bullet symbol "*" to represent spaces in the
  3050. output. Here are the possible modifiers, in the order in which they may
  3051. appear:
  3052.      The minus sign, used before the width modifier (see below), says
  3053.      to left-justify the argument within its specified width.  Normally
  3054.      the argument is printed right-justified in the specified width.
  3055.      Thus,
  3056.           printf "%-4s", "foo"
  3057.      prints `foo*'.
  3058. `SPACE'
  3059.      For numeric conversions, prefix positive values with a space, and
  3060.      negative values with a minus sign.
  3061.      The plus sign, used before the width modifier (see below), says to
  3062.      always supply a sign for numeric conversions, even if the data to
  3063.      be formatted is positive. The `+' overrides the space modifier.
  3064.      Use an "alternate form" for certain control letters.  For `%o',
  3065.      supply a leading zero.  For `%x', and `%X', supply a leading `0x'
  3066.      or `0X' for a non-zero result.  For `%e', `%E', and `%f', the
  3067.      result will always contain a decimal point.  For `%g', and `%G',
  3068.      trailing zeros are not removed from the result.
  3069.      A leading `0' (zero) acts as a flag, that indicates output should
  3070.      be padded with zeros instead of spaces.  This applies even to
  3071.      non-numeric output formats (d.c.).  This flag only has an effect
  3072.      when the field width is wider than the value to be printed.
  3073. `WIDTH'
  3074.      This is a number specifying the desired minimum width of a field.
  3075.      Inserting any number between the `%' sign and the format control
  3076.      character forces the field to be expanded to this width.  The
  3077.      default way to do this is to pad with spaces on the left.  For
  3078.      example,
  3079.           printf "%4s", "foo"
  3080.      prints `*foo'.
  3081.      The value of WIDTH is a minimum width, not a maximum.  If the item
  3082.      value requires more than WIDTH characters, it can be as wide as
  3083.      necessary.  Thus,
  3084.           printf "%4s", "foobar"
  3085.      prints `foobar'.
  3086.      Preceding the WIDTH with a minus sign causes the output to be
  3087.      padded with spaces on the right, instead of on the left.
  3088. `.PREC'
  3089.      This is a number that specifies the precision to use when printing.
  3090.      For the `e', `E', and `f' formats, this specifies the number of
  3091.      digits you want printed to the right of the decimal point.  For
  3092.      the `g', and `G' formats, it specifies the maximum number of
  3093.      significant digits.  For the `d', `o', `i', `u', `x', and `X'
  3094.      formats, it specifies the minimum number of digits to print.  For
  3095.      a string, it specifies the maximum number of characters from the
  3096.      string that should be printed.  Thus,
  3097.           printf "%.4s", "foobar"
  3098.      prints `foob'.
  3099.    The C library `printf''s dynamic WIDTH and PREC capability (for
  3100. example, `"%*.*s"') is supported.  Instead of supplying explicit WIDTH
  3101. and/or PREC values in the format string, you pass them in the argument
  3102. list.  For example:
  3103.      w = 5
  3104.      p = 3
  3105.      s = "abcdefg"
  3106.      printf "%*.*s\n", w, p, s
  3107. is exactly equivalent to
  3108.      s = "abcdefg"
  3109.      printf "%5.3s\n", s
  3110. Both programs output `**abc'.
  3111.    Earlier versions of `awk' did not support this capability.  If you
  3112. must use such a version, you may simulate this feature by using
  3113. concatenation to build up the format string, like so:
  3114.      w = 5
  3115.      p = 3
  3116.      s = "abcdefg"
  3117.      printf "%" w "." p "s\n", s
  3118. This is not particularly easy to read, but it does work.
  3119.    C programmers may be used to supplying additional `l' and `h' flags
  3120. in `printf' format strings. These are not valid in `awk'.  Most `awk'
  3121. implementations silently ignore these flags.  If `--lint' is provided
  3122. on the command line (*note Command Line Options: Options.), `gawk' will
  3123. warn about their use. If `--posix' is supplied, their use is a fatal
  3124. error.
  3125. File: gawk.info,  Node: Printf Examples,  Prev: Format Modifiers,  Up: Printf
  3126. Examples Using `printf'
  3127. -----------------------
  3128.    Here is how to use `printf' to make an aligned table:
  3129.      awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
  3130. prints the names of bulletin boards (`$1') of the file `BBS-list' as a
  3131. string of 10 characters, left justified.  It also prints the phone
  3132. numbers (`$2') afterward on the line.  This produces an aligned
  3133. two-column table of names and phone numbers:
  3134.      $ awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
  3135.      -| aardvark   555-5553
  3136.      -| alpo-net   555-3412
  3137.      -| barfly     555-7685
  3138.      -| bites      555-1675
  3139.      -| camelot    555-0542
  3140.      -| core       555-2912
  3141.      -| fooey      555-1234
  3142.      -| foot       555-6699
  3143.      -| macfoo     555-6480
  3144.      -| sdace      555-3430
  3145.      -| sabafoo    555-2127
  3146.    Did you notice that we did not specify that the phone numbers be
  3147. printed as numbers?  They had to be printed as strings because the
  3148. numbers are separated by a dash.  If we had tried to print the phone
  3149. numbers as numbers, all we would have gotten would have been the first
  3150. three digits, `555'.  This would have been pretty confusing.
  3151.    We did not specify a width for the phone numbers because they are the
  3152. last things on their lines.  We don't need to put spaces after them.
  3153.    We could make our table look even nicer by adding headings to the
  3154. tops of the columns.  To do this, we use the `BEGIN' pattern (*note The
  3155. `BEGIN' and `END' Special Patterns: BEGIN/END.) to force the header to
  3156. be printed only once, at the beginning of the `awk' program:
  3157.      awk 'BEGIN { print "Name      Number"
  3158.                   print "----      ------" }
  3159.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  3160.    Did you notice that we mixed `print' and `printf' statements in the
  3161. above example?  We could have used just `printf' statements to get the
  3162. same results:
  3163.      awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
  3164.                   printf "%-10s %s\n", "----", "------" }
  3165.           { printf "%-10s %s\n", $1, $2 }' BBS-list
  3166. By printing each column heading with the same format specification used
  3167. for the elements of the column, we have made sure that the headings are
  3168. aligned just like the columns.
  3169.    The fact that the same format specification is used three times can
  3170. be emphasized by storing it in a variable, like this:
  3171.      awk 'BEGIN { format = "%-10s %s\n"
  3172.                   printf format, "Name", "Number"
  3173.                   printf format, "----", "------" }
  3174.           { printf format, $1, $2 }' BBS-list
  3175.    See if you can use the `printf' statement to line up the headings and
  3176. table data for our `inventory-shipped' example covered earlier in the
  3177. section on the `print' statement (*note The `print' Statement: Print.).
  3178. File: gawk.info,  Node: Redirection,  Next: Special Files,  Prev: Printf,  Up: Printing
  3179. Redirecting Output of `print' and `printf'
  3180. ==========================================
  3181.    So far we have been dealing only with output that prints to the
  3182. standard output, usually your terminal.  Both `print' and `printf' can
  3183. also send their output to other places.  This is called "redirection".
  3184.    A redirection appears after the `print' or `printf' statement.
  3185. Redirections in `awk' are written just like redirections in shell
  3186. commands, except that they are written inside the `awk' program.
  3187.    There are three forms of output redirection: output to a file,
  3188. output appended to a file, and output through a pipe to another command.
  3189. They are all shown for the `print' statement, but they work identically
  3190. for `printf' also.
  3191. `print ITEMS > OUTPUT-FILE'
  3192.      This type of redirection prints the items into the output file
  3193.      OUTPUT-FILE.  The file name OUTPUT-FILE can be any expression.
  3194.      Its value is changed to a string and then used as a file name
  3195.      (*note Expressions::.).
  3196.      When this type of redirection is used, the OUTPUT-FILE is erased
  3197.      before the first output is written to it.  Subsequent writes to
  3198.      the same OUTPUT-FILE do not erase OUTPUT-FILE, but append to it.
  3199.      If OUTPUT-FILE does not exist, then it is created.
  3200.      For example, here is how an `awk' program can write a list of BBS
  3201.      names to a file `name-list' and a list of phone numbers to a file
  3202.      `phone-list'.  Each output file contains one name or number per
  3203.      line.
  3204.           $ awk '{ print $2 > "phone-list"
  3205.           >        print $1 > "name-list" }' BBS-list
  3206.           $ cat phone-list
  3207.           -| 555-5553
  3208.           -| 555-3412
  3209.           ...
  3210.           $ cat name-list
  3211.           -| aardvark
  3212.           -| alpo-net
  3213.           ...
  3214. `print ITEMS >> OUTPUT-FILE'
  3215.      This type of redirection prints the items into the pre-existing
  3216.      output file OUTPUT-FILE.  The difference between this and the
  3217.      single-`>' redirection is that the old contents (if any) of
  3218.      OUTPUT-FILE are not erased.  Instead, the `awk' output is appended
  3219.      to the file.  If OUTPUT-FILE does not exist, then it is created.
  3220. `print ITEMS | COMMAND'
  3221.      It is also possible to send output to another program through a
  3222.      pipe instead of into a file.   This type of redirection opens a
  3223.      pipe to COMMAND and writes the values of ITEMS through this pipe,
  3224.      to another process created to execute COMMAND.
  3225.      The redirection argument COMMAND is actually an `awk' expression.
  3226.      Its value is converted to a string, whose contents give the shell
  3227.      command to be run.
  3228.      For example, this produces two files, one unsorted list of BBS
  3229.      names and one list sorted in reverse alphabetical order:
  3230.           awk '{ print $1 > "names.unsorted"
  3231.                  command = "sort -r > names.sorted"
  3232.                  print $1 | command }' BBS-list
  3233.      Here the unsorted list is written with an ordinary redirection
  3234.      while the sorted list is written by piping through the `sort'
  3235.      utility.
  3236.      This example uses redirection to mail a message to a mailing list
  3237.      `bug-system'.  This might be useful when trouble is encountered in
  3238.      an `awk' script run periodically for system maintenance.
  3239.           report = "mail bug-system"
  3240.           print "Awk script failed:", $0 | report
  3241.           m = ("at record number " FNR " of " FILENAME)
  3242.           print m | report
  3243.           close(report)
  3244.      The message is built using string concatenation and saved in the
  3245.      variable `m'.  It is then sent down the pipeline to the `mail'
  3246.      program.
  3247.      We call the `close' function here because it's a good idea to close
  3248.      the pipe as soon as all the intended output has been sent to it.
  3249.      *Note Closing Input and Output Files and Pipes: Close Files And
  3250.      Pipes, for more information on this.  This example also
  3251.      illustrates the use of a variable to represent a FILE or COMMAND:
  3252.      it is not necessary to always use a string constant.  Using a
  3253.      variable is generally a good idea, since `awk' requires you to
  3254.      spell the string value identically every time.
  3255.    Redirecting output using `>', `>>', or `|' asks the system to open a
  3256. file or pipe only if the particular FILE or COMMAND you've specified
  3257. has not already been written to by your program, or if it has been
  3258. closed since it was last written to.
  3259.    Many `awk' implementations limit the number of pipelines an `awk'
  3260. program may have open to just one!  In `gawk', there is no such limit.
  3261. You can open as many pipelines as the underlying operating system will
  3262. permit.
  3263. File: gawk.info,  Node: Special Files,  Next: Close Files And Pipes,  Prev: Redirection,  Up: Printing
  3264. Special File Names in `gawk'
  3265. ============================
  3266.    Running programs conventionally have three input and output streams
  3267. already available to them for reading and writing.  These are known as
  3268. the "standard input", "standard output", and "standard error output".
  3269. These streams are, by default, connected to your terminal, but they are
  3270. often redirected with the shell, via the `<', `<<', `>', `>>', `>&' and
  3271. `|' operators.  Standard error is typically used for writing error
  3272. messages; the reason we have two separate streams, standard output and
  3273. standard error, is so that they can be redirected separately.
  3274.    In other implementations of `awk', the only way to write an error
  3275. message to standard error in an `awk' program is as follows:
  3276.      print "Serious error detected!" | "cat 1>&2"
  3277. This works by opening a pipeline to a shell command which can access the
  3278. standard error stream which it inherits from the `awk' process.  This
  3279. is far from elegant, and is also inefficient, since it requires a
  3280. separate process.  So people writing `awk' programs often neglect to do
  3281. this.  Instead, they send the error messages to the terminal, like this:
  3282.      print "Serious error detected!" > "/dev/tty"
  3283. This usually has the same effect, but not always: although the standard
  3284. error stream is usually the terminal, it can be redirected, and when
  3285. that happens, writing to the terminal is not correct.  In fact, if
  3286. `awk' is run from a background job, it may not have a terminal at all.
  3287. Then opening `/dev/tty' will fail.
  3288.    `gawk' provides special file names for accessing the three standard
  3289. streams.  When you redirect input or output in `gawk', if the file name
  3290. matches one of these special names, then `gawk' directly uses the
  3291. stream it stands for.
  3292. `/dev/stdin'
  3293.      The standard input (file descriptor 0).
  3294. `/dev/stdout'
  3295.      The standard output (file descriptor 1).
  3296. `/dev/stderr'
  3297.      The standard error output (file descriptor 2).
  3298. `/dev/fd/N'
  3299.      The file associated with file descriptor N.  Such a file must have
  3300.      been opened by the program initiating the `awk' execution
  3301.      (typically the shell).  Unless you take special pains in the shell
  3302.      from which you invoke `gawk', only descriptors 0, 1 and 2 are
  3303.      available.
  3304.    The file names `/dev/stdin', `/dev/stdout', and `/dev/stderr' are
  3305. aliases for `/dev/fd/0', `/dev/fd/1', and `/dev/fd/2', respectively,
  3306. but they are more self-explanatory.
  3307.    The proper way to write an error message in a `gawk' program is to
  3308. use `/dev/stderr', like this:
  3309.      print "Serious error detected!" > "/dev/stderr"
  3310.    `gawk' also provides special file names that give access to
  3311. information about the running `gawk' process.  Each of these "files"
  3312. provides a single record of information.  To read them more than once,
  3313. you must first close them with the `close' function (*note Closing
  3314. Input and Output Files and Pipes: Close Files And Pipes.).  The
  3315. filenames are:
  3316. `/dev/pid'
  3317.      Reading this file returns the process ID of the current process,
  3318.      in decimal, terminated with a newline.
  3319. `/dev/ppid'
  3320.      Reading this file returns the parent process ID of the current
  3321.      process, in decimal, terminated with a newline.
  3322. `/dev/pgrpid'
  3323.      Reading this file returns the process group ID of the current
  3324.      process, in decimal, terminated with a newline.
  3325. `/dev/user'
  3326.      Reading this file returns a single record terminated with a
  3327.      newline.  The fields are separated with spaces.  The fields
  3328.      represent the following information:
  3329.     `$1'
  3330.           The return value of the `getuid' system call (the real user
  3331.           ID number).
  3332.     `$2'
  3333.           The return value of the `geteuid' system call (the effective
  3334.           user ID number).
  3335.     `$3'
  3336.           The return value of the `getgid' system call (the real group
  3337.           ID number).
  3338.     `$4'
  3339.           The return value of the `getegid' system call (the effective
  3340.           group ID number).
  3341.      If there are any additional fields, they are the group IDs
  3342.      returned by `getgroups' system call.  (Multiple groups may not be
  3343.      supported on all systems.)
  3344.    These special file names may be used on the command line as data
  3345. files, as well as for I/O redirections within an `awk' program.  They
  3346. may not be used as source files with the `-f' option.
  3347.    Recognition of these special file names is disabled if `gawk' is in
  3348. compatibility mode (*note Command Line Options: Options.).
  3349.    *Caution*:  Unless your system actually has a `/dev/fd' directory
  3350. (or any of the other above listed special files), the interpretation of
  3351. these file names is done by `gawk' itself.  For example, using
  3352. `/dev/fd/4' for output will actually write on file descriptor 4, and
  3353. not on a new file descriptor that was `dup''ed from file descriptor 4.
  3354. Most of the time this does not matter; however, it is important to
  3355. *not* close any of the files related to file descriptors 0, 1, and 2.
  3356. If you do close one of these files, unpredictable behavior will result.
  3357.    The special files that provide process-related information may
  3358. disappear in a future version of `gawk'.  *Note Probable Future
  3359. Extensions: Future Extensions.
  3360. File: gawk.info,  Node: Close Files And Pipes,  Prev: Special Files,  Up: Printing
  3361. Closing Input and Output Files and Pipes
  3362. ========================================
  3363.    If the same file name or the same shell command is used with
  3364. `getline' (*note Explicit Input with `getline': Getline.) more than
  3365. once during the execution of an `awk' program, the file is opened (or
  3366. the command is executed) only the first time.  At that time, the first
  3367. record of input is read from that file or command.  The next time the
  3368. same file or command is used in `getline', another record is read from
  3369. it, and so on.
  3370.    Similarly, when a file or pipe is opened for output, the file name
  3371. or command associated with it is remembered by `awk' and subsequent
  3372. writes to the same file or command are appended to the previous writes.
  3373. The file or pipe stays open until `awk' exits.
  3374.    This implies that if you want to start reading the same file again
  3375. from the beginning, or if you want to rerun a shell command (rather than
  3376. reading more output from the command), you must take special steps.
  3377. What you must do is use the `close' function, as follows:
  3378.      close(FILENAME)
  3379.      close(COMMAND)
  3380.    The argument FILENAME or COMMAND can be any expression.  Its value
  3381. must *exactly* match the string that was used to open the file or start
  3382. the command (spaces and other "irrelevant" characters included). For
  3383. example, if you open a pipe with this:
  3384.      "sort -r names" | getline foo
  3385. then you must close it with this:
  3386.      close("sort -r names")
  3387.    Once this function call is executed, the next `getline' from that
  3388. file or command, or the next `print' or `printf' to that file or
  3389. command, will reopen the file or rerun the command.
  3390.    Because the expression that you use to close a file or pipeline must
  3391. exactly match the expression used to open the file or run the command,
  3392. it is good practice to use a variable to store the file name or command.
  3393. The previous example would become
  3394.      sortcom = "sort -r names"
  3395.      sortcom | getline foo
  3396.      ...
  3397.      close(sortcom)
  3398. This helps avoid hard-to-find typographical errors in your `awk'
  3399. programs.
  3400.    Here are some reasons why you might need to close an output file:
  3401.    * To write a file and read it back later on in the same `awk'
  3402.      program.  Close the file when you are finished writing it; then
  3403.      you can start reading it with `getline'.
  3404.    * To write numerous files, successively, in the same `awk' program.
  3405.      If you don't close the files, eventually you may exceed a system
  3406.      limit on the number of open files in one process.  So close each
  3407.      one when you are finished writing it.
  3408.    * To make a command finish.  When you redirect output through a pipe,
  3409.      the command reading the pipe normally continues to try to read
  3410.      input as long as the pipe is open.  Often this means the command
  3411.      cannot really do its work until the pipe is closed.  For example,
  3412.      if you redirect output to the `mail' program, the message is not
  3413.      actually sent until the pipe is closed.
  3414.    * To run the same program a second time, with the same arguments.
  3415.      This is not the same thing as giving more input to the first run!
  3416.      For example, suppose you pipe output to the `mail' program.  If you
  3417.      output several lines redirected to this pipe without closing it,
  3418.      they make a single message of several lines.  By contrast, if you
  3419.      close the pipe after each line of output, then each line makes a
  3420.      separate message.
  3421.    `close' returns a value of zero if the close succeeded.  Otherwise,
  3422. the value will be non-zero.  In this case, `gawk' sets the variable
  3423. `ERRNO' to a string describing the error that occurred.
  3424.    If you use more files than the system allows you to have open,
  3425. `gawk' will attempt to multiplex the available open files among your
  3426. data files.  `gawk''s ability to do this depends upon the facilities of
  3427. your operating system: it may not always work.  It is therefore both
  3428. good practice and good portability advice to always use `close' on your
  3429. files when you are done with them.
  3430. File: gawk.info,  Node: Expressions,  Next: Patterns and Actions,  Prev: Printing,  Up: Top
  3431. Expressions
  3432. ***********
  3433.    Expressions are the basic building blocks of `awk' patterns and
  3434. actions.  An expression evaluates to a value, which you can print, test,
  3435. store in a variable or pass to a function.  Additionally, an expression
  3436. can assign a new value to a variable or a field, with an assignment
  3437. operator.
  3438.    An expression can serve as a pattern or action statement on its own.
  3439. Most other kinds of statements contain one or more expressions which
  3440. specify data on which to operate.  As in other languages, expressions
  3441. in `awk' include variables, array references, constants, and function
  3442. calls, as well as combinations of these with various operators.
  3443. * Menu:
  3444. * Constants::                   String, numeric, and regexp constants.
  3445. * Using Constant Regexps::      When and how to use a regexp constant.
  3446. * Variables::                   Variables give names to values for later use.
  3447. * Conversion::                  The conversion of strings to numbers and vice
  3448.                                 versa.
  3449. * Arithmetic Ops::              Arithmetic operations (`+', `-',
  3450.                                 etc.)
  3451. * Concatenation::               Concatenating strings.
  3452. * Assignment Ops::              Changing the value of a variable or a field.
  3453. * Increment Ops::               Incrementing the numeric value of a variable.
  3454. * Truth Values::                What is "true" and what is "false".
  3455. * Typing and Comparison::       How variables acquire types, and how this
  3456.                                 affects comparison of numbers and strings with
  3457.                                 `<', etc.
  3458. * Boolean Ops::                 Combining comparison expressions using boolean
  3459.                                 operators `||' ("or"), `&&'
  3460.                                 ("and") and `!' ("not").
  3461. * Conditional Exp::             Conditional expressions select between two
  3462.                                 subexpressions under control of a third
  3463.                                 subexpression.
  3464. * Function Calls::              A function call is an expression.
  3465. * Precedence::                  How various operators nest.
  3466. File: gawk.info,  Node: Constants,  Next: Using Constant Regexps,  Prev: Expressions,  Up: Expressions
  3467. Constant Expressions
  3468. ====================
  3469.    The simplest type of expression is the "constant", which always has
  3470. the same value.  There are three types of constants: numeric constants,
  3471. string constants, and regular expression constants.
  3472. * Menu:
  3473. * Scalar Constants::            Numeric and string constants.
  3474. * Regexp Constants::            Regular Expression constants.
  3475. File: gawk.info,  Node: Scalar Constants,  Next: Regexp Constants,  Prev: Constants,  Up: Constants
  3476. Numeric and String Constants
  3477. ----------------------------
  3478.    A "numeric constant" stands for a number.  This number can be an
  3479. integer, a decimal fraction, or a number in scientific (exponential)
  3480. notation.(1) Here are some examples of numeric constants, which all
  3481. have the same value:
  3482.      105
  3483.      1.05e+2
  3484.      1050e-1
  3485.    A string constant consists of a sequence of characters enclosed in
  3486. double-quote marks.  For example:
  3487.      "parrot"
  3488. represents the string whose contents are `parrot'.  Strings in `gawk'
  3489. can be of any length and they can contain any of the possible eight-bit
  3490. ASCII characters including ASCII NUL (character code zero).  Other `awk'
  3491. implementations may have difficulty with some character codes.
  3492.    ---------- Footnotes ----------
  3493.    (1)  The internal representation uses double-precision floating
  3494. point numbers. If you don't know what that means, then don't worry
  3495. about it.
  3496. File: gawk.info,  Node: Regexp Constants,  Prev: Scalar Constants,  Up: Constants
  3497. Regular Expression Constants
  3498. ----------------------------
  3499.    A regexp constant is a regular expression description enclosed in
  3500. slashes, such as `/^beginning and end$/'.  Most regexps used in `awk'
  3501. programs are constant, but the `~' and `!~' matching operators can also
  3502. match computed or "dynamic" regexps (which are just ordinary strings or
  3503. variables that contain a regexp).
  3504. File: gawk.info,  Node: Using Constant Regexps,  Next: Variables,  Prev: Constants,  Up: Expressions
  3505. Using Regular Expression Constants
  3506. ==================================
  3507.    When used on the right hand side of the `~' or `!~' operators, a
  3508. regexp constant merely stands for the regexp that is to be matched.
  3509.    Regexp constants (such as `/foo/') may be used like simple
  3510. expressions.  When a regexp constant appears by itself, it has the same
  3511. meaning as if it appeared in a pattern, i.e. `($0 ~ /foo/)' (d.c.)
  3512. (*note Expressions as Patterns: Expression Patterns.).  This means that
  3513. the two code segments,
  3514.      if ($0 ~ /barfly/ || $0 ~ /camelot/)
  3515.          print "found"
  3516.      if (/barfly/ || /camelot/)
  3517.          print "found"
  3518. are exactly equivalent.
  3519.    One rather bizarre consequence of this rule is that the following
  3520. boolean expression is valid, but does not do what the user probably
  3521. intended:
  3522.      # note that /foo/ is on the left of the ~
  3523.      if (/foo/ ~ $1) print "found foo"
  3524. This code is "obviously" testing `$1' for a match against the regexp
  3525. `/foo/'.  But in fact, the expression `/foo/ ~ $1' actually means `($0
  3526. ~ /foo/) ~ $1'.  In other words, first match the input record against
  3527. the regexp `/foo/'.  The result will be either zero or one, depending
  3528. upon the success or failure of the match.  Then match that result
  3529. against the first field in the record.
  3530.    Since it is unlikely that you would ever really wish to make this
  3531. kind of test, `gawk' will issue a warning when it sees this construct in
  3532. a program.
  3533.    Another consequence of this rule is that the assignment statement
  3534.      matches = /foo/
  3535. will assign either zero or one to the variable `matches', depending
  3536. upon the contents of the current input record.
  3537.    This feature of the language was never well documented until the
  3538. POSIX specification.
  3539.    Constant regular expressions are also used as the first argument for
  3540. the `gensub', `sub' and `gsub' functions, and as the second argument of
  3541. the `match' function (*note Built-in Functions for String Manipulation:
  3542. String Functions.).  Modern implementations of `awk', including `gawk',
  3543. allow the third argument of `split' to be a regexp constant, while some
  3544. older implementations do not (d.c.).
  3545.    This can lead to confusion when attempting to use regexp constants
  3546. as arguments to user defined functions (*note User-defined Functions:
  3547. User-defined.).  For example:
  3548.      function mysub(pat, repl, str, global)
  3549.      {
  3550.          if (global)
  3551.              gsub(pat, repl, str)
  3552.          else
  3553.              sub(pat, repl, str)
  3554.          return str
  3555.      }
  3556.      
  3557.      {
  3558.          ...
  3559.          text = "hi! hi yourself!"
  3560.          mysub(/hi/, "howdy", text, 1)
  3561.          ...
  3562.      }
  3563.    In this example, the programmer wishes to pass a regexp constant to
  3564. the user-defined function `mysub', which will in turn pass it on to
  3565. either `sub' or `gsub'.  However, what really happens is that the `pat'
  3566. parameter will be either one or zero, depending upon whether or not
  3567. `$0' matches `/hi/'.
  3568.    As it is unlikely that you would ever really wish to pass a truth
  3569. value in this way, `gawk' will issue a warning when it sees a regexp
  3570. constant used as a parameter to a user-defined function.
  3571. File: gawk.info,  Node: Variables,  Next: Conversion,  Prev: Using Constant Regexps,  Up: Expressions
  3572. Variables
  3573. =========
  3574.    Variables are ways of storing values at one point in your program for
  3575. use later in another part of your program.  You can manipulate them
  3576. entirely within your program text, and you can also assign values to
  3577. them on the `awk' command line.
  3578. * Menu:
  3579. * Using Variables::             Using variables in your programs.
  3580. * Assignment Options::          Setting variables on the command line and a
  3581.                                 summary of command line syntax. This is an
  3582.                                 advanced method of input.
  3583. File: gawk.info,  Node: Using Variables,  Next: Assignment Options,  Prev: Variables,  Up: Variables
  3584. Using Variables in a Program
  3585. ----------------------------
  3586.    Variables let you give names to values and refer to them later.  You
  3587. have already seen variables in many of the examples.  The name of a
  3588. variable must be a sequence of letters, digits and underscores, but it
  3589. may not begin with a digit.  Case is significant in variable names; `a'
  3590. and `A' are distinct variables.
  3591.    A variable name is a valid expression by itself; it represents the
  3592. variable's current value.  Variables are given new values with
  3593. "assignment operators", "increment operators" and "decrement operators".
  3594. *Note Assignment Expressions: Assignment Ops.
  3595.    A few variables have special built-in meanings, such as `FS', the
  3596. field separator, and `NF', the number of fields in the current input
  3597. record.  *Note Built-in Variables::, for a list of them.  These
  3598. built-in variables can be used and assigned just like all other
  3599. variables, but their values are also used or changed automatically by
  3600. `awk'.  All built-in variables names are entirely upper-case.
  3601.    Variables in `awk' can be assigned either numeric or string values.
  3602. By default, variables are initialized to the empty string, which is
  3603. zero if converted to a number.  There is no need to "initialize" each
  3604. variable explicitly in `awk', the way you would in C and in most other
  3605. traditional languages.
  3606. File: gawk.info,  Node: Assignment Options,  Prev: Using Variables,  Up: Variables
  3607. Assigning Variables on the Command Line
  3608. ---------------------------------------
  3609.    You can set any `awk' variable by including a "variable assignment"
  3610. among the arguments on the command line when you invoke `awk' (*note
  3611. Other Command Line Arguments: Other Arguments.).  Such an assignment has
  3612. this form:
  3613.      VARIABLE=TEXT
  3614. With it, you can set a variable either at the beginning of the `awk'
  3615. run or in between input files.
  3616.    If you precede the assignment with the `-v' option, like this:
  3617.      -v VARIABLE=TEXT
  3618. then the variable is set at the very beginning, before even the `BEGIN'
  3619. rules are run.  The `-v' option and its assignment must precede all the
  3620. file name arguments, as well as the program text.  (*Note Command Line
  3621. Options: Options, for more information about the `-v' option.)
  3622.    Otherwise, the variable assignment is performed at a time determined
  3623. by its position among the input file arguments: after the processing of
  3624. the preceding input file argument.  For example:
  3625.      awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
  3626. prints the value of field number `n' for all input records.  Before the
  3627. first file is read, the command line sets the variable `n' equal to
  3628. four.  This causes the fourth field to be printed in lines from the
  3629. file `inventory-shipped'.  After the first file has finished, but
  3630. before the second file is started, `n' is set to two, so that the
  3631. second field is printed in lines from `BBS-list'.
  3632.      $ awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
  3633.      -| 15
  3634.      -| 24
  3635.      ...
  3636.      -| 555-5553
  3637.      -| 555-3412
  3638.      ...
  3639.    Command line arguments are made available for explicit examination by
  3640. the `awk' program in an array named `ARGV' (*note Using `ARGC' and
  3641. `ARGV': ARGC and ARGV.).
  3642.    `awk' processes the values of command line assignments for escape
  3643. sequences (d.c.) (*note Escape Sequences::.).
  3644. File: gawk.info,  Node: Conversion,  Next: Arithmetic Ops,  Prev: Variables,  Up: Expressions
  3645. Conversion of Strings and Numbers
  3646. =================================
  3647.    Strings are converted to numbers, and numbers to strings, if the
  3648. context of the `awk' program demands it.  For example, if the value of
  3649. either `foo' or `bar' in the expression `foo + bar' happens to be a
  3650. string, it is converted to a number before the addition is performed.
  3651. If numeric values appear in string concatenation, they are converted to
  3652. strings.  Consider this:
  3653.      two = 2; three = 3
  3654.      print (two three) + 4
  3655. This prints the (numeric) value 27.  The numeric values of the
  3656. variables `two' and `three' are converted to strings and concatenated
  3657. together, and the resulting string is converted back to the number 23,
  3658. to which four is then added.
  3659.    If, for some reason, you need to force a number to be converted to a
  3660. string, concatenate the empty string, `""', with that number.  To force
  3661. a string to be converted to a number, add zero to that string.
  3662.    A string is converted to a number by interpreting any numeric prefix
  3663. of the string as numerals: `"2.5"' converts to 2.5, `"1e3"' converts to
  3664. 1000, and `"25fix"' has a numeric value of 25.  Strings that can't be
  3665. interpreted as valid numbers are converted to zero.
  3666.    The exact manner in which numbers are converted into strings is
  3667. controlled by the `awk' built-in variable `CONVFMT' (*note Built-in
  3668. Variables::.).  Numbers are converted using the `sprintf' function
  3669. (*note Built-in Functions for String Manipulation: String Functions.)
  3670. with `CONVFMT' as the format specifier.
  3671.    `CONVFMT''s default value is `"%.6g"', which prints a value with at
  3672. least six significant digits.  For some applications you will want to
  3673. change it to specify more precision.  Double precision on most modern
  3674. machines gives you 16 or 17 decimal digits of precision.
  3675.    Strange results can happen if you set `CONVFMT' to a string that
  3676. doesn't tell `sprintf' how to format floating point numbers in a useful
  3677. way.  For example, if you forget the `%' in the format, all numbers
  3678. will be converted to the same constant string.
  3679.    As a special case, if a number is an integer, then the result of
  3680. converting it to a string is *always* an integer, no matter what the
  3681. value of `CONVFMT' may be.  Given the following code fragment:
  3682.      CONVFMT = "%2.2f"
  3683.      a = 12
  3684.      b = a ""
  3685. `b' has the value `"12"', not `"12.00"' (d.c.).
  3686.    Prior to the POSIX standard, `awk' specified that the value of
  3687. `OFMT' was used for converting numbers to strings.  `OFMT' specifies
  3688. the output format to use when printing numbers with `print'.  `CONVFMT'
  3689. was introduced in order to separate the semantics of conversion from
  3690. the semantics of printing.  Both `CONVFMT' and `OFMT' have the same
  3691. default value: `"%.6g"'.  In the vast majority of cases, old `awk'
  3692. programs will not change their behavior.  However, this use of `OFMT'
  3693. is something to keep in mind if you must port your program to other
  3694. implementations of `awk'; we recommend that instead of changing your
  3695. programs, you just port `gawk' itself!  *Note The `print' Statement:
  3696. Print, for more information on the `print' statement.
  3697. File: gawk.info,  Node: Arithmetic Ops,  Next: Concatenation,  Prev: Conversion,  Up: Expressions
  3698. Arithmetic Operators
  3699. ====================
  3700.    The `awk' language uses the common arithmetic operators when
  3701. evaluating expressions.  All of these arithmetic operators follow normal
  3702. precedence rules, and work as you would expect them to.
  3703.    Here is a file `grades' containing a list of student names and three
  3704. test scores per student (it's a small class):
  3705.      Pat   100 97 58
  3706.      Sandy  84 72 93
  3707.      Chris  72 92 89
  3708. This programs takes the file `grades', and prints the average of the
  3709. scores.
  3710.      $ awk '{ sum = $2 + $3 + $4 ; avg = sum / 3
  3711.      >        print $1, avg }' grades
  3712.      -| Pat 85
  3713.      -| Sandy 83
  3714.      -| Chris 84.3333
  3715.    This table lists the arithmetic operators in `awk', in order from
  3716. highest precedence to lowest:
  3717. `- X'
  3718.      Negation.
  3719. `+ X'
  3720.      Unary plus.  The expression is converted to a number.
  3721. `X ^ Y'
  3722. `X ** Y'
  3723.      Exponentiation: X raised to the Y power.  `2 ^ 3' has the value
  3724.      eight.  The character sequence `**' is equivalent to `^'.  (The
  3725.      POSIX standard only specifies the use of `^' for exponentiation.)
  3726. `X * Y'
  3727.      Multiplication.
  3728. `X / Y'
  3729.      Division.  Since all numbers in `awk' are real numbers, the result
  3730.      is not rounded to an integer: `3 / 4' has the value 0.75.
  3731. `X % Y'
  3732.      Remainder.  The quotient is rounded toward zero to an integer,
  3733.      multiplied by Y and this result is subtracted from X.  This
  3734.      operation is sometimes known as "trunc-mod."  The following
  3735.      relation always holds:
  3736.           b * int(a / b) + (a % b) == a
  3737.      One possibly undesirable effect of this definition of remainder is
  3738.      that `X % Y' is negative if X is negative.  Thus,
  3739.           -17 % 8 = -1
  3740.      In other `awk' implementations, the signedness of the remainder
  3741.      may be machine dependent.
  3742. `X + Y'
  3743.      Addition.
  3744. `X - Y'
  3745.      Subtraction.
  3746.    For maximum portability, do not use the `**' operator.
  3747.    Unary plus and minus have the same precedence, the multiplication
  3748. operators all have the same precedence, and addition and subtraction
  3749. have the same precedence.
  3750. File: gawk.info,  Node: Concatenation,  Next: Assignment Ops,  Prev: Arithmetic Ops,  Up: Expressions
  3751. String Concatenation
  3752. ====================
  3753.      It seemed like a good idea at the time.
  3754.      Brian Kernighan
  3755.    There is only one string operation: concatenation.  It does not have
  3756. a specific operator to represent it.  Instead, concatenation is
  3757. performed by writing expressions next to one another, with no operator.
  3758. For example:
  3759.      $ awk '{ print "Field number one: " $1 }' BBS-list
  3760.      -| Field number one: aardvark
  3761.      -| Field number one: alpo-net
  3762.      ...
  3763.    Without the space in the string constant after the `:', the line
  3764. would run together.  For example:
  3765.      $ awk '{ print "Field number one:" $1 }' BBS-list
  3766.      -| Field number one:aardvark
  3767.      -| Field number one:alpo-net
  3768.      ...
  3769.    Since string concatenation does not have an explicit operator, it is
  3770. often necessary to insure that it happens where you want it to by using
  3771. parentheses to enclose the items to be concatenated.  For example, the
  3772. following code fragment does not concatenate `file' and `name' as you
  3773. might expect:
  3774.      file = "file"
  3775.      name = "name"
  3776.      print "something meaningful" > file name
  3777. It is necessary to use the following:
  3778.      print "something meaningful" > (file name)
  3779.    We recommend that you use parentheses around concatenation in all
  3780. but the most common contexts (such as on the right-hand side of `=').
  3781. File: gawk.info,  Node: Assignment Ops,  Next: Increment Ops,  Prev: Concatenation,  Up: Expressions
  3782. Assignment Expressions
  3783. ======================
  3784.    An "assignment" is an expression that stores a new value into a
  3785. variable.  For example, let's assign the value one to the variable `z':
  3786.      z = 1
  3787.    After this expression is executed, the variable `z' has the value
  3788. one.  Whatever old value `z' had before the assignment is forgotten.
  3789.    Assignments can store string values also.  For example, this would
  3790. store the value `"this food is good"' in the variable `message':
  3791.      thing = "food"
  3792.      predicate = "good"
  3793.      message = "this " thing " is " predicate
  3794. (This also illustrates string concatenation.)
  3795.    The `=' sign is called an "assignment operator".  It is the simplest
  3796. assignment operator because the value of the right-hand operand is
  3797. stored unchanged.
  3798.    Most operators (addition, concatenation, and so on) have no effect
  3799. except to compute a value.  If you ignore the value, you might as well
  3800. not use the operator.  An assignment operator is different; it does
  3801. produce a value, but even if you ignore the value, the assignment still
  3802. makes itself felt through the alteration of the variable.  We call this
  3803. a "side effect".
  3804.    The left-hand operand of an assignment need not be a variable (*note
  3805. Variables::.); it can also be a field (*note Changing the Contents of a
  3806. Field: Changing Fields.) or an array element (*note Arrays in `awk':
  3807. Arrays.).  These are all called "lvalues", which means they can appear
  3808. on the left-hand side of an assignment operator.  The right-hand
  3809. operand may be any expression; it produces the new value which the
  3810. assignment stores in the specified variable, field or array element.
  3811. (Such values are called "rvalues").
  3812.    It is important to note that variables do *not* have permanent types.
  3813. The type of a variable is simply the type of whatever value it happens
  3814. to hold at the moment.  In the following program fragment, the variable
  3815. `foo' has a numeric value at first, and a string value later on:
  3816.      foo = 1
  3817.      print foo
  3818.      foo = "bar"
  3819.      print foo
  3820. When the second assignment gives `foo' a string value, the fact that it
  3821. previously had a numeric value is forgotten.
  3822.    String values that do not begin with a digit have a numeric value of
  3823. zero. After executing this code, the value of `foo' is five:
  3824.      foo = "a string"
  3825.      foo = foo + 5
  3826. (Note that using a variable as a number and then later as a string can
  3827. be confusing and is poor programming style.  The above examples
  3828. illustrate how `awk' works, *not* how you should write your own
  3829. programs!)
  3830.    An assignment is an expression, so it has a value: the same value
  3831. that is assigned.  Thus, `z = 1' as an expression has the value one.
  3832. One consequence of this is that you can write multiple assignments
  3833. together:
  3834.      x = y = z = 0
  3835. stores the value zero in all three variables.  It does this because the
  3836. value of `z = 0', which is zero, is stored into `y', and then the value
  3837. of `y = z = 0', which is zero, is stored into `x'.
  3838.    You can use an assignment anywhere an expression is called for.  For
  3839. example, it is valid to write `x != (y = 1)' to set `y' to one and then
  3840. test whether `x' equals one.  But this style tends to make programs
  3841. hard to read; except in a one-shot program, you should not use such
  3842. nesting of assignments.
  3843.    Aside from `=', there are several other assignment operators that do
  3844. arithmetic with the old value of the variable.  For example, the
  3845. operator `+=' computes a new value by adding the right-hand value to
  3846. the old value of the variable.  Thus, the following assignment adds
  3847. five to the value of `foo':
  3848.      foo += 5
  3849. This is equivalent to the following:
  3850.      foo = foo + 5
  3851. Use whichever one makes the meaning of your program clearer.
  3852.    There are situations where using `+=' (or any assignment operator)
  3853. is *not* the same as simply repeating the left-hand operand in the
  3854. right-hand expression.  For example:
  3855.      # Thanks to Pat Rankin for this example
  3856.      BEGIN  {
  3857.          foo[rand()] += 5
  3858.          for (x in foo)
  3859.             print x, foo[x]
  3860.      
  3861.          bar[rand()] = bar[rand()] + 5
  3862.          for (x in bar)
  3863.             print x, bar[x]
  3864.      }
  3865. The indices of `bar' are guaranteed to be different, because `rand'
  3866. will return different values each time it is called.  (Arrays and the
  3867. `rand' function haven't been covered yet.  *Note Arrays in `awk':
  3868. Arrays, and see *Note Numeric Built-in Functions: Numeric Functions,
  3869. for more information).  This example illustrates an important fact
  3870. about the assignment operators: the left-hand expression is only
  3871. evaluated *once*.
  3872.    It is also up to the implementation as to which expression is
  3873. evaluated first, the left-hand one or the right-hand one.  Consider
  3874. this example:
  3875.      i = 1
  3876.      a[i += 2] = i + 1
  3877. The value of `a[3]' could be either two or four.
  3878.    Here is a table of the arithmetic assignment operators.  In each
  3879. case, the right-hand operand is an expression whose value is converted
  3880. to a number.
  3881. `LVALUE += INCREMENT'
  3882.      Adds INCREMENT to the value of LVALUE to make the new value of
  3883.      LVALUE.
  3884. `LVALUE -= DECREMENT'
  3885.      Subtracts DECREMENT from the value of LVALUE.
  3886. `LVALUE *= COEFFICIENT'
  3887.      Multiplies the value of LVALUE by COEFFICIENT.
  3888. `LVALUE /= DIVISOR'
  3889.      Divides the value of LVALUE by DIVISOR.
  3890. `LVALUE %= MODULUS'
  3891.      Sets LVALUE to its remainder by MODULUS.
  3892. `LVALUE ^= POWER'
  3893. `LVALUE **= POWER'
  3894.      Raises LVALUE to the power POWER.  (Only the `^=' operator is
  3895.      specified by POSIX.)
  3896.    For maximum portability, do not use the `**=' operator.
  3897. File: gawk.info,  Node: Increment Ops,  Next: Truth Values,  Prev: Assignment Ops,  Up: Expressions
  3898. Increment and Decrement Operators
  3899. =================================
  3900.    "Increment" and "decrement operators" increase or decrease the value
  3901. of a variable by one.  You could do the same thing with an assignment
  3902. operator, so the increment operators add no power to the `awk'
  3903. language; but they are convenient abbreviations for very common
  3904. operations.
  3905.    The operator to add one is written `++'.  It can be used to increment
  3906. a variable either before or after taking its value.
  3907.    To pre-increment a variable V, write `++V'.  This adds one to the
  3908. value of V and that new value is also the value of this expression.
  3909. The assignment expression `V += 1' is completely equivalent.
  3910.    Writing the `++' after the variable specifies post-increment.  This
  3911. increments the variable value just the same; the difference is that the
  3912. value of the increment expression itself is the variable's *old* value.
  3913. Thus, if `foo' has the value four, then the expression `foo++' has the
  3914. value four, but it changes the value of `foo' to five.
  3915.    The post-increment `foo++' is nearly equivalent to writing `(foo +=
  3916. 1) - 1'.  It is not perfectly equivalent because all numbers in `awk'
  3917. are floating point: in floating point, `foo + 1 - 1' does not
  3918. necessarily equal `foo'.  But the difference is minute as long as you
  3919. stick to numbers that are fairly small (less than 10e12).
  3920.    Any lvalue can be incremented.  Fields and array elements are
  3921. incremented just like variables.  (Use `$(i++)' when you wish to do a
  3922. field reference and a variable increment at the same time.  The
  3923. parentheses are necessary because of the precedence of the field
  3924. reference operator, `$'.)
  3925.    The decrement operator `--' works just like `++' except that it
  3926. subtracts one instead of adding.  Like `++', it can be used before the
  3927. lvalue to pre-decrement or after it to post-decrement.
  3928.    Here is a summary of increment and decrement expressions.
  3929. `++LVALUE'
  3930.      This expression increments LVALUE and the new value becomes the
  3931.      value of the expression.
  3932. `LVALUE++'
  3933.      This expression increments LVALUE, but the value of the expression
  3934.      is the *old* value of LVALUE.
  3935. `--LVALUE'
  3936.      Like `++LVALUE', but instead of adding, it subtracts.  It
  3937.      decrements LVALUE and delivers the value that results.
  3938. `LVALUE--'
  3939.      Like `LVALUE++', but instead of adding, it subtracts.  It
  3940.      decrements LVALUE.  The value of the expression is the *old* value
  3941.      of LVALUE.
  3942. File: gawk.info,  Node: Truth Values,  Next: Typing and Comparison,  Prev: Increment Ops,  Up: Expressions
  3943. True and False in `awk'
  3944. =======================
  3945.    Many programming languages have a special representation for the
  3946. concepts of "true" and "false."  Such languages usually use the special
  3947. constants `true' and `false', or perhaps their upper-case equivalents.
  3948.    `awk' is different.  It borrows a very simple concept of true and
  3949. false from C.  In `awk', any non-zero numeric value, *or* any non-empty
  3950. string value is true.  Any other value (zero or the null string, `""')
  3951. is false.  The following program will print `A strange truth value'
  3952. three times:
  3953.      BEGIN {
  3954.         if (3.1415927)
  3955.             print "A strange truth value"
  3956.         if ("Four Score And Seven Years Ago")
  3957.             print "A strange truth value"
  3958.         if (j = 57)
  3959.             print "A strange truth value"
  3960.      }
  3961.    There is a surprising consequence of the "non-zero or non-null" rule:
  3962. The string constant `"0"' is actually true, since it is non-null (d.c.).
  3963. File: gawk.info,  Node: Typing and Comparison,  Next: Boolean Ops,  Prev: Truth Values,  Up: Expressions
  3964. Variable Typing and Comparison Expressions
  3965. ==========================================
  3966.      The Guide is definitive. Reality is frequently inaccurate.
  3967.      The Hitchhiker's Guide to the Galaxy
  3968.    Unlike other programming languages, `awk' variables do not have a
  3969. fixed type. Instead, they can be either a number or a string, depending
  3970. upon the value that is assigned to them.
  3971.    The 1992 POSIX standard introduced the concept of a "numeric
  3972. string", which is simply a string that looks like a number, for
  3973. example, `" +2"'.  This concept is used for determining the type of a
  3974. variable.
  3975.    The type of the variable is important, since the types of two
  3976. variables determine how they are compared.
  3977.    In `gawk', variable typing follows these rules.
  3978.   1. A numeric literal or the result of a numeric operation has the
  3979.      NUMERIC attribute.
  3980.   2. A string literal or the result of a string operation has the STRING
  3981.      attribute.
  3982.   3. Fields, `getline' input, `FILENAME', `ARGV' elements, `ENVIRON'
  3983.      elements and the elements of an array created by `split' that are
  3984.      numeric strings have the STRNUM attribute.  Otherwise, they have
  3985.      the STRING attribute.  Uninitialized variables also have the
  3986.      STRNUM attribute.
  3987.   4. Attributes propagate across assignments, but are not changed by
  3988.      any use.
  3989.    The last rule is particularly important. In the following program,
  3990. `a' has numeric type, even though it is later used in a string
  3991. operation.
  3992.      BEGIN {
  3993.               a = 12.345
  3994.               b = a " is a cute number"
  3995.               print b
  3996.      }
  3997.    When two operands are compared, either string comparison or numeric
  3998. comparison may be used, depending on the attributes of the operands,
  3999. according to the following, symmetric, matrix:
  4000.          +----------------------------------------------
  4001.          |    STRING        NUMERIC        STRNUM
  4002.      --------+----------------------------------------------
  4003.          |
  4004.      STRING    |    string        string        string
  4005.          |
  4006.      NUMERIC    |    string        numeric        numeric
  4007.          |
  4008.      STRNUM    |    string        numeric        numeric
  4009.      --------+----------------------------------------------
  4010.    The basic idea is that user input that looks numeric, and *only*
  4011. user input, should be treated as numeric, even though it is actually
  4012. made of characters, and is therefore also a string.
  4013.    "Comparison expressions" compare strings or numbers for
  4014. relationships such as equality.  They are written using "relational
  4015. operators", which are a superset of those in C.  Here is a table of
  4016. them:
  4017. `X < Y'
  4018.      True if X is less than Y.
  4019. `X <= Y'
  4020.      True if X is less than or equal to Y.
  4021. `X > Y'
  4022.      True if X is greater than Y.
  4023. `X >= Y'
  4024.      True if X is greater than or equal to Y.
  4025. `X == Y'
  4026.      True if X is equal to Y.
  4027. `X != Y'
  4028.      True if X is not equal to Y.
  4029. `X ~ Y'
  4030.      True if the string X matches the regexp denoted by Y.
  4031. `X !~ Y'
  4032.      True if the string X does not match the regexp denoted by Y.
  4033. `SUBSCRIPT in ARRAY'
  4034.      True if the array ARRAY has an element with the subscript
  4035.      SUBSCRIPT.
  4036.    Comparison expressions have the value one if true and zero if false.
  4037.    When comparing operands of mixed types, numeric operands are
  4038. converted to strings using the value of `CONVFMT' (*note Conversion of
  4039. Strings and Numbers: Conversion.).
  4040.    Strings are compared by comparing the first character of each, then
  4041. the second character of each, and so on.  Thus `"10"' is less than
  4042. `"9"'.  If there are two strings where one is a prefix of the other,
  4043. the shorter string is less than the longer one.  Thus `"abc"' is less
  4044. than `"abcd"'.
  4045.    It is very easy to accidentally mistype the `==' operator, and leave
  4046. off one of the `='s.  The result is still valid `awk' code, but the
  4047. program will not do what you mean:
  4048.      if (a = b)   # oops! should be a == b
  4049.         ...
  4050.      else
  4051.         ...
  4052. Unless `b' happens to be zero or the null string, the `if' part of the
  4053. test will always succeed.  Because the operators are so similar, this
  4054. kind of error is very difficult to spot when scanning the source code.
  4055.    Here are some sample expressions, how `gawk' compares them, and what
  4056. the result of the comparison is.
  4057. `1.5 <= 2.0'
  4058.      numeric comparison (true)
  4059. `"abc" >= "xyz"'
  4060.      string comparison (false)
  4061. `1.5 != " +2"'
  4062.      string comparison (true)
  4063. `"1e2" < "3"'
  4064.      string comparison (true)
  4065. `a = 2; b = "2"'
  4066. `a == b'
  4067.      string comparison (true)
  4068. `a = 2; b = " +2"'
  4069. `a == b'
  4070.      string comparison (false)
  4071.    In this example,
  4072.      $ echo 1e2 3 | awk '{ print ($1 < $2) ? "true" : "false" }'
  4073.      -| false
  4074. the result is `false' since both `$1' and `$2' are numeric strings and
  4075. thus both have the STRNUM attribute, dictating a numeric comparison.
  4076.    The purpose of the comparison rules and the use of numeric strings is
  4077. to attempt to produce the behavior that is "least surprising," while
  4078. still "doing the right thing."
  4079.    String comparisons and regular expression comparisons are very
  4080. different.  For example,
  4081.      x == "foo"
  4082. has the value of one, or is true, if the variable `x' is precisely
  4083. `foo'.  By contrast,
  4084.      x ~ /foo/
  4085. has the value one if `x' contains `foo', such as `"Oh, what a fool am
  4086. I!"'.
  4087.    The right hand operand of the `~' and `!~' operators may be either a
  4088. regexp constant (`/.../'), or an ordinary expression, in which case the
  4089. value of the expression as a string is used as a dynamic regexp (*note
  4090. How to Use Regular Expressions: Regexp Usage.; also *note Using Dynamic
  4091. Regexps: Computed Regexps.).
  4092.    In recent implementations of `awk', a constant regular expression in
  4093. slashes by itself is also an expression.  The regexp `/REGEXP/' is an
  4094. abbreviation for this comparison expression:
  4095.      $0 ~ /REGEXP/
  4096.    One special place where `/foo/' is *not* an abbreviation for `$0 ~
  4097. /foo/' is when it is the right-hand operand of `~' or `!~'!  *Note
  4098. Using Regular Expression Constants: Using Constant Regexps, where this
  4099. is discussed in more detail.
  4100. File: gawk.info,  Node: Boolean Ops,  Next: Conditional Exp,  Prev: Typing and Comparison,  Up: Expressions
  4101. Boolean Expressions
  4102. ===================
  4103.    A "boolean expression" is a combination of comparison expressions or
  4104. matching expressions, using the boolean operators "or" (`||'), "and"
  4105. (`&&'), and "not" (`!'), along with parentheses to control nesting.
  4106. The truth value of the boolean expression is computed by combining the
  4107. truth values of the component expressions.  Boolean expressions are
  4108. also referred to as "logical expressions".  The terms are equivalent.
  4109.    Boolean expressions can be used wherever comparison and matching
  4110. expressions can be used.  They can be used in `if', `while', `do' and
  4111. `for' statements (*note Control Statements in Actions: Statements.).
  4112. They have numeric values (one if true, zero if false), which come into
  4113. play if the result of the boolean expression is stored in a variable, or
  4114. used in arithmetic.
  4115.    In addition, every boolean expression is also a valid pattern, so
  4116. you can use one as a pattern to control the execution of rules.
  4117.    Here are descriptions of the three boolean operators, with examples.
  4118. `BOOLEAN1 && BOOLEAN2'
  4119.      True if both BOOLEAN1 and BOOLEAN2 are true.  For example, the
  4120.      following statement prints the current input record if it contains
  4121.      both `2400' and `foo'.
  4122.           if ($0 ~ /2400/ && $0 ~ /foo/) print
  4123.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is true.
  4124.      This can make a difference when BOOLEAN2 contains expressions that
  4125.      have side effects: in the case of `$0 ~ /foo/ && ($2 == bar++)',
  4126.      the variable `bar' is not incremented if there is no `foo' in the
  4127.      record.
  4128. `BOOLEAN1 || BOOLEAN2'
  4129.      True if at least one of BOOLEAN1 or BOOLEAN2 is true.  For
  4130.      example, the following statement prints all records in the input
  4131.      that contain *either* `2400' or `foo', or both.
  4132.           if ($0 ~ /2400/ || $0 ~ /foo/) print
  4133.      The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is false.
  4134.      This can make a difference when BOOLEAN2 contains expressions
  4135.      that have side effects.
  4136. `! BOOLEAN'
  4137.      True if BOOLEAN is false.  For example, the following program
  4138.      prints all records in the input file `BBS-list' that do *not*
  4139.      contain the string `foo'.
  4140.           awk '{ if (! ($0 ~ /foo/)) print }' BBS-list
  4141.    The `&&' and `||' operators are called "short-circuit" operators
  4142. because of the way they work.  Evaluation of the full expression is
  4143. "short-circuited" if the result can be determined part way through its
  4144. evaluation.
  4145.    You can continue a statement that uses `&&' or `||' simply by
  4146. putting a newline after them.  But you cannot put a newline in front of
  4147. either of these operators without using backslash continuation (*note
  4148. `awk' Statements Versus Lines: Statements/Lines.).
  4149.    The actual value of an expression using the `!' operator will be
  4150. either one or zero, depending upon the truth value of the expression it
  4151. is applied to.
  4152.    The `!' operator is often useful for changing the sense of a flag
  4153. variable from false to true and back again. For example, the following
  4154. program is one way to print lines in between special bracketing lines:
  4155.      $1 == "START"   { interested = ! interested }
  4156.      interested == 1 { print }
  4157.      $1 == "END"     { interested = ! interested }
  4158. The variable `interested', like all `awk' variables, starts out
  4159. initialized to zero, which is also false.  When a line is seen whose
  4160. first field is `START', the value of `interested' is toggled to true,
  4161. using `!'. The next rule prints lines as long as `interested' is true.
  4162. When a line is seen whose first field is `END', `interested' is toggled
  4163. back to false.
  4164. File: gawk.info,  Node: Conditional Exp,  Next: Function Calls,  Prev: Boolean Ops,  Up: Expressions
  4165. Conditional Expressions
  4166. =======================
  4167.    A "conditional expression" is a special kind of expression with
  4168. three operands.  It allows you to use one expression's value to select
  4169. one of two other expressions.
  4170.    The conditional expression is the same as in the C language:
  4171.      SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP
  4172. There are three subexpressions.  The first, SELECTOR, is always
  4173. computed first.  If it is "true" (not zero and not null) then
  4174. IF-TRUE-EXP is computed next and its value becomes the value of the
  4175. whole expression.  Otherwise, IF-FALSE-EXP is computed next and its
  4176. value becomes the value of the whole expression.
  4177.    For example, this expression produces the absolute value of `x':
  4178.      x > 0 ? x : -x
  4179.    Each time the conditional expression is computed, exactly one of
  4180. IF-TRUE-EXP and IF-FALSE-EXP is computed; the other is ignored.  This
  4181. is important when the expressions contain side effects.  For example,
  4182. this conditional expression examines element `i' of either array `a' or
  4183. array `b', and increments `i'.
  4184.      x == y ? a[i++] : b[i++]
  4185. This is guaranteed to increment `i' exactly once, because each time
  4186. only one of the two increment expressions is executed, and the other is
  4187. not.  *Note Arrays in `awk': Arrays, for more information about arrays.
  4188.    As a minor `gawk' extension, you can continue a statement that uses
  4189. `?:' simply by putting a newline after either character.  However, you
  4190. cannot put a newline in front of either character without using
  4191. backslash continuation (*note `awk' Statements Versus Lines:
  4192. Statements/Lines.).
  4193. File: gawk.info,  Node: Function Calls,  Next: Precedence,  Prev: Conditional Exp,  Up: Expressions
  4194. Function Calls
  4195. ==============
  4196.    A "function" is a name for a particular calculation.  Because it has
  4197. a name, you can ask for it by name at any point in the program.  For
  4198. example, the function `sqrt' computes the square root of a number.
  4199.    A fixed set of functions are "built-in", which means they are
  4200. available in every `awk' program.  The `sqrt' function is one of these.
  4201. *Note Built-in Functions: Built-in, for a list of built-in functions
  4202. and their descriptions.  In addition, you can define your own functions
  4203. for use in your program.  *Note User-defined Functions: User-defined,
  4204. for how to do this.
  4205.    The way to use a function is with a "function call" expression,
  4206. which consists of the function name followed immediately by a list of
  4207. "arguments" in parentheses.  The arguments are expressions which
  4208. provide the raw materials for the function's calculations.  When there
  4209. is more than one argument, they are separated by commas.  If there are
  4210. no arguments, write just `()' after the function name.  Here are some
  4211. examples:
  4212.      sqrt(x^2 + y^2)        one argument
  4213.      atan2(y, x)            two arguments
  4214.      rand()                 no arguments
  4215.    *Do not put any space between the function name and the
  4216. open-parenthesis!*  A user-defined function name looks just like the
  4217. name of a variable, and space would make the expression look like
  4218. concatenation of a variable with an expression inside parentheses.
  4219. Space before the parenthesis is harmless with built-in functions, but
  4220. it is best not to get into the habit of using space to avoid mistakes
  4221. with user-defined functions.
  4222.    Each function expects a particular number of arguments.  For
  4223. example, the `sqrt' function must be called with a single argument, the
  4224. number to take the square root of:
  4225.      sqrt(ARGUMENT)
  4226.    Some of the built-in functions allow you to omit the final argument.
  4227. If you do so, they use a reasonable default.  *Note Built-in Functions:
  4228. Built-in, for full details.  If arguments are omitted in calls to
  4229. user-defined functions, then those arguments are treated as local
  4230. variables, initialized to the empty string (*note User-defined
  4231. Functions: User-defined.).
  4232.    Like every other expression, the function call has a value, which is
  4233. computed by the function based on the arguments you give it.  In this
  4234. example, the value of `sqrt(ARGUMENT)' is the square root of ARGUMENT.
  4235. A function can also have side effects, such as assigning values to
  4236. certain variables or doing I/O.
  4237.    Here is a command to read numbers, one number per line, and print the
  4238. square root of each one:
  4239.      $ awk '{ print "The square root of", $1, "is", sqrt($1) }'
  4240.      1
  4241.      -| The square root of 1 is 1
  4242.      3
  4243.      -| The square root of 3 is 1.73205
  4244.      5
  4245.      -| The square root of 5 is 2.23607
  4246.      Control-d
  4247. File: gawk.info,  Node: Precedence,  Prev: Function Calls,  Up: Expressions
  4248. Operator Precedence (How Operators Nest)
  4249. ========================================
  4250.    "Operator precedence" determines how operators are grouped, when
  4251. different operators appear close by in one expression.  For example,
  4252. `*' has higher precedence than `+'; thus, `a + b * c' means to multiply
  4253. `b' and `c', and then add `a' to the product (i.e. `a + (b * c)').
  4254.    You can overrule the precedence of the operators by using
  4255. parentheses.  You can think of the precedence rules as saying where the
  4256. parentheses are assumed to be if you do not write parentheses yourself.
  4257. In fact, it is wise to always use parentheses whenever you have an
  4258. unusual combination of operators, because other people who read the
  4259. program may not remember what the precedence is in this case.  You
  4260. might forget, too; then you could make a mistake.  Explicit parentheses
  4261. will help prevent any such mistake.
  4262.    When operators of equal precedence are used together, the leftmost
  4263. operator groups first, except for the assignment, conditional and
  4264. exponentiation operators, which group in the opposite order.  Thus, `a
  4265. - b + c' groups as `(a - b) + c', and `a = b = c' groups as `a = (b =
  4266.    The precedence of prefix unary operators does not matter as long as
  4267. only unary operators are involved, because there is only one way to
  4268. interpret them--innermost first.  Thus, `$++i' means `$(++i)' and
  4269. `++$x' means `++($x)'.  However, when another operator follows the
  4270. operand, then the precedence of the unary operators can matter.  Thus,
  4271. `$x^2' means `($x)^2', but `-x^2' means `-(x^2)', because `-' has lower
  4272. precedence than `^' while `$' has higher precedence.
  4273.    Here is a table of `awk''s operators, in order from highest
  4274. precedence to lowest:
  4275. `(...)'
  4276.      Grouping.
  4277.      Field.
  4278. `++ --'
  4279.      Increment, decrement.
  4280. `^ **'
  4281.      Exponentiation.  These operators group right-to-left.  (The `**'
  4282.      operator is not specified by POSIX.)
  4283. `+ - !'
  4284.      Unary plus, minus, logical "not".
  4285. `* / %'
  4286.      Multiplication, division, modulus.
  4287. `+ -'
  4288.      Addition, subtraction.
  4289. `Concatenation'
  4290.      No special token is used to indicate concatenation.  The operands
  4291.      are simply written side by side.
  4292. `< <= == !='
  4293. `> >= >> |'
  4294.      Relational, and redirection.  The relational operators and the
  4295.      redirections have the same precedence level.  Characters such as
  4296.      `>' serve both as relationals and as redirections; the context
  4297.      distinguishes between the two meanings.
  4298.      Note that the I/O redirection operators in `print' and `printf'
  4299.      statements belong to the statement level, not to expressions.  The
  4300.      redirection does not produce an expression which could be the
  4301.      operand of another operator.  As a result, it does not make sense
  4302.      to use a redirection operator near another operator of lower
  4303.      precedence, without parentheses.  Such combinations, for example
  4304.      `print foo > a ? b : c', result in syntax errors.  The correct way
  4305.      to write this statement is `print foo > (a ? b : c)'.
  4306. `~ !~'
  4307.      Matching, non-matching.
  4308.      Array membership.
  4309.      Logical "and".
  4310.      Logical "or".
  4311.      Conditional.  This operator groups right-to-left.
  4312. `= += -= *='
  4313. `/= %= ^= **='
  4314.      Assignment.  These operators group right-to-left.  (The `**='
  4315.      operator is not specified by POSIX.)
  4316. File: gawk.info,  Node: Patterns and Actions,  Next: Statements,  Prev: Expressions,  Up: Top
  4317. Patterns and Actions
  4318. ********************
  4319.    As you have already seen, each `awk' statement consists of a pattern
  4320. with an associated action.  This chapter describes how you build
  4321. patterns and actions.
  4322. * Menu:
  4323. * Pattern Overview::            What goes into a pattern.
  4324. * Action Overview::             What goes into an action.
  4325. File: gawk.info,  Node: Pattern Overview,  Next: Action Overview,  Prev: Patterns and Actions,  Up: Patterns and Actions
  4326. Pattern Elements
  4327. ================
  4328.    Patterns in `awk' control the execution of rules: a rule is executed
  4329. when its pattern matches the current input record.  This section
  4330. explains all about how to write patterns.
  4331. * Menu:
  4332. * Kinds of Patterns::           A list of all kinds of patterns.
  4333. * Regexp Patterns::             Using regexps as patterns.
  4334. * Expression Patterns::         Any expression can be used as a pattern.
  4335. * Ranges::                      Pairs of patterns specify record ranges.
  4336. * BEGIN/END::                   Specifying initialization and cleanup rules.
  4337. * Empty::                       The empty pattern, which matches every record.
  4338. File: gawk.info,  Node: Kinds of Patterns,  Next: Regexp Patterns,  Prev: Pattern Overview,  Up: Pattern Overview
  4339. Kinds of Patterns
  4340. -----------------
  4341.    Here is a summary of the types of patterns supported in `awk'.
  4342. `/REGULAR EXPRESSION/'
  4343.      A regular expression as a pattern.  It matches when the text of the
  4344.      input record fits the regular expression.  (*Note Regular
  4345.      Expressions: Regexp.)
  4346. `EXPRESSION'
  4347.      A single expression.  It matches when its value is non-zero (if a
  4348.      number) or non-null (if a string).  (*Note Expressions as
  4349.      Patterns: Expression Patterns.)
  4350. `PAT1, PAT2'
  4351.      A pair of patterns separated by a comma, specifying a range of
  4352.      records.  The range includes both the initial record that matches
  4353.      PAT1, and the final record that matches PAT2.  (*Note Specifying
  4354.      Record Ranges with Patterns: Ranges.)
  4355. `BEGIN'
  4356. `END'
  4357.      Special patterns for you to supply start-up or clean-up actions
  4358.      for your `awk' program.  (*Note The `BEGIN' and `END' Special
  4359.      Patterns: BEGIN/END.)
  4360. `EMPTY'
  4361.      The empty pattern matches every input record.  (*Note The Empty
  4362.      Pattern: Empty.)
  4363. File: gawk.info,  Node: Regexp Patterns,  Next: Expression Patterns,  Prev: Kinds of Patterns,  Up: Pattern Overview
  4364. Regular Expressions as Patterns
  4365. -------------------------------
  4366.    We have been using regular expressions as patterns since our early
  4367. examples.  This kind of pattern is simply a regexp constant in the
  4368. pattern part of a rule.  Its  meaning is `$0 ~ /PATTERN/'.  The pattern
  4369. matches when the input record matches the regexp.  For example:
  4370.      /foo|bar|baz/  { buzzwords++ }
  4371.      END            { print buzzwords, "buzzwords seen" }
  4372. File: gawk.info,  Node: Expression Patterns,  Next: Ranges,  Prev: Regexp Patterns,  Up: Pattern Overview
  4373. Expressions as Patterns
  4374. -----------------------
  4375.    Any `awk' expression is valid as an `awk' pattern.  Then the pattern
  4376. matches if the expression's value is non-zero (if a number) or non-null
  4377. (if a string).
  4378.    The expression is reevaluated each time the rule is tested against a
  4379. new input record.  If the expression uses fields such as `$1', the
  4380. value depends directly on the new input record's text; otherwise, it
  4381. depends only on what has happened so far in the execution of the `awk'
  4382. program, but that may still be useful.
  4383.    A very common kind of expression used as a pattern is the comparison
  4384. expression, using the comparison operators described in *Note Variable
  4385. Typing and Comparison Expressions: Typing and Comparison.
  4386.    Regexp matching and non-matching are also very common expressions.
  4387. The left operand of the `~' and `!~' operators is a string.  The right
  4388. operand is either a constant regular expression enclosed in slashes
  4389. (`/REGEXP/'), or any expression, whose string value is used as a
  4390. dynamic regular expression (*note Using Dynamic Regexps: Computed
  4391. Regexps.).
  4392.    The following example prints the second field of each input record
  4393. whose first field is precisely `foo'.
  4394.      $ awk '$1 == "foo" { print $2 }' BBS-list
  4395. (There is no output, since there is no BBS site named "foo".) Contrast
  4396. this with the following regular expression match, which would accept
  4397. any record with a first field that contains `foo':
  4398.      $ awk '$1 ~ /foo/ { print $2 }' BBS-list
  4399.      -| 555-1234
  4400.      -| 555-6699
  4401.      -| 555-6480
  4402.      -| 555-2127
  4403.    Boolean expressions are also commonly used as patterns.  Whether the
  4404. pattern matches an input record depends on whether its subexpressions
  4405. match.
  4406.    For example, the following command prints all records in `BBS-list'
  4407. that contain both `2400' and `foo'.
  4408.      $ awk '/2400/ && /foo/' BBS-list
  4409.      -| fooey        555-1234     2400/1200/300     B
  4410.    The following command prints all records in `BBS-list' that contain
  4411. *either* `2400' or `foo', or both.
  4412.      $ awk '/2400/ || /foo/' BBS-list
  4413.      -| alpo-net     555-3412     2400/1200/300     A
  4414.      -| bites        555-1675     2400/1200/300     A
  4415.      -| fooey        555-1234     2400/1200/300     B
  4416.      -| foot         555-6699     1200/300          B
  4417.      -| macfoo       555-6480     1200/300          A
  4418.      -| sdace        555-3430     2400/1200/300     A
  4419.      -| sabafoo      555-2127     1200/300          C
  4420.    The following command prints all records in `BBS-list' that do *not*
  4421. contain the string `foo'.
  4422.      $ awk '! /foo/' BBS-list
  4423.      -| aardvark     555-5553     1200/300          B
  4424.      -| alpo-net     555-3412     2400/1200/300     A
  4425.      -| barfly       555-7685     1200/300          A
  4426.      -| bites        555-1675     2400/1200/300     A
  4427.      -| camelot      555-0542     300               C
  4428.      -| core         555-2912     1200/300          C
  4429.      -| sdace        555-3430     2400/1200/300     A
  4430.    The subexpressions of a boolean operator in a pattern can be
  4431. constant regular expressions, comparisons, or any other `awk'
  4432. expressions.  Range patterns are not expressions, so they cannot appear
  4433. inside boolean patterns.  Likewise, the special patterns `BEGIN' and
  4434. `END', which never match any input record, are not expressions and
  4435. cannot appear inside boolean patterns.
  4436.    A regexp constant as a pattern is also a special case of an
  4437. expression pattern.  `/foo/' as an expression has the value one if `foo'
  4438. appears in the current input record; thus, as a pattern, `/foo/'
  4439. matches any record containing `foo'.
  4440. File: gawk.info,  Node: Ranges,  Next: BEGIN/END,  Prev: Expression Patterns,  Up: Pattern Overview
  4441. Specifying Record Ranges with Patterns
  4442. --------------------------------------
  4443.    A "range pattern" is made of two patterns separated by a comma, of
  4444. the form `BEGPAT, ENDPAT'.  It matches ranges of consecutive input
  4445. records.  The first pattern, BEGPAT, controls where the range begins,
  4446. and the second one, ENDPAT, controls where it ends.  For example,
  4447.      awk '$1 == "on", $1 == "off"'
  4448. prints every record between `on'/`off' pairs, inclusive.
  4449.    A range pattern starts out by matching BEGPAT against every input
  4450. record; when a record matches BEGPAT, the range pattern becomes "turned
  4451. on".  The range pattern matches this record.  As long as it stays
  4452. turned on, it automatically matches every input record read.  It also
  4453. matches ENDPAT against every input record; when that succeeds, the
  4454. range pattern is turned off again for the following record.  Then it
  4455. goes back to checking BEGPAT against each record.
  4456.    The record that turns on the range pattern and the one that turns it
  4457. off both match the range pattern.  If you don't want to operate on
  4458. these records, you can write `if' statements in the rule's action to
  4459. distinguish them from the records you are interested in.
  4460.    It is possible for a pattern to be turned both on and off by the same
  4461. record, if the record satisfies both conditions.  Then the action is
  4462. executed for just that record.
  4463.    For example, suppose you have text between two identical markers (say
  4464. the `%' symbol) that you wish to ignore.  You might try to combine a
  4465. range pattern that describes the delimited text with the `next'
  4466. statement (not discussed yet, *note The `next' Statement: Next
  4467. Statement.), which causes `awk' to skip any further processing of the
  4468. current record and start over again with the next input record. Such a
  4469. program would look like this:
  4470.      /^%$/,/^%$/    { next }
  4471.                     { print }
  4472. This program fails because the range pattern is both turned on and
  4473. turned off by the first line with just a `%' on it.  To accomplish this
  4474. task, you must write the program this way, using a flag:
  4475.      /^%$/     { skip = ! skip; next }
  4476.      skip == 1 { next } # skip lines with `skip' set
  4477.    Note that in a range pattern, the `,' has the lowest precedence (is
  4478. evaluated last) of all the operators.  Thus, for example, the following
  4479. program attempts to combine a range pattern with another, simpler test.
  4480.      echo Yes | awk '/1/,/2/ || /Yes/'
  4481.    The author of this program intended it to mean `(/1/,/2/) || /Yes/'.
  4482. However, `awk' interprets this as `/1/, (/2/ || /Yes/)'.  This cannot
  4483. be changed or worked around; range patterns do not combine with other
  4484. patterns.
  4485. File: gawk.info,  Node: BEGIN/END,  Next: Empty,  Prev: Ranges,  Up: Pattern Overview
  4486. The `BEGIN' and `END' Special Patterns
  4487. --------------------------------------
  4488.    `BEGIN' and `END' are special patterns.  They are not used to match
  4489. input records.  Rather, they supply start-up or clean-up actions for
  4490. your `awk' script.
  4491. * Menu:
  4492. * Using BEGIN/END::             How and why to use BEGIN/END rules.
  4493. * I/O And BEGIN/END::           I/O issues in BEGIN/END rules.
  4494. File: gawk.info,  Node: Using BEGIN/END,  Next: I/O And BEGIN/END,  Prev: BEGIN/END,  Up: BEGIN/END
  4495. Startup and Cleanup Actions
  4496. ...........................
  4497.    A `BEGIN' rule is executed, once, before the first input record has
  4498. been read.  An `END' rule is executed, once, after all the input has
  4499. been read.  For example:
  4500.      $ awk '
  4501.      > BEGIN { print "Analysis of \"foo\"" }
  4502.      > /foo/ { ++n }
  4503.      > END   { print "\"foo\" appears " n " times." }' BBS-list
  4504.      -| Analysis of "foo"
  4505.      -| "foo" appears 4 times.
  4506.    This program finds the number of records in the input file `BBS-list'
  4507. that contain the string `foo'.  The `BEGIN' rule prints a title for the
  4508. report.  There is no need to use the `BEGIN' rule to initialize the
  4509. counter `n' to zero, as `awk' does this automatically (*note
  4510. Variables::.).
  4511.    The second rule increments the variable `n' every time a record
  4512. containing the pattern `foo' is read.  The `END' rule prints the value
  4513. of `n' at the end of the run.
  4514.    The special patterns `BEGIN' and `END' cannot be used in ranges or
  4515. with boolean operators (indeed, they cannot be used with any operators).
  4516.    An `awk' program may have multiple `BEGIN' and/or `END' rules.  They
  4517. are executed in the order they appear, all the `BEGIN' rules at
  4518. start-up and all the `END' rules at termination.  `BEGIN' and `END'
  4519. rules may be intermixed with other rules.  This feature was added in
  4520. the 1987 version of `awk', and is included in the POSIX standard.  The
  4521. original (1978) version of `awk' required you to put the `BEGIN' rule
  4522. at the beginning of the program, and the `END' rule at the end, and
  4523. only allowed one of each.  This is no longer required, but it is a good
  4524. idea in terms of program organization and readability.
  4525.    Multiple `BEGIN' and `END' rules are useful for writing library
  4526. functions, since each library file can have its own `BEGIN' and/or
  4527. `END' rule to do its own initialization and/or cleanup.  Note that the
  4528. order in which library functions are named on the command line controls
  4529. the order in which their `BEGIN' and `END' rules are executed.
  4530. Therefore you have to be careful to write such rules in library files
  4531. so that the order in which they are executed doesn't matter.  *Note
  4532. Command Line Options: Options, for more information on using library
  4533. functions.  *Note A Library of `awk' Functions: Library Functions, for
  4534. a number of useful library functions.
  4535.    If an `awk' program only has a `BEGIN' rule, and no other rules,
  4536. then the program exits after the `BEGIN' rule has been run.  (The
  4537. original version of `awk' used to keep reading and ignoring input until
  4538. end of file was seen.)  However, if an `END' rule exists, then the
  4539. input will be read, even if there are no other rules in the program.
  4540. This is necessary in case the `END' rule checks the `FNR' and `NR'
  4541. variables (d.c.).
  4542.    `BEGIN' and `END' rules must have actions; there is no default
  4543. action for these rules since there is no current record when they run.
  4544. File: gawk.info,  Node: I/O And BEGIN/END,  Prev: Using BEGIN/END,  Up: BEGIN/END
  4545. Input/Output from `BEGIN' and `END' Rules
  4546. .........................................
  4547.    There are several (sometimes subtle) issues involved when doing I/O
  4548. from a `BEGIN' or `END' rule.
  4549.    The first has to do with the value of `$0' in a `BEGIN' rule.  Since
  4550. `BEGIN' rules are executed before any input is read, there simply is no
  4551. input record, and therefore no fields, when executing `BEGIN' rules.
  4552. References to `$0' and the fields yield a null string or zero,
  4553. depending upon the context.  One way to give `$0' a real value is to
  4554. execute a `getline' command without a variable (*note Explicit Input
  4555. with `getline': Getline.).  Another way is to simply assign a value to
  4556.    The second point is similar to the first, but from the other
  4557. direction.  Inside an `END' rule, what is the value of `$0' and `NF'?
  4558. Traditionally, due largely to implementation issues, `$0' and `NF' were
  4559. *undefined* inside an `END' rule.  The POSIX standard specified that
  4560. `NF' was available in an `END' rule, containing the number of fields
  4561. from the last input record.  Due most probably to an oversight, the
  4562. standard does not say that `$0' is also preserved, although logically
  4563. one would think that it should be.  In fact, `gawk' does preserve the
  4564. value of `$0' for use in `END' rules.  Be aware, however, that Unix
  4565. `awk', and possibly other implementations, do not.
  4566.    The third point follows from the first two.  What is the meaning of
  4567. `print' inside a `BEGIN' or `END' rule?  The meaning is the same as
  4568. always, `print $0'.  If `$0' is the null string, then this prints an
  4569. empty line.  Many long time `awk' programmers use `print' in `BEGIN'
  4570. and `END' rules, to mean `print ""', relying on `$0' being null.  While
  4571. you might generally get away with this in `BEGIN' rules, in `gawk' at
  4572. least, it is a very bad idea in `END' rules.  It is also poor style,
  4573. since if you want an empty line in the output, you should say so
  4574. explicitly in your program.
  4575. File: gawk.info,  Node: Empty,  Prev: BEGIN/END,  Up: Pattern Overview
  4576. The Empty Pattern
  4577. -----------------
  4578.    An empty (i.e. non-existent) pattern is considered to match *every*
  4579. input record.  For example, the program:
  4580.      awk '{ print $1 }' BBS-list
  4581. prints the first field of every record.
  4582. File: gawk.info,  Node: Action Overview,  Prev: Pattern Overview,  Up: Patterns and Actions
  4583. Overview of Actions
  4584. ===================
  4585.    An `awk' program or script consists of a series of rules and
  4586. function definitions, interspersed.  (Functions are described later.
  4587. *Note User-defined Functions: User-defined.)
  4588.    A rule contains a pattern and an action, either of which (but not
  4589. both) may be omitted.  The purpose of the "action" is to tell `awk'
  4590. what to do once a match for the pattern is found.  Thus, in outline, an
  4591. `awk' program generally looks like this:
  4592.      [PATTERN] [{ ACTION }]
  4593.      [PATTERN] [{ ACTION }]
  4594.      ...
  4595.      function NAME(ARGS) { ... }
  4596.      ...
  4597.    An action consists of one or more `awk' "statements", enclosed in
  4598. curly braces (`{' and `}').  Each statement specifies one thing to be
  4599. done.  The statements are separated by newlines or semicolons.
  4600.    The curly braces around an action must be used even if the action
  4601. contains only one statement, or even if it contains no statements at
  4602. all.  However, if you omit the action entirely, omit the curly braces as
  4603. well.  An omitted action is equivalent to `{ print $0 }'.
  4604.      /foo/  { }  # match foo, do nothing - empty action
  4605.      /foo/       # match foo, print the record - omitted action
  4606.    Here are the kinds of statements supported in `awk':
  4607.    * Expressions, which can call functions or assign values to variables
  4608.      (*note Expressions::.).  Executing this kind of statement simply
  4609.      computes the value of the expression.  This is useful when the
  4610.      expression has side effects (*note Assignment Expressions:
  4611.      Assignment Ops.).
  4612.    * Control statements, which specify the control flow of `awk'
  4613.      programs.  The `awk' language gives you C-like constructs (`if',
  4614.      `for', `while', and `do') as well as a few special ones (*note
  4615.      Control Statements in Actions: Statements.).
  4616.    * Compound statements, which consist of one or more statements
  4617.      enclosed in curly braces.  A compound statement is used in order
  4618.      to put several statements together in the body of an `if',
  4619.      `while', `do' or `for' statement.
  4620.    * Input statements, using the `getline' command (*note Explicit
  4621.      Input with `getline': Getline.), the `next' statement (*note The
  4622.      `next' Statement: Next Statement.), and the `nextfile' statement
  4623.      (*note The `nextfile' Statement: Nextfile Statement.).
  4624.    * Output statements, `print' and `printf'.  *Note Printing Output:
  4625.      Printing.
  4626.    * Deletion statements, for deleting array elements.  *Note The
  4627.      `delete' Statement: Delete.
  4628. File: gawk.info,  Node: Statements,  Next: Built-in Variables,  Prev: Patterns and Actions,  Up: Top
  4629. Control Statements in Actions
  4630. *****************************
  4631.    "Control statements" such as `if', `while', and so on control the
  4632. flow of execution in `awk' programs.  Most of the control statements in
  4633. `awk' are patterned on similar statements in C.
  4634.    All the control statements start with special keywords such as `if'
  4635. and `while', to distinguish them from simple expressions.
  4636.    Many control statements contain other statements; for example, the
  4637. `if' statement contains another statement which may or may not be
  4638. executed.  The contained statement is called the "body".  If you want
  4639. to include more than one statement in the body, group them into a
  4640. single "compound statement" with curly braces, separating them with
  4641. newlines or semicolons.
  4642. * Menu:
  4643. * If Statement::                Conditionally execute some `awk'
  4644.                                 statements.
  4645. * While Statement::             Loop until some condition is satisfied.
  4646. * Do Statement::                Do specified action while looping until some
  4647.                                 condition is satisfied.
  4648. * For Statement::               Another looping statement, that provides
  4649.                                 initialization and increment clauses.
  4650. * Break Statement::             Immediately exit the innermost enclosing loop.
  4651. * Continue Statement::          Skip to the end of the innermost enclosing
  4652.                                 loop.
  4653. * Next Statement::              Stop processing the current input record.
  4654. * Nextfile Statement::          Stop processing the current file.
  4655. * Exit Statement::              Stop execution of `awk'.
  4656. File: gawk.info,  Node: If Statement,  Next: While Statement,  Prev: Statements,  Up: Statements
  4657. The `if'-`else' Statement
  4658. =========================
  4659.    The `if'-`else' statement is `awk''s decision-making statement.  It
  4660. looks like this:
  4661.      if (CONDITION) THEN-BODY [else ELSE-BODY]
  4662. The CONDITION is an expression that controls what the rest of the
  4663. statement will do.  If CONDITION is true, THEN-BODY is executed;
  4664. otherwise, ELSE-BODY is executed.  The `else' part of the statement is
  4665. optional.  The condition is considered false if its value is zero or
  4666. the null string, and true otherwise.
  4667.    Here is an example:
  4668.      if (x % 2 == 0)
  4669.          print "x is even"
  4670.      else
  4671.          print "x is odd"
  4672.    In this example, if the expression `x % 2 == 0' is true (that is,
  4673. the value of `x' is evenly divisible by two), then the first `print'
  4674. statement is executed, otherwise the second `print' statement is
  4675. executed.
  4676.    If the `else' appears on the same line as THEN-BODY, and THEN-BODY
  4677. is not a compound statement (i.e. not surrounded by curly braces), then
  4678. a semicolon must separate THEN-BODY from `else'.  To illustrate this,
  4679. let's rewrite the previous example:
  4680.      if (x % 2 == 0) print "x is even"; else
  4681.              print "x is odd"
  4682. If you forget the `;', `awk' won't be able to interpret the statement,
  4683. and you will get a syntax error.
  4684.    We would not actually write this example this way, because a human
  4685. reader might fail to see the `else' if it were not the first thing on
  4686. its line.
  4687. File: gawk.info,  Node: While Statement,  Next: Do Statement,  Prev: If Statement,  Up: Statements
  4688. The `while' Statement
  4689. =====================
  4690.    In programming, a "loop" means a part of a program that can be
  4691. executed two or more times in succession.
  4692.    The `while' statement is the simplest looping statement in `awk'.
  4693. It repeatedly executes a statement as long as a condition is true.  It
  4694. looks like this:
  4695.      while (CONDITION)
  4696.        BODY
  4697. Here BODY is a statement that we call the "body" of the loop, and
  4698. CONDITION is an expression that controls how long the loop keeps
  4699. running.
  4700.    The first thing the `while' statement does is test CONDITION.  If
  4701. CONDITION is true, it executes the statement BODY.  (The CONDITION is
  4702. true when the value is not zero and not a null string.) After BODY has
  4703. been executed, CONDITION is tested again, and if it is still true, BODY
  4704. is executed again.  This process repeats until CONDITION is no longer
  4705. true.  If CONDITION is initially false, the body of the loop is never
  4706. executed, and `awk' continues with the statement following the loop.
  4707.    This example prints the first three fields of each record, one per
  4708. line.
  4709.      awk '{ i = 1
  4710.             while (i <= 3) {
  4711.                 print $i
  4712.                 i++
  4713.             }
  4714.      }' inventory-shipped
  4715. Here the body of the loop is a compound statement enclosed in braces,
  4716. containing two statements.
  4717.    The loop works like this: first, the value of `i' is set to one.
  4718. Then, the `while' tests whether `i' is less than or equal to three.
  4719. This is true when `i' equals one, so the `i'-th field is printed.  Then
  4720. the `i++' increments the value of `i' and the loop repeats.  The loop
  4721. terminates when `i' reaches four.
  4722.    As you can see, a newline is not required between the condition and
  4723. the body; but using one makes the program clearer unless the body is a
  4724. compound statement or is very simple.  The newline after the open-brace
  4725. that begins the compound statement is not required either, but the
  4726. program would be harder to read without it.
  4727. File: gawk.info,  Node: Do Statement,  Next: For Statement,  Prev: While Statement,  Up: Statements
  4728. The `do'-`while' Statement
  4729. ==========================
  4730.    The `do' loop is a variation of the `while' looping statement.  The
  4731. `do' loop executes the BODY once, and then repeats BODY as long as
  4732. CONDITION is true.  It looks like this:
  4733.      do
  4734.        BODY
  4735.      while (CONDITION)
  4736.    Even if CONDITION is false at the start, BODY is executed at least
  4737. once (and only once, unless executing BODY makes CONDITION true).
  4738. Contrast this with the corresponding `while' statement:
  4739.      while (CONDITION)
  4740.        BODY
  4741. This statement does not execute BODY even once if CONDITION is false to
  4742. begin with.
  4743.    Here is an example of a `do' statement:
  4744.      awk '{ i = 1
  4745.             do {
  4746.                print $0
  4747.                i++
  4748.             } while (i <= 10)
  4749.      }'
  4750. This program prints each input record ten times.  It isn't a very
  4751. realistic example, since in this case an ordinary `while' would do just
  4752. as well.  But this reflects actual experience; there is only
  4753. occasionally a real use for a `do' statement.
  4754. File: gawk.info,  Node: For Statement,  Next: Break Statement,  Prev: Do Statement,  Up: Statements
  4755. The `for' Statement
  4756. ===================
  4757.    The `for' statement makes it more convenient to count iterations of a
  4758. loop.  The general form of the `for' statement looks like this:
  4759.      for (INITIALIZATION; CONDITION; INCREMENT)
  4760.        BODY
  4761. The INITIALIZATION, CONDITION and INCREMENT parts are arbitrary `awk'
  4762. expressions, and BODY stands for any `awk' statement.
  4763.    The `for' statement starts by executing INITIALIZATION.  Then, as
  4764. long as CONDITION is true, it repeatedly executes BODY and then
  4765. INCREMENT.  Typically INITIALIZATION sets a variable to either zero or
  4766. one, INCREMENT adds one to it, and CONDITION compares it against the
  4767. desired number of iterations.
  4768.    Here is an example of a `for' statement:
  4769.      awk '{ for (i = 1; i <= 3; i++)
  4770.                print $i
  4771.      }' inventory-shipped
  4772. This prints the first three fields of each input record, one field per
  4773. line.
  4774.    You cannot set more than one variable in the INITIALIZATION part
  4775. unless you use a multiple assignment statement such as `x = y = 0',
  4776. which is possible only if all the initial values are equal.  (But you
  4777. can initialize additional variables by writing their assignments as
  4778. separate statements preceding the `for' loop.)
  4779.    The same is true of the INCREMENT part; to increment additional
  4780. variables, you must write separate statements at the end of the loop.
  4781. The C compound expression, using C's comma operator, would be useful in
  4782. this context, but it is not supported in `awk'.
  4783.    Most often, INCREMENT is an increment expression, as in the example
  4784. above.  But this is not required; it can be any expression whatever.
  4785. For example, this statement prints all the powers of two between one
  4786. and 100:
  4787.      for (i = 1; i <= 100; i *= 2)
  4788.        print i
  4789.    Any of the three expressions in the parentheses following the `for'
  4790. may be omitted if there is nothing to be done there.  Thus,
  4791. `for (; x > 0;)' is equivalent to `while (x > 0)'.  If the CONDITION is
  4792. omitted, it is treated as TRUE, effectively yielding an "infinite loop"
  4793. (i.e. a loop that will never terminate).
  4794.    In most cases, a `for' loop is an abbreviation for a `while' loop,
  4795. as shown here:
  4796.      INITIALIZATION
  4797.      while (CONDITION) {
  4798.        BODY
  4799.        INCREMENT
  4800.      }
  4801. The only exception is when the `continue' statement (*note The
  4802. `continue' Statement: Continue Statement.) is used inside the loop;
  4803. changing a `for' statement to a `while' statement in this way can
  4804. change the effect of the `continue' statement inside the loop.
  4805.    There is an alternate version of the `for' loop, for iterating over
  4806. all the indices of an array:
  4807.      for (i in array)
  4808.          DO SOMETHING WITH array[i]
  4809. *Note Scanning All Elements of an Array: Scanning an Array, for more
  4810. information on this version of the `for' loop.
  4811.    The `awk' language has a `for' statement in addition to a `while'
  4812. statement because often a `for' loop is both less work to type and more
  4813. natural to think of.  Counting the number of iterations is very common
  4814. in loops.  It can be easier to think of this counting as part of
  4815. looping rather than as something to do inside the loop.
  4816.    The next section has more complicated examples of `for' loops.
  4817. File: gawk.info,  Node: Break Statement,  Next: Continue Statement,  Prev: For Statement,  Up: Statements
  4818. The `break' Statement
  4819. =====================
  4820.    The `break' statement jumps out of the innermost `for', `while', or
  4821. `do' loop that encloses it.  The following example finds the smallest
  4822. divisor of any integer, and also identifies prime numbers:
  4823.      awk '# find smallest divisor of num
  4824.           { num = $1
  4825.             for (div = 2; div*div <= num; div++)
  4826.               if (num % div == 0)
  4827.                 break
  4828.             if (num % div == 0)
  4829.               printf "Smallest divisor of %d is %d\n", num, div
  4830.             else
  4831.               printf "%d is prime\n", num
  4832.           }'
  4833.    When the remainder is zero in the first `if' statement, `awk'
  4834. immediately "breaks out" of the containing `for' loop.  This means that
  4835. `awk' proceeds immediately to the statement following the loop and
  4836. continues processing.  (This is very different from the `exit'
  4837. statement which stops the entire `awk' program.  *Note The `exit'
  4838. Statement: Exit Statement.)
  4839.    Here is another program equivalent to the previous one.  It
  4840. illustrates how the CONDITION of a `for' or `while' could just as well
  4841. be replaced with a `break' inside an `if':
  4842.      awk '# find smallest divisor of num
  4843.           { num = $1
  4844.             for (div = 2; ; div++) {
  4845.               if (num % div == 0) {
  4846.                 printf "Smallest divisor of %d is %d\n", num, div
  4847.                 break
  4848.               }
  4849.               if (div*div > num) {
  4850.                 printf "%d is prime\n", num
  4851.                 break
  4852.               }
  4853.             }
  4854.      }'
  4855.    As described above, the `break' statement has no meaning when used
  4856. outside the body of a loop.  However, although it was never documented,
  4857. historical implementations of `awk' have treated the `break' statement
  4858. outside of a loop as if it were a `next' statement (*note The `next'
  4859. Statement: Next Statement.).  Recent versions of Unix `awk' no longer
  4860. allow this usage.  `gawk' will support this use of `break' only if
  4861. `--traditional' has been specified on the command line (*note Command
  4862. Line Options: Options.).  Otherwise, it will be treated as an error,
  4863. since the POSIX standard specifies that `break' should only be used
  4864. inside the body of a loop (d.c.).
  4865. File: gawk.info,  Node: Continue Statement,  Next: Next Statement,  Prev: Break Statement,  Up: Statements
  4866. The `continue' Statement
  4867. ========================
  4868.    The `continue' statement, like `break', is used only inside `for',
  4869. `while', and `do' loops.  It skips over the rest of the loop body,
  4870. causing the next cycle around the loop to begin immediately.  Contrast
  4871. this with `break', which jumps out of the loop altogether.
  4872.    The `continue' statement in a `for' loop directs `awk' to skip the
  4873. rest of the body of the loop, and resume execution with the
  4874. increment-expression of the `for' statement.  The following program
  4875. illustrates this fact:
  4876.      awk 'BEGIN {
  4877.           for (x = 0; x <= 20; x++) {
  4878.               if (x == 5)
  4879.                   continue
  4880.               printf "%d ", x
  4881.           }
  4882.           print ""
  4883.      }'
  4884. This program prints all the numbers from zero to 20, except for five,
  4885. for which the `printf' is skipped.  Since the increment `x++' is not
  4886. skipped, `x' does not remain stuck at five.  Contrast the `for' loop
  4887. above with this `while' loop:
  4888.      awk 'BEGIN {
  4889.           x = 0
  4890.           while (x <= 20) {
  4891.               if (x == 5)
  4892.                   continue
  4893.               printf "%d ", x
  4894.               x++
  4895.           }
  4896.           print ""
  4897.      }'
  4898. This program loops forever once `x' gets to five.
  4899.    As described above, the `continue' statement has no meaning when
  4900. used outside the body of a loop.  However, although it was never
  4901. documented, historical implementations of `awk' have treated the
  4902. `continue' statement outside of a loop as if it were a `next' statement
  4903. (*note The `next' Statement: Next Statement.).  Recent versions of Unix
  4904. `awk' no longer allow this usage.  `gawk' will support this use of
  4905. `continue' only if `--traditional' has been specified on the command
  4906. line (*note Command Line Options: Options.).  Otherwise, it will be
  4907. treated as an error, since the POSIX standard specifies that `continue'
  4908. should only be used inside the body of a loop (d.c.).
  4909. File: gawk.info,  Node: Next Statement,  Next: Nextfile Statement,  Prev: Continue Statement,  Up: Statements
  4910. The `next' Statement
  4911. ====================
  4912.    The `next' statement forces `awk' to immediately stop processing the
  4913. current record and go on to the next record.  This means that no
  4914. further rules are executed for the current record.  The rest of the
  4915. current rule's action is not executed either.
  4916.    Contrast this with the effect of the `getline' function (*note
  4917. Explicit Input with `getline': Getline.).  That too causes `awk' to
  4918. read the next record immediately, but it does not alter the flow of
  4919. control in any way.  So the rest of the current action executes with a
  4920. new input record.
  4921.    At the highest level, `awk' program execution is a loop that reads
  4922. an input record and then tests each rule's pattern against it.  If you
  4923. think of this loop as a `for' statement whose body contains the rules,
  4924. then the `next' statement is analogous to a `continue' statement: it
  4925. skips to the end of the body of this implicit loop, and executes the
  4926. increment (which reads another record).
  4927.    For example, if your `awk' program works only on records with four
  4928. fields, and you don't want it to fail when given bad input, you might
  4929. use this rule near the beginning of the program:
  4930.      NF != 4 {
  4931.        err = sprintf("%s:%d: skipped: NF != 4\n", FILENAME, FNR)
  4932.        print err > "/dev/stderr"
  4933.        next
  4934.      }
  4935. so that the following rules will not see the bad record.  The error
  4936. message is redirected to the standard error output stream, as error
  4937. messages should be.  *Note Special File Names in `gawk': Special Files.
  4938.    According to the POSIX standard, the behavior is undefined if the
  4939. `next' statement is used in a `BEGIN' or `END' rule.  `gawk' will treat
  4940. it as a syntax error.  Although POSIX permits it, some other `awk'
  4941. implementations don't allow the `next' statement inside function bodies
  4942. (*note User-defined Functions: User-defined.).  Just as any other
  4943. `next' statement, a `next' inside a function body reads the next record
  4944. and starts processing it with the first rule in the program.
  4945.    If the `next' statement causes the end of the input to be reached,
  4946. then the code in any `END' rules will be executed.  *Note The `BEGIN'
  4947. and `END' Special Patterns: BEGIN/END.
  4948.    *Caution:* Some `awk' implementations generate a run-time error if
  4949. you use the `next' statement inside a user-defined function (*note
  4950. User-defined Functions: User-defined.).  `gawk' does not have this
  4951. problem.
  4952. File: gawk.info,  Node: Nextfile Statement,  Next: Exit Statement,  Prev: Next Statement,  Up: Statements
  4953. The `nextfile' Statement
  4954. ========================
  4955.    `gawk' provides the `nextfile' statement, which is similar to the
  4956. `next' statement.  However, instead of abandoning processing of the
  4957. current record, the `nextfile' statement instructs `gawk' to stop
  4958. processing the current data file.
  4959.    Upon execution of the `nextfile' statement, `FILENAME' is updated to
  4960. the name of the next data file listed on the command line, `FNR' is
  4961. reset to one, `ARGIND' is incremented, and processing starts over with
  4962. the first rule in the progam.  *Note Built-in Variables::.
  4963.    If the `nextfile' statement causes the end of the input to be
  4964. reached, then the code in any `END' rules will be executed.  *Note The
  4965. `BEGIN' and `END' Special Patterns: BEGIN/END.
  4966.    The `nextfile' statement is a `gawk' extension; it is not
  4967. (currently) available in any other `awk' implementation.  *Note
  4968. Implementing `nextfile' as a Function: Nextfile Function, for a
  4969. user-defined function you can use to simulate the `nextfile' statement.
  4970.    The `nextfile' statement would be useful if you have many data files
  4971. to process, and you expect that you would not want to process every
  4972. record in every file.  Normally, in order to move on to the next data
  4973. file, you would have to continue scanning the unwanted records.  The
  4974. `nextfile' statement accomplishes this much more efficiently.
  4975.    *Caution:*  Versions of `gawk' prior to 3.0 used two words (`next
  4976. file') for the `nextfile' statement.  This was changed in 3.0 to one
  4977. word, since the treatment of `file' was inconsistent. When it appeared
  4978. after `next', it was a keyword.  Otherwise, it was a regular
  4979. identifier.  The old usage is still accepted. However, `gawk' will
  4980. generate a warning message, and support for `next file' will eventually
  4981. be discontinued in a future version of `gawk'.
  4982. File: gawk.info,  Node: Exit Statement,  Prev: Nextfile Statement,  Up: Statements
  4983. The `exit' Statement
  4984. ====================
  4985.    The `exit' statement causes `awk' to immediately stop executing the
  4986. current rule and to stop processing input; any remaining input is
  4987. ignored.  It looks like this:
  4988.      exit [RETURN CODE]
  4989.    If an `exit' statement is executed from a `BEGIN' rule the program
  4990. stops processing everything immediately.  No input records are read.
  4991. However, if an `END' rule is present, it is executed (*note The `BEGIN'
  4992. and `END' Special Patterns: BEGIN/END.).
  4993.    If `exit' is used as part of an `END' rule, it causes the program to
  4994. stop immediately.
  4995.    An `exit' statement that is not part of a `BEGIN' or `END' rule
  4996. stops the execution of any further automatic rules for the current
  4997. record, skips reading any remaining input records, and executes the
  4998. `END' rule if there is one.
  4999.    If you do not want the `END' rule to do its job in this case, you
  5000. can set a variable to non-zero before the `exit' statement, and check
  5001. that variable in the `END' rule.  *Note Assertions: Assert Function,
  5002. for an example that does this.
  5003.    If an argument is supplied to `exit', its value is used as the exit
  5004. status code for the `awk' process.  If no argument is supplied, `exit'
  5005. returns status zero (success).  In the case where an argument is
  5006. supplied to a first `exit' statement, and then `exit' is called a
  5007. second time with no argument, the previously supplied exit value is
  5008. used (d.c.).
  5009.    For example, let's say you've discovered an error condition you
  5010. really don't know how to handle.  Conventionally, programs report this
  5011. by exiting with a non-zero status.  Your `awk' program can do this
  5012. using an `exit' statement with a non-zero argument.  Here is an example:
  5013.      BEGIN {
  5014.             if (("date" | getline date_now) < 0) {
  5015.               print "Can't get system date" > "/dev/stderr"
  5016.               exit 1
  5017.             }
  5018.             print "current date is", date_now
  5019.             close("date")
  5020.      }
  5021. File: gawk.info,  Node: Built-in Variables,  Next: Arrays,  Prev: Statements,  Up: Top
  5022. Built-in Variables
  5023. ******************
  5024.    Most `awk' variables are available for you to use for your own
  5025. purposes; they never change except when your program assigns values to
  5026. them, and never affect anything except when your program examines them.
  5027. However, a few variables in `awk' have special built-in meanings.  Some
  5028. of them `awk' examines automatically, so that they enable you to tell
  5029. `awk' how to do certain things.  Others are set automatically by `awk',
  5030. so that they carry information from the internal workings of `awk' to
  5031. your program.
  5032.    This chapter documents all the built-in variables of `gawk'.  Most
  5033. of them are also documented in the chapters describing their areas of
  5034. activity.
  5035. * Menu:
  5036. * User-modified::               Built-in variables that you change to control
  5037.                                 `awk'.
  5038. * Auto-set::                    Built-in variables where `awk' gives you
  5039.                                 information.
  5040. * ARGC and ARGV::               Ways to use `ARGC' and `ARGV'.
  5041. File: gawk.info,  Node: User-modified,  Next: Auto-set,  Prev: Built-in Variables,  Up: Built-in Variables
  5042. Built-in Variables that Control `awk'
  5043. =====================================
  5044.    This is an alphabetical list of the variables which you can change to
  5045. control how `awk' does certain things. Those variables that are
  5046. specific to `gawk' are marked with an asterisk, `*'.
  5047. `CONVFMT'
  5048.      This string controls conversion of numbers to strings (*note
  5049.      Conversion of Strings and Numbers: Conversion.).  It works by
  5050.      being passed, in effect, as the first argument to the `sprintf'
  5051.      function (*note Built-in Functions for String Manipulation: String
  5052.      Functions.).  Its default value is `"%.6g"'.  `CONVFMT' was
  5053.      introduced by the POSIX standard.
  5054. `FIELDWIDTHS *'
  5055.      This is a space separated list of columns that tells `gawk' how to
  5056.      split input with fixed, columnar boundaries.  It is an
  5057.      experimental feature.  Assigning to `FIELDWIDTHS' overrides the
  5058.      use of `FS' for field splitting.  *Note Reading Fixed-width Data:
  5059.      Constant Size, for more information.
  5060.      If `gawk' is in compatibility mode (*note Command Line Options:
  5061.      Options.), then `FIELDWIDTHS' has no special meaning, and field
  5062.      splitting operations are done based exclusively on the value of
  5063.      `FS'.
  5064.      `FS' is the input field separator (*note Specifying How Fields are
  5065.      Separated: Field Separators.).  The value is a single-character
  5066.      string or a multi-character regular expression that matches the
  5067.      separations between fields in an input record.  If the value is
  5068.      the null string (`""'), then each character in the record becomes
  5069.      a separate field.
  5070.      The default value is `" "', a string consisting of a single space.
  5071.      As a special exception, this value means that any sequence of
  5072.      spaces, tabs, and/or newlines is a single separator.(1)  It also
  5073.      causes spaces, tabs, and newlines at the beginning and end of a
  5074.      record to be ignored.
  5075.      You can set the value of `FS' on the command line using the `-F'
  5076.      option:
  5077.           awk -F, 'PROGRAM' INPUT-FILES
  5078.      If `gawk' is using `FIELDWIDTHS' for field-splitting, assigning a
  5079.      value to `FS' will cause `gawk' to return to the normal,
  5080.      `FS'-based, field splitting. An easy way to do this is to simply
  5081.      say `FS = FS', perhaps with an explanatory comment.
  5082. `IGNORECASE *'
  5083.      If `IGNORECASE' is non-zero or non-null, then all string
  5084.      comparisons, and all regular expression matching are
  5085.      case-independent.  Thus, regexp matching with `~' and `!~', and
  5086.      the `gensub', `gsub', `index', `match', `split' and `sub'
  5087.      functions, record termination with `RS', and field splitting with
  5088.      `FS' all ignore case when doing their particular regexp operations.
  5089.      The value of `IGNORECASE' does *not* affect array subscripting.
  5090.      *Note Case-sensitivity in Matching: Case-sensitivity.
  5091.      If `gawk' is in compatibility mode (*note Command Line Options:
  5092.      Options.), then `IGNORECASE' has no special meaning, and string
  5093.      and regexp operations are always case-sensitive.
  5094. `OFMT'
  5095.      This string controls conversion of numbers to strings (*note
  5096.      Conversion of Strings and Numbers: Conversion.) for printing with
  5097.      the `print' statement.  It works by being passed, in effect, as
  5098.      the first argument to the `sprintf' function (*note Built-in
  5099.      Functions for String Manipulation: String Functions.).  Its
  5100.      default value is `"%.6g"'.  Earlier versions of `awk' also used
  5101.      `OFMT' to specify the format for converting numbers to strings in
  5102.      general expressions; this is now done by `CONVFMT'.
  5103. `OFS'
  5104.      This is the output field separator (*note Output Separators::.).
  5105.      It is output between the fields output by a `print' statement.  Its
  5106.      default value is `" "', a string consisting of a single space.
  5107. `ORS'
  5108.      This is the output record separator.  It is output at the end of
  5109.      every `print' statement.  Its default value is `"\n"'.  (*Note
  5110.      Output Separators::.)
  5111.      This is `awk''s input record separator.  Its default value is a
  5112.      string containing a single newline character, which means that an
  5113.      input record consists of a single line of text.  It can also be
  5114.      the null string, in which case records are separated by runs of
  5115.      blank lines, or a regexp, in which case records are separated by
  5116.      matches of the regexp in the input text.  (*Note How Input is
  5117.      Split into Records: Records.)
  5118. `SUBSEP'
  5119.      `SUBSEP' is the subscript separator.  It has the default value of
  5120.      `"\034"', and is used to separate the parts of the indices of a
  5121.      multi-dimensional array.  Thus, the expression `foo["A", "B"]'
  5122.      really accesses `foo["A\034B"]' (*note Multi-dimensional Arrays:
  5123.      Multi-dimensional.).
  5124.    ---------- Footnotes ----------
  5125.    (1)  In POSIX `awk', newline does not count as whitespace.
  5126. File: gawk.info,  Node: Auto-set,  Next: ARGC and ARGV,  Prev: User-modified,  Up: Built-in Variables
  5127. Built-in Variables that Convey Information
  5128. ==========================================
  5129.    This is an alphabetical list of the variables that are set
  5130. automatically by `awk' on certain occasions in order to provide
  5131. information to your program.  Those variables that are specific to
  5132. `gawk' are marked with an asterisk, `*'.
  5133. `ARGC'
  5134. `ARGV'
  5135.      The command-line arguments available to `awk' programs are stored
  5136.      in an array called `ARGV'.  `ARGC' is the number of command-line
  5137.      arguments present.  *Note Other Command Line Arguments: Other
  5138.      Arguments.  Unlike most `awk' arrays, `ARGV' is indexed from zero
  5139.      to `ARGC' - 1.  For example:
  5140.           $ awk 'BEGIN {
  5141.           >        for (i = 0; i < ARGC; i++)
  5142.           >            print ARGV[i]
  5143.           >      }' inventory-shipped BBS-list
  5144.           -| awk
  5145.           -| inventory-shipped
  5146.           -| BBS-list
  5147.      In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
  5148.      `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.  The
  5149.      value of `ARGC' is three, one more than the index of the last
  5150.      element in `ARGV', since the elements are numbered from zero.
  5151.      The names `ARGC' and `ARGV', as well as the convention of indexing
  5152.      the array from zero to `ARGC' - 1, are derived from the C
  5153.      language's method of accessing command line arguments.  *Note
  5154.      Using `ARGC' and `ARGV': ARGC and ARGV, for information about how
  5155.      `awk' uses these variables.
  5156. `ARGIND *'
  5157.      The index in `ARGV' of the current file being processed.  Every
  5158.      time `gawk' opens a new data file for processing, it sets `ARGIND'
  5159.      to the index in `ARGV' of the file name.  When `gawk' is
  5160.      processing the input files, it is always true that `FILENAME ==
  5161.      ARGV[ARGIND]'.
  5162.      This variable is useful in file processing; it allows you to tell
  5163.      how far along you are in the list of data files, and to
  5164.      distinguish between successive instances of the same filename on
  5165.      the command line.
  5166.      While you can change the value of `ARGIND' within your `awk'
  5167.      program, `gawk' will automatically set it to a new value when the
  5168.      next file is opened.
  5169.      This variable is a `gawk' extension. In other `awk'
  5170.      implementations, or if `gawk' is in compatibility mode (*note
  5171.      Command Line Options: Options.), it is not special.
  5172. `ENVIRON'
  5173.      An associative array that contains the values of the environment.
  5174.      The array indices are the environment variable names; the values
  5175.      are the values of the particular environment variables.  For
  5176.      example, `ENVIRON["HOME"]' might be `/home/arnold'.  Changing this
  5177.      array does not affect the environment passed on to any programs
  5178.      that `awk' may spawn via redirection or the `system' function.
  5179.      (In a future version of `gawk', it may do so.)
  5180.      Some operating systems may not have environment variables.  On
  5181.      such systems, the `ENVIRON' array is empty (except for
  5182.      `ENVIRON["AWKPATH"]').
  5183. `ERRNO *'
  5184.      If a system error occurs either doing a redirection for `getline',
  5185.      during a read for `getline', or during a `close' operation, then
  5186.      `ERRNO' will contain a string describing the error.
  5187.      This variable is a `gawk' extension. In other `awk'
  5188.      implementations, or if `gawk' is in compatibility mode (*note
  5189.      Command Line Options: Options.), it is not special.
  5190. `FILENAME'
  5191.      This is the name of the file that `awk' is currently reading.
  5192.      When no data files are listed on the command line, `awk' reads
  5193.      from the standard input, and `FILENAME' is set to `"-"'.
  5194.      `FILENAME' is changed each time a new file is read (*note Reading
  5195.      Input Files: Reading Files.).  Inside a `BEGIN' rule, the value of
  5196.      `FILENAME' is `""', since there are no input files being processed
  5197.      yet.(1) (d.c.)
  5198. `FNR'
  5199.      `FNR' is the current record number in the current file.  `FNR' is
  5200.      incremented each time a new record is read (*note Explicit Input
  5201.      with `getline': Getline.).  It is reinitialized to zero each time
  5202.      a new input file is started.
  5203.      `NF' is the number of fields in the current input record.  `NF' is
  5204.      set each time a new record is read, when a new field is created,
  5205.      or when `$0' changes (*note Examining Fields: Fields.).
  5206.      This is the number of input records `awk' has processed since the
  5207.      beginning of the program's execution (*note How Input is Split
  5208.      into Records: Records.).  `NR' is set each time a new record is
  5209.      read.
  5210. `RLENGTH'
  5211.      `RLENGTH' is the length of the substring matched by the `match'
  5212.      function (*note Built-in Functions for String Manipulation: String
  5213.      Functions.).  `RLENGTH' is set by invoking the `match' function.
  5214.      Its value is the length of the matched string, or -1 if no match
  5215.      was found.
  5216. `RSTART'
  5217.      `RSTART' is the start-index in characters of the substring matched
  5218.      by the `match' function (*note Built-in Functions for String
  5219.      Manipulation: String Functions.).  `RSTART' is set by invoking the
  5220.      `match' function.  Its value is the position of the string where
  5221.      the matched substring starts, or zero if no match was found.
  5222. `RT *'
  5223.      `RT' is set each time a record is read. It contains the input text
  5224.      that matched the text denoted by `RS', the record separator.
  5225.      This variable is a `gawk' extension. In other `awk'
  5226.      implementations, or if `gawk' is in compatibility mode (*note
  5227.      Command Line Options: Options.), it is not special.
  5228.    A side note about `NR' and `FNR'.  `awk' simply increments both of
  5229. these variables each time it reads a record, instead of setting them to
  5230. the absolute value of the number of records read.  This means that your
  5231. program can change these variables, and their new values will be
  5232. incremented for each record (d.c.).  For example:
  5233.      $ echo '1
  5234.      > 2
  5235.      > 3
  5236.      > 4' | awk 'NR == 2 { NR = 17 }
  5237.      > { print NR }'
  5238.      -| 1
  5239.      -| 17
  5240.      -| 18
  5241.      -| 19
  5242. Before `FNR' was added to the `awk' language (*note Major Changes
  5243. between V7 and SVR3.1: V7/SVR3.1.), many `awk' programs used this
  5244. feature to track the number of records in a file by resetting `NR' to
  5245. zero when `FILENAME' changed.
  5246.    ---------- Footnotes ----------
  5247.    (1)  Some early implementations of Unix `awk' initialized `FILENAME'
  5248. to `"-"', even if there were data files to be processed. This behavior
  5249. was incorrect, and should not be relied upon in your programs.
  5250. File: gawk.info,  Node: ARGC and ARGV,  Prev: Auto-set,  Up: Built-in Variables
  5251. Using `ARGC' and `ARGV'
  5252. =======================
  5253.    In *Note Built-in Variables that Convey Information: Auto-set, you
  5254. saw this program describing the information contained in `ARGC' and
  5255. `ARGV':
  5256.      $ awk 'BEGIN {
  5257.      >        for (i = 0; i < ARGC; i++)
  5258.      >            print ARGV[i]
  5259.      >      }' inventory-shipped BBS-list
  5260.      -| awk
  5261.      -| inventory-shipped
  5262.      -| BBS-list
  5263. In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
  5264. `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.
  5265.    Notice that the `awk' program is not entered in `ARGV'.  The other
  5266. special command line options, with their arguments, are also not
  5267. entered.  But variable assignments on the command line *are* treated as
  5268. arguments, and do show up in the `ARGV' array.
  5269.    Your program can alter `ARGC' and the elements of `ARGV'.  Each time
  5270. `awk' reaches the end of an input file, it uses the next element of
  5271. `ARGV' as the name of the next input file.  By storing a different
  5272. string there, your program can change which files are read.  You can
  5273. use `"-"' to represent the standard input.  By storing additional
  5274. elements and incrementing `ARGC' you can cause additional files to be
  5275. read.
  5276.    If you decrease the value of `ARGC', that eliminates input files
  5277. from the end of the list.  By recording the old value of `ARGC'
  5278. elsewhere, your program can treat the eliminated arguments as something
  5279. other than file names.
  5280.    To eliminate a file from the middle of the list, store the null
  5281. string (`""') into `ARGV' in place of the file's name.  As a special
  5282. feature, `awk' ignores file names that have been replaced with the null
  5283. string.  You may also use the `delete' statement to remove elements from
  5284. `ARGV' (*note The `delete' Statement: Delete.).
  5285.    All of these actions are typically done from the `BEGIN' rule,
  5286. before actual processing of the input begins.  *Note Splitting a Large
  5287. File Into Pieces: Split Program, and see *Note Duplicating Output Into
  5288. Multiple Files: Tee Program, for an example of each way of removing
  5289. elements from `ARGV'.
  5290.    The following fragment processes `ARGV' in order to examine, and
  5291. then remove, command line options.
  5292.      BEGIN {
  5293.          for (i = 1; i < ARGC; i++) {
  5294.              if (ARGV[i] == "-v")
  5295.                  verbose = 1
  5296.              else if (ARGV[i] == "-d")
  5297.                  debug = 1
  5298.              else if (ARGV[i] ~ /^-?/) {
  5299.                  e = sprintf("%s: unrecognized option -- %c",
  5300.                          ARGV[0], substr(ARGV[i], 1, ,1))
  5301.                  print e > "/dev/stderr"
  5302.              } else
  5303.                  break
  5304.              delete ARGV[i]
  5305.          }
  5306.      }
  5307.    To actually get the options into the `awk' program, you have to end
  5308. the `awk' options with `--', and then supply your options, like so:
  5309.      awk -f myprog -- -v -d file1 file2 ...
  5310.    This is not necessary in `gawk': Unless `--posix' has been
  5311. specified, `gawk' silently puts any unrecognized options into `ARGV'
  5312. for the `awk' program to deal with.
  5313.    As soon as it sees an unknown option, `gawk' stops looking for other
  5314. options it might otherwise recognize.  The above example with `gawk'
  5315. would be:
  5316.      gawk -f myprog -d -v file1 file2 ...
  5317. Since `-d' is not a valid `gawk' option, the following `-v' is passed
  5318. on to the `awk' program.
  5319. File: gawk.info,  Node: Arrays,  Next: Built-in,  Prev: Built-in Variables,  Up: Top
  5320. Arrays in `awk'
  5321. ***************
  5322.    An "array" is a table of values, called "elements".  The elements of
  5323. an array are distinguished by their indices.  "Indices" may be either
  5324. numbers or strings.  `awk' maintains a single set of names that may be
  5325. used for naming variables, arrays and functions (*note User-defined
  5326. Functions: User-defined.).  Thus, you cannot have a variable and an
  5327. array with the same name in the same `awk' program.
  5328. * Menu:
  5329. * Array Intro::                 Introduction to Arrays
  5330. * Reference to Elements::       How to examine one element of an array.
  5331. * Assigning Elements::          How to change an element of an array.
  5332. * Array Example::               Basic Example of an Array
  5333. * Scanning an Array::           A variation of the `for' statement. It
  5334.                                 loops through the indices of an array's
  5335.                                 existing elements.
  5336. * Delete::                      The `delete' statement removes an element
  5337.                                 from an array.
  5338. * Numeric Array Subscripts::    How to use numbers as subscripts in
  5339.                                 `awk'.
  5340. * Uninitialized Subscripts::    Using Uninitialized variables as subscripts.
  5341. * Multi-dimensional::           Emulating multi-dimensional arrays in
  5342.                                 `awk'.
  5343. * Multi-scanning::              Scanning multi-dimensional arrays.
  5344. File: gawk.info,  Node: Array Intro,  Next: Reference to Elements,  Prev: Arrays,  Up: Arrays
  5345. Introduction to Arrays
  5346. ======================
  5347.    The `awk' language provides one-dimensional "arrays" for storing
  5348. groups of related strings or numbers.
  5349.    Every `awk' array must have a name.  Array names have the same
  5350. syntax as variable names; any valid variable name would also be a valid
  5351. array name.  But you cannot use one name in both ways (as an array and
  5352. as a variable) in one `awk' program.
  5353.    Arrays in `awk' superficially resemble arrays in other programming
  5354. languages; but there are fundamental differences.  In `awk', you don't
  5355. need to specify the size of an array before you start to use it.
  5356. Additionally, any number or string in `awk' may be used as an array
  5357. index, not just consecutive integers.
  5358.    In most other languages, you have to "declare" an array and specify
  5359. how many elements or components it contains.  In such languages, the
  5360. declaration causes a contiguous block of memory to be allocated for that
  5361. many elements.  An index in the array usually must be a positive
  5362. integer; for example, the index zero specifies the first element in the
  5363. array, which is actually stored at the beginning of the block of
  5364. memory.  Index one specifies the second element, which is stored in
  5365. memory right after the first element, and so on.  It is impossible to
  5366. add more elements to the array, because it has room for only as many
  5367. elements as you declared.  (Some languages allow arbitrary starting and
  5368. ending indices, e.g., `15 .. 27', but the size of the array is still
  5369. fixed when the array is declared.)
  5370.    A contiguous array of four elements might look like this,
  5371. conceptually, if the element values are eight, `"foo"', `""' and 30:
  5372.      +---------+---------+--------+---------+
  5373.      |    8    |  "foo"  |   ""   |    30   |    value
  5374.      +---------+---------+--------+---------+
  5375.           0         1         2         3        index
  5376. Only the values are stored; the indices are implicit from the order of
  5377. the values.  Eight is the value at index zero, because eight appears in
  5378. the position with zero elements before it.
  5379.    Arrays in `awk' are different: they are "associative".  This means
  5380. that each array is a collection of pairs: an index, and its
  5381. corresponding array element value:
  5382.      Element 4     Value 30
  5383.      Element 2     Value "foo"
  5384.      Element 1     Value 8
  5385.      Element 3     Value ""
  5386. We have shown the pairs in jumbled order because their order is
  5387. irrelevant.
  5388.    One advantage of associative arrays is that new pairs can be added
  5389. at any time.  For example, suppose we add to the above array a tenth
  5390. element whose value is `"number ten"'.  The result is this:
  5391.      Element 10    Value "number ten"
  5392.      Element 4     Value 30
  5393.      Element 2     Value "foo"
  5394.      Element 1     Value 8
  5395.      Element 3     Value ""
  5396. Now the array is "sparse", which just means some indices are missing:
  5397. it has elements 1-4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.
  5398.    Another consequence of associative arrays is that the indices don't
  5399. have to be positive integers.  Any number, or even a string, can be an
  5400. index.  For example, here is an array which translates words from
  5401. English into French:
  5402.      Element "dog" Value "chien"
  5403.      Element "cat" Value "chat"
  5404.      Element "one" Value "un"
  5405.      Element 1     Value "un"
  5406. Here we decided to translate the number one in both spelled-out and
  5407. numeric form--thus illustrating that a single array can have both
  5408. numbers and strings as indices.  (In fact, array subscripts are always
  5409. strings; this is discussed in more detail in *Note Using Numbers to
  5410. Subscript Arrays: Numeric Array Subscripts.)
  5411.    The value of `IGNORECASE' has no effect upon array subscripting.
  5412. You must use the exact same string value to retrieve an array element
  5413. as you used to store it.
  5414.    When `awk' creates an array for you, e.g., with the `split' built-in
  5415. function, that array's indices are consecutive integers starting at one.
  5416. (*Note Built-in Functions for String Manipulation: String Functions.)
  5417. File: gawk.info,  Node: Reference to Elements,  Next: Assigning Elements,  Prev: Array Intro,  Up: Arrays
  5418. Referring to an Array Element
  5419. =============================
  5420.    The principal way of using an array is to refer to one of its
  5421. elements.  An array reference is an expression which looks like this:
  5422.      ARRAY[INDEX]
  5423. Here, ARRAY is the name of an array.  The expression INDEX is the index
  5424. of the element of the array that you want.
  5425.    The value of the array reference is the current value of that array
  5426. element.  For example, `foo[4.3]' is an expression for the element of
  5427. array `foo' at index `4.3'.
  5428.    If you refer to an array element that has no recorded value, the
  5429. value of the reference is `""', the null string.  This includes elements
  5430. to which you have not assigned any value, and elements that have been
  5431. deleted (*note The `delete' Statement: Delete.).  Such a reference
  5432. automatically creates that array element, with the null string as its
  5433. value.  (In some cases, this is unfortunate, because it might waste
  5434. memory inside `awk'.)
  5435.    You can find out if an element exists in an array at a certain index
  5436. with the expression:
  5437.      INDEX in ARRAY
  5438. This expression tests whether or not the particular index exists,
  5439. without the side effect of creating that element if it is not present.
  5440. The expression has the value one (true) if `ARRAY[INDEX]' exists, and
  5441. zero (false) if it does not exist.
  5442.    For example, to test whether the array `frequencies' contains the
  5443. index `2', you could write this statement:
  5444.      if (2 in frequencies)
  5445.          print "Subscript 2 is present."
  5446.    Note that this is *not* a test of whether or not the array
  5447. `frequencies' contains an element whose *value* is two.  (There is no
  5448. way to do that except to scan all the elements.)  Also, this *does not*
  5449. create `frequencies[2]', while the following (incorrect) alternative
  5450. would do so:
  5451.      if (frequencies[2] != "")
  5452.          print "Subscript 2 is present."
  5453. File: gawk.info,  Node: Assigning Elements,  Next: Array Example,  Prev: Reference to Elements,  Up: Arrays
  5454. Assigning Array Elements
  5455. ========================
  5456.    Array elements are lvalues: they can be assigned values just like
  5457. `awk' variables:
  5458.      ARRAY[SUBSCRIPT] = VALUE
  5459. Here ARRAY is the name of your array.  The expression SUBSCRIPT is the
  5460. index of the element of the array that you want to assign a value.  The
  5461. expression VALUE is the value you are assigning to that element of the
  5462. array.
  5463. File: gawk.info,  Node: Array Example,  Next: Scanning an Array,  Prev: Assigning Elements,  Up: Arrays
  5464. Basic Array Example
  5465. ===================
  5466.    The following program takes a list of lines, each beginning with a
  5467. line number, and prints them out in order of line number.  The line
  5468. numbers are not in order, however, when they are first read:  they are
  5469. scrambled.  This program sorts the lines by making an array using the
  5470. line numbers as subscripts.  It then prints out the lines in sorted
  5471. order of their numbers.  It is a very simple program, and gets confused
  5472. if it encounters repeated numbers, gaps, or lines that don't begin with
  5473. a number.
  5474.      {
  5475.        if ($1 > max)
  5476.          max = $1
  5477.        arr[$1] = $0
  5478.      }
  5479.      
  5480.      END {
  5481.        for (x = 1; x <= max; x++)
  5482.          print arr[x]
  5483.      }
  5484.    The first rule keeps track of the largest line number seen so far;
  5485. it also stores each line into the array `arr', at an index that is the
  5486. line's number.
  5487.    The second rule runs after all the input has been read, to print out
  5488. all the lines.
  5489.    When this program is run with the following input:
  5490.      5  I am the Five man
  5491.      2  Who are you?  The new number two!
  5492.      4  . . . And four on the floor
  5493.      1  Who is number one?
  5494.      3  I three you.
  5495. its output is this:
  5496.      1  Who is number one?
  5497.      2  Who are you?  The new number two!
  5498.      3  I three you.
  5499.      4  . . . And four on the floor
  5500.      5  I am the Five man
  5501.    If a line number is repeated, the last line with a given number
  5502. overrides the others.
  5503.    Gaps in the line numbers can be handled with an easy improvement to
  5504. the program's `END' rule:
  5505.      END {
  5506.        for (x = 1; x <= max; x++)
  5507.          if (x in arr)
  5508.            print arr[x]
  5509.      }
  5510. File: gawk.info,  Node: Scanning an Array,  Next: Delete,  Prev: Array Example,  Up: Arrays
  5511. Scanning All Elements of an Array
  5512. =================================
  5513.    In programs that use arrays, you often need a loop that executes
  5514. once for each element of an array.  In other languages, where arrays are
  5515. contiguous and indices are limited to positive integers, this is easy:
  5516. you can find all the valid indices by counting from the lowest index up
  5517. to the highest.  This technique won't do the job in `awk', since any
  5518. number or string can be an array index.  So `awk' has a special kind of
  5519. `for' statement for scanning an array:
  5520.      for (VAR in ARRAY)
  5521.        BODY
  5522. This loop executes BODY once for each index in ARRAY that your program
  5523. has previously used, with the variable VAR set to that index.
  5524.    Here is a program that uses this form of the `for' statement.  The
  5525. first rule scans the input records and notes which words appear (at
  5526. least once) in the input, by storing a one into the array `used' with
  5527. the word as index.  The second rule scans the elements of `used' to
  5528. find all the distinct words that appear in the input.  It prints each
  5529. word that is more than 10 characters long, and also prints the number of
  5530. such words.  *Note Built-in Functions for String Manipulation: String
  5531. Functions, for more information on the built-in function `length'.
  5532.      # Record a 1 for each word that is used at least once.
  5533.      {
  5534.          for (i = 1; i <= NF; i++)
  5535.              used[$i] = 1
  5536.      }
  5537.      
  5538.      # Find number of distinct words more than 10 characters long.
  5539.      END {
  5540.          for (x in used)
  5541.              if (length(x) > 10) {
  5542.                  ++num_long_words
  5543.                  print x
  5544.              }
  5545.          print num_long_words, "words longer than 10 characters"
  5546.      }
  5547. *Note Generating Word Usage Counts: Word Sorting, for a more detailed
  5548. example of this type.
  5549.    The order in which elements of the array are accessed by this
  5550. statement is determined by the internal arrangement of the array
  5551. elements within `awk' and cannot be controlled or changed.  This can
  5552. lead to problems if new elements are added to ARRAY by statements in
  5553. the loop body; you cannot predict whether or not the `for' loop will
  5554. reach them.  Similarly, changing VAR inside the loop may produce
  5555. strange results.  It is best to avoid such things.
  5556. File: gawk.info,  Node: Delete,  Next: Numeric Array Subscripts,  Prev: Scanning an Array,  Up: Arrays
  5557. The `delete' Statement
  5558. ======================
  5559.    You can remove an individual element of an array using the `delete'
  5560. statement:
  5561.      delete ARRAY[INDEX]
  5562.    Once you have deleted an array element, you can no longer obtain any
  5563. value the element once had.  It is as if you had never referred to it
  5564. and had never given it any value.
  5565.    Here is an example of deleting elements in an array:
  5566.      for (i in frequencies)
  5567.        delete frequencies[i]
  5568. This example removes all the elements from the array `frequencies'.
  5569.    If you delete an element, a subsequent `for' statement to scan the
  5570. array will not report that element, and the `in' operator to check for
  5571. the presence of that element will return zero (i.e. false):
  5572.      delete foo[4]
  5573.      if (4 in foo)
  5574.          print "This will never be printed"
  5575.    It is important to note that deleting an element is *not* the same
  5576. as assigning it a null value (the empty string, `""').
  5577.      foo[4] = ""
  5578.      if (4 in foo)
  5579.        print "This is printed, even though foo[4] is empty"
  5580.    It is not an error to delete an element that does not exist.
  5581.    You can delete all the elements of an array with a single statement,
  5582. by leaving off the subscript in the `delete' statement.
  5583.      delete ARRAY
  5584.    This ability is a `gawk' extension; it is not available in
  5585. compatibility mode (*note Command Line Options: Options.).
  5586.    Using this version of the `delete' statement is about three times
  5587. more efficient than the equivalent loop that deletes each element one
  5588. at a time.
  5589.    The following statement provides a portable, but non-obvious way to
  5590. clear out an array.
  5591.      # thanks to Michael Brennan for pointing this out
  5592.      split("", array)
  5593.    The `split' function (*note Built-in Functions for String
  5594. Manipulation: String Functions.) clears out the target array first.
  5595. This call asks it to split apart the null string. Since there is no
  5596. data to split out, the function simply clears the array and then
  5597. returns.
  5598. File: gawk.info,  Node: Numeric Array Subscripts,  Next: Uninitialized Subscripts,  Prev: Delete,  Up: Arrays
  5599. Using Numbers to Subscript Arrays
  5600. =================================
  5601.    An important aspect of arrays to remember is that *array subscripts
  5602. are always strings*.  If you use a numeric value as a subscript, it
  5603. will be converted to a string value before it is used for subscripting
  5604. (*note Conversion of Strings and Numbers: Conversion.).
  5605.    This means that the value of the built-in variable `CONVFMT' can
  5606. potentially affect how your program accesses elements of an array.  For
  5607. example:
  5608.      xyz = 12.153
  5609.      data[xyz] = 1
  5610.      CONVFMT = "%2.2f"
  5611.      if (xyz in data)
  5612.          printf "%s is in data\n", xyz
  5613.      else
  5614.          printf "%s is not in data\n", xyz
  5615. This prints `12.15 is not in data'.  The first statement gives `xyz' a
  5616. numeric value.  Assigning to `data[xyz]' subscripts `data' with the
  5617. string value `"12.153"' (using the default conversion value of
  5618. `CONVFMT', `"%.6g"'), and assigns one to `data["12.153"]'.  The program
  5619. then changes the value of `CONVFMT'.  The test `(xyz in data)'
  5620. generates a new string value from `xyz', this time `"12.15"', since the
  5621. value of `CONVFMT' only allows two significant digits.  This test fails,
  5622. since `"12.15"' is a different string from `"12.153"'.
  5623.    According to the rules for conversions (*note Conversion of Strings
  5624. and Numbers: Conversion.), integer values are always converted to
  5625. strings as integers, no matter what the value of `CONVFMT' may happen
  5626. to be.  So the usual case of:
  5627.      for (i = 1; i <= maxsub; i++)
  5628.          do something with array[i]
  5629. will work, no matter what the value of `CONVFMT'.
  5630.    Like many things in `awk', the majority of the time things work as
  5631. you would expect them to work.  But it is useful to have a precise
  5632. knowledge of the actual rules, since sometimes they can have a subtle
  5633. effect on your programs.
  5634. File: gawk.info,  Node: Uninitialized Subscripts,  Next: Multi-dimensional,  Prev: Numeric Array Subscripts,  Up: Arrays
  5635. Using Uninitialized Variables as Subscripts
  5636. ===========================================
  5637.    Suppose you want to print your input data in reverse order.  A
  5638. reasonable attempt at a program to do so (with some test data) might
  5639. look like this:
  5640.      $ echo 'line 1
  5641.      > line 2
  5642.      > line 3' | awk '{ l[lines] = $0; ++lines }
  5643.      > END {
  5644.      >     for (i = lines-1; i >= 0; --i)
  5645.      >        print l[i]
  5646.      > }'
  5647.      -| line 3
  5648.      -| line 2
  5649.    Unfortunately, the very first line of input data did not come out in
  5650. the output!
  5651.    At first glance, this program should have worked.  The variable
  5652. `lines' is uninitialized, and uninitialized variables have the numeric
  5653. value zero.  So, the value of `l[0]' should have been printed.
  5654.    The issue here is that subscripts for `awk' arrays are *always*
  5655. strings. And uninitialized variables, when used as strings, have the
  5656. value `""', not zero.  Thus, `line 1' ended up stored in `l[""]'.
  5657.    The following version of the program works correctly:
  5658.      { l[lines++] = $0 }
  5659.      END {
  5660.          for (i = lines - 1; i >= 0; --i)
  5661.             print l[i]
  5662.      }
  5663.    Here, the `++' forces `lines' to be numeric, thus making the "old
  5664. value" numeric zero, which is then converted to `"0"' as the array
  5665. subscript.
  5666.    As we have just seen, even though it is somewhat unusual, the null
  5667. string (`""') is a valid array subscript (d.c.). If `--lint' is provided
  5668. on the command line (*note Command Line Options: Options.), `gawk' will
  5669. warn about the use of the null string as a subscript.
  5670. File: gawk.info,  Node: Multi-dimensional,  Next: Multi-scanning,  Prev: Uninitialized Subscripts,  Up: Arrays
  5671. Multi-dimensional Arrays
  5672. ========================
  5673.    A multi-dimensional array is an array in which an element is
  5674. identified by a sequence of indices, instead of a single index.  For
  5675. example, a two-dimensional array requires two indices.  The usual way
  5676. (in most languages, including `awk') to refer to an element of a
  5677. two-dimensional array named `grid' is with `grid[X,Y]'.
  5678.    Multi-dimensional arrays are supported in `awk' through
  5679. concatenation of indices into one string.  What happens is that `awk'
  5680. converts the indices into strings (*note Conversion of Strings and
  5681. Numbers: Conversion.) and concatenates them together, with a separator
  5682. between them.  This creates a single string that describes the values
  5683. of the separate indices.  The combined string is used as a single index
  5684. into an ordinary, one-dimensional array.  The separator used is the
  5685. value of the built-in variable `SUBSEP'.
  5686.    For example, suppose we evaluate the expression `foo[5,12] = "value"'
  5687. when the value of `SUBSEP' is `"@"'.  The numbers five and 12 are
  5688. converted to strings and concatenated with an `@' between them,
  5689. yielding `"5@12"'; thus, the array element `foo["5@12"]' is set to
  5690. `"value"'.
  5691.    Once the element's value is stored, `awk' has no record of whether
  5692. it was stored with a single index or a sequence of indices.  The two
  5693. expressions `foo[5,12]' and `foo[5 SUBSEP 12]' are always equivalent.
  5694.    The default value of `SUBSEP' is the string `"\034"', which contains
  5695. a non-printing character that is unlikely to appear in an `awk' program
  5696. or in most input data.
  5697.    The usefulness of choosing an unlikely character comes from the fact
  5698. that index values that contain a string matching `SUBSEP' lead to
  5699. combined strings that are ambiguous.  Suppose that `SUBSEP' were `"@"';
  5700. then `foo["a@b", "c"]' and `foo["a", "b@c"]' would be indistinguishable
  5701. because both would actually be stored as `foo["a@b@c"]'.
  5702.    You can test whether a particular index-sequence exists in a
  5703. "multi-dimensional" array with the same operator `in' used for single
  5704. dimensional arrays.  Instead of a single index as the left-hand operand,
  5705. write the whole sequence of indices, separated by commas, in
  5706. parentheses:
  5707.      (SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY
  5708.    The following example treats its input as a two-dimensional array of
  5709. fields; it rotates this array 90 degrees clockwise and prints the
  5710. result.  It assumes that all lines have the same number of elements.
  5711.      awk '{
  5712.           if (max_nf < NF)
  5713.                max_nf = NF
  5714.           max_nr = NR
  5715.           for (x = 1; x <= NF; x++)
  5716.                vector[x, NR] = $x
  5717.      }
  5718.      
  5719.      END {
  5720.           for (x = 1; x <= max_nf; x++) {
  5721.                for (y = max_nr; y >= 1; --y)
  5722.                     printf("%s ", vector[x, y])
  5723.                printf("\n")
  5724.           }
  5725.      }'
  5726. When given the input:
  5727.      1 2 3 4 5 6
  5728.      2 3 4 5 6 1
  5729.      3 4 5 6 1 2
  5730.      4 5 6 1 2 3
  5731. it produces:
  5732.      4 3 2 1
  5733.      5 4 3 2
  5734.      6 5 4 3
  5735.      1 6 5 4
  5736.      2 1 6 5
  5737.      3 2 1 6
  5738. File: gawk.info,  Node: Multi-scanning,  Prev: Multi-dimensional,  Up: Arrays
  5739. Scanning Multi-dimensional Arrays
  5740. =================================
  5741.    There is no special `for' statement for scanning a
  5742. "multi-dimensional" array; there cannot be one, because in truth there
  5743. are no multi-dimensional arrays or elements; there is only a
  5744. multi-dimensional *way of accessing* an array.
  5745.    However, if your program has an array that is always accessed as
  5746. multi-dimensional, you can get the effect of scanning it by combining
  5747. the scanning `for' statement (*note Scanning All Elements of an Array:
  5748. Scanning an Array.) with the `split' built-in function (*note Built-in
  5749. Functions for String Manipulation: String Functions.).  It works like
  5750. this:
  5751.      for (combined in array) {
  5752.        split(combined, separate, SUBSEP)
  5753.        ...
  5754.      }
  5755. This sets `combined' to each concatenated, combined index in the array,
  5756. and splits it into the individual indices by breaking it apart where
  5757. the value of `SUBSEP' appears.  The split-out indices become the
  5758. elements of the array `separate'.
  5759.    Thus, suppose you have previously stored a value in `array[1,
  5760. "foo"]'; then an element with index `"1\034foo"' exists in `array'.
  5761. (Recall that the default value of `SUBSEP' is the character with code
  5762. 034.)  Sooner or later the `for' statement will find that index and do
  5763. an iteration with `combined' set to `"1\034foo"'.  Then the `split'
  5764. function is called as follows:
  5765.      split("1\034foo", separate, "\034")
  5766. The result of this is to set `separate[1]' to `"1"' and `separate[2]'
  5767. to `"foo"'.  Presto, the original sequence of separate indices has been
  5768. recovered.
  5769. File: gawk.info,  Node: Built-in,  Next: User-defined,  Prev: Arrays,  Up: Top
  5770. Built-in Functions
  5771. ******************
  5772.    "Built-in" functions are functions that are always available for
  5773. your `awk' program to call.  This chapter defines all the built-in
  5774. functions in `awk'; some of them are mentioned in other sections, but
  5775. they are summarized here for your convenience.  (You can also define
  5776. new functions yourself.  *Note User-defined Functions: User-defined.)
  5777. * Menu:
  5778. * Calling Built-in::            How to call built-in functions.
  5779. * Numeric Functions::           Functions that work with numbers, including
  5780.                                 `int', `sin' and `rand'.
  5781. * String Functions::            Functions for string manipulation, such as
  5782.                                 `split', `match', and
  5783.                                 `sprintf'.
  5784. * I/O Functions::               Functions for files and shell commands.
  5785. * Time Functions::              Functions for dealing with time stamps.
  5786. File: gawk.info,  Node: Calling Built-in,  Next: Numeric Functions,  Prev: Built-in,  Up: Built-in
  5787. Calling Built-in Functions
  5788. ==========================
  5789.    To call a built-in function, write the name of the function followed
  5790. by arguments in parentheses.  For example, `atan2(y + z, 1)' is a call
  5791. to the function `atan2', with two arguments.
  5792.    Whitespace is ignored between the built-in function name and the
  5793. open-parenthesis, but we recommend that you avoid using whitespace
  5794. there.  User-defined functions do not permit whitespace in this way, and
  5795. you will find it easier to avoid mistakes by following a simple
  5796. convention which always works: no whitespace after a function name.
  5797.    Each built-in function accepts a certain number of arguments.  In
  5798. some cases, arguments can be omitted. The defaults for omitted
  5799. arguments vary from function to function and are described under the
  5800. individual functions.  In some `awk' implementations, extra arguments
  5801. given to built-in functions are ignored.  However, in `gawk', it is a
  5802. fatal error to give extra arguments to a built-in function.
  5803.    When a function is called, expressions that create the function's
  5804. actual parameters are evaluated completely before the function call is
  5805. performed.  For example, in the code fragment:
  5806.      i = 4
  5807.      j = sqrt(i++)
  5808. the variable `i' is set to five before `sqrt' is called with a value of
  5809. four for its actual parameter.
  5810.    The order of evaluation of the expressions used for the function's
  5811. parameters is undefined.  Thus, you should not write programs that
  5812. assume that parameters are evaluated from left to right or from right
  5813. to left.  For example,
  5814.      i = 5
  5815.      j = atan2(i++, i *= 2)
  5816.    If the order of evaluation is left to right, then `i' first becomes
  5817. six, and then 12, and `atan2' is called with the two arguments six and
  5818. 12.  But if the order of evaluation is right to left, `i' first becomes
  5819. 10, and then 11, and `atan2' is called with the two arguments 11 and 10.
  5820. File: gawk.info,  Node: Numeric Functions,  Next: String Functions,  Prev: Calling Built-in,  Up: Built-in
  5821. Numeric Built-in Functions
  5822. ==========================
  5823.    Here is a full list of built-in functions that work with numbers.
  5824. Optional parameters are enclosed in square brackets ("[" and "]").
  5825. `int(X)'
  5826.      This produces the nearest integer to X, located between X and zero,
  5827.      truncated toward zero.
  5828.      For example, `int(3)' is three, `int(3.9)' is three, `int(-3.9)'
  5829.      is -3, and `int(-3)' is -3 as well.
  5830. `sqrt(X)'
  5831.      This gives you the positive square root of X.  It reports an error
  5832.      if X is negative.  Thus, `sqrt(4)' is two.
  5833. `exp(X)'
  5834.      This gives you the exponential of X (`e ^ X'), or reports an error
  5835.      if X is out of range.  The range of values X can have depends on
  5836.      your machine's floating point representation.
  5837. `log(X)'
  5838.      This gives you the natural logarithm of X, if X is positive;
  5839.      otherwise, it reports an error.
  5840. `sin(X)'
  5841.      This gives you the sine of X, with X in radians.
  5842. `cos(X)'
  5843.      This gives you the cosine of X, with X in radians.
  5844. `atan2(Y, X)'
  5845.      This gives you the arctangent of `Y / X' in radians.
  5846. `rand()'
  5847.      This gives you a random number.  The values of `rand' are
  5848.      uniformly-distributed between zero and one.  The value is never
  5849.      zero and never one.
  5850.      Often you want random integers instead.  Here is a user-defined
  5851.      function you can use to obtain a random non-negative integer less
  5852.      than N:
  5853.           function randint(n) {
  5854.                return int(n * rand())
  5855.           }
  5856.      The multiplication produces a random real number greater than zero
  5857.      and less than `n'.  We then make it an integer (using `int')
  5858.      between zero and `n' - 1, inclusive.
  5859.      Here is an example where a similar function is used to produce
  5860.      random integers between one and N.  This program prints a new
  5861.      random number for each input record.
  5862.           awk '
  5863.           # Function to roll a simulated die.
  5864.           function roll(n) { return 1 + int(rand() * n) }
  5865.           
  5866.           # Roll 3 six-sided dice and
  5867.           # print total number of points.
  5868.           {
  5869.                 printf("%d points\n",
  5870.                        roll(6)+roll(6)+roll(6))
  5871.           }'
  5872.      *Caution:* In most `awk' implementations, including `gawk', `rand'
  5873.      starts generating numbers from the same starting number, or
  5874.      "seed", each time you run `awk'.  Thus, a program will generate
  5875.      the same results each time you run it.  The numbers are random
  5876.      within one `awk' run, but predictable from run to run.  This is
  5877.      convenient for debugging, but if you want a program to do
  5878.      different things each time it is used, you must change the seed to
  5879.      a value that will be different in each run.  To do this, use
  5880.      `srand'.
  5881. `srand([X])'
  5882.      The function `srand' sets the starting point, or seed, for
  5883.      generating random numbers to the value X.
  5884.      Each seed value leads to a particular sequence of random
  5885.      numbers.(1) Thus, if you set the seed to the same value a second
  5886.      time, you will get the same sequence of random numbers again.
  5887.      If you omit the argument X, as in `srand()', then the current date
  5888.      and time of day are used for a seed.  This is the way to get random
  5889.      numbers that are truly unpredictable.
  5890.      The return value of `srand' is the previous seed.  This makes it
  5891.      easy to keep track of the seeds for use in consistently reproducing
  5892.      sequences of random numbers.
  5893.    ---------- Footnotes ----------
  5894.    (1)  Computer generated random numbers really are not truly random.
  5895. They are technically known as "pseudo-random."  This means that while
  5896. the numbers in a sequence appear to be random, you can in fact generate
  5897. the same sequence of random numbers over and over again.
  5898. File: gawk.info,  Node: String Functions,  Next: I/O Functions,  Prev: Numeric Functions,  Up: Built-in
  5899. Built-in Functions for String Manipulation
  5900. ==========================================
  5901.    The functions in this section look at or change the text of one or
  5902. more strings.  Optional parameters are enclosed in square brackets ("["
  5903. and "]").
  5904. `index(IN, FIND)'
  5905.      This searches the string IN for the first occurrence of the string
  5906.      FIND, and returns the position in characters where that occurrence
  5907.      begins in the string IN.  For example:
  5908.           $ awk 'BEGIN { print index("peanut", "an") }'
  5909.           -| 3
  5910.      If FIND is not found, `index' returns zero.  (Remember that string
  5911.      indices in `awk' start at one.)
  5912. `length([STRING])'
  5913.      This gives you the number of characters in STRING.  If STRING is a
  5914.      number, the length of the digit string representing that number is
  5915.      returned.  For example, `length("abcde")' is five.  By contrast,
  5916.      `length(15 * 35)' works out to three.  How?  Well, 15 * 35 = 525,
  5917.      and 525 is then converted to the string `"525"', which has three
  5918.      characters.
  5919.      If no argument is supplied, `length' returns the length of `$0'.
  5920.      In older versions of `awk', you could call the `length' function
  5921.      without any parentheses.  Doing so is marked as "deprecated" in the
  5922.      POSIX standard.  This means that while you can do this in your
  5923.      programs, it is a feature that can eventually be removed from a
  5924.      future version of the standard.  Therefore, for maximal
  5925.      portability of your `awk' programs, you should always supply the
  5926.      parentheses.
  5927. `match(STRING, REGEXP)'
  5928.      The `match' function searches the string, STRING, for the longest,
  5929.      leftmost substring matched by the regular expression, REGEXP.  It
  5930.      returns the character position, or "index", of where that
  5931.      substring begins (one, if it starts at the beginning of STRING).
  5932.      If no match is found, it returns zero.
  5933.      The `match' function sets the built-in variable `RSTART' to the
  5934.      index.  It also sets the built-in variable `RLENGTH' to the length
  5935.      in characters of the matched substring.  If no match is found,
  5936.      `RSTART' is set to zero, and `RLENGTH' to -1.
  5937.      For example:
  5938.           awk '{
  5939.                  if ($1 == "FIND")
  5940.                    regex = $2
  5941.                  else {
  5942.                    where = match($0, regex)
  5943.                    if (where != 0)
  5944.                      print "Match of", regex, "found at", \
  5945.                                where, "in", $0
  5946.                  }
  5947.           }'
  5948.      This program looks for lines that match the regular expression
  5949.      stored in the variable `regex'.  This regular expression can be
  5950.      changed.  If the first word on a line is `FIND', `regex' is
  5951.      changed to be the second word on that line.  Therefore, given:
  5952.           FIND ru+n
  5953.           My program runs
  5954.           but not very quickly
  5955.           FIND Melvin
  5956.           JF+KM
  5957.           This line is property of Reality Engineering Co.
  5958.           Melvin was here.
  5959.      `awk' prints:
  5960.           Match of ru+n found at 12 in My program runs
  5961.           Match of Melvin found at 1 in Melvin was here.
  5962. `split(STRING, ARRAY [, FIELDSEP])'
  5963.      This divides STRING into pieces separated by FIELDSEP, and stores
  5964.      the pieces in ARRAY.  The first piece is stored in `ARRAY[1]', the
  5965.      second piece in `ARRAY[2]', and so forth.  The string value of the
  5966.      third argument, FIELDSEP, is a regexp describing where to split
  5967.      STRING (much as `FS' can be a regexp describing where to split
  5968.      input records).  If the FIELDSEP is omitted, the value of `FS' is
  5969.      used.  `split' returns the number of elements created.
  5970.      The `split' function splits strings into pieces in a manner
  5971.      similar to the way input lines are split into fields.  For example:
  5972.           split("cul-de-sac", a, "-")
  5973.      splits the string `cul-de-sac' into three fields using `-' as the
  5974.      separator.  It sets the contents of the array `a' as follows:
  5975.           a[1] = "cul"
  5976.           a[2] = "de"
  5977.           a[3] = "sac"
  5978.      The value returned by this call to `split' is three.
  5979.      As with input field-splitting, when the value of FIELDSEP is
  5980.      `" "', leading and trailing whitespace is ignored, and the elements
  5981.      are separated by runs of whitespace.
  5982.      Also as with input field-splitting, if FIELDSEP is the null
  5983.      string, each individual character in the string is split into its
  5984.      own array element.  (This is a `gawk'-specific extension.)
  5985.      Recent implementations of `awk', including `gawk', allow the third
  5986.      argument to be a regexp constant (`/abc/'), as well as a string
  5987.      (d.c.).  The POSIX standard allows this as well.
  5988.      Before splitting the string, `split' deletes any previously
  5989.      existing elements in the array ARRAY (d.c.).
  5990. `sprintf(FORMAT, EXPRESSION1,...)'
  5991.      This returns (without printing) the string that `printf' would
  5992.      have printed out with the same arguments (*note Using `printf'
  5993.      Statements for Fancier Printing: Printf.).  For example:
  5994.           sprintf("pi = %.2f (approx.)", 22/7)
  5995.      returns the string `"pi = 3.14 (approx.)"'.
  5996. `sub(REGEXP, REPLACEMENT [, TARGET])'
  5997.      The `sub' function alters the value of TARGET.  It searches this
  5998.      value, which is treated as a string, for the leftmost longest
  5999.      substring matched by the regular expression, REGEXP, extending
  6000.      this match as far as possible.  Then the entire string is changed
  6001.      by replacing the matched text with REPLACEMENT.  The modified
  6002.      string becomes the new value of TARGET.
  6003.      This function is peculiar because TARGET is not simply used to
  6004.      compute a value, and not just any expression will do: it must be a
  6005.      variable, field or array element, so that `sub' can store a
  6006.      modified value there.  If this argument is omitted, then the
  6007.      default is to use and alter `$0'.
  6008.      For example:
  6009.           str = "water, water, everywhere"
  6010.           sub(/at/, "ith", str)
  6011.      sets `str' to `"wither, water, everywhere"', by replacing the
  6012.      leftmost, longest occurrence of `at' with `ith'.
  6013.      The `sub' function returns the number of substitutions made (either
  6014.      one or zero).
  6015.      If the special character `&' appears in REPLACEMENT, it stands for
  6016.      the precise substring that was matched by REGEXP.  (If the regexp
  6017.      can match more than one string, then this precise substring may
  6018.      vary.)  For example:
  6019.           awk '{ sub(/candidate/, "& and his wife"); print }'
  6020.      changes the first occurrence of `candidate' to `candidate and his
  6021.      wife' on each input line.
  6022.      Here is another example:
  6023.           awk 'BEGIN {
  6024.                   str = "daabaaa"
  6025.                   sub(/a*/, "c&c", str)
  6026.                   print str
  6027.           }'
  6028.           -| dcaacbaaa
  6029.      This shows how `&' can represent a non-constant string, and also
  6030.      illustrates the "leftmost, longest" rule in regexp matching (*note
  6031.      How Much Text Matches?: Leftmost Longest.).
  6032.      The effect of this special character (`&') can be turned off by
  6033.      putting a backslash before it in the string.  As usual, to insert
  6034.      one backslash in the string, you must write two backslashes.
  6035.      Therefore, write `\\&' in a string constant to include a literal
  6036.      `&' in the replacement.  For example, here is how to replace the
  6037.      first `|' on each line with an `&':
  6038.           awk '{ sub(/\|/, "\\&"); print }'
  6039.      *Note:* As mentioned above, the third argument to `sub' must be a
  6040.      variable, field or array reference.  Some versions of `awk' allow
  6041.      the third argument to be an expression which is not an lvalue.  In
  6042.      such a case, `sub' would still search for the pattern and return
  6043.      zero or one, but the result of the substitution (if any) would be
  6044.      thrown away because there is no place to put it.  Such versions of
  6045.      `awk' accept expressions like this:
  6046.           sub(/USA/, "United States", "the USA and Canada")
  6047.      For historical compatibility, `gawk' will accept erroneous code,
  6048.      such as in the above example. However, using any other
  6049.      non-changeable object as the third parameter will cause a fatal
  6050.      error, and your program will not run.
  6051. `gsub(REGEXP, REPLACEMENT [, TARGET])'
  6052.      This is similar to the `sub' function, except `gsub' replaces
  6053.      *all* of the longest, leftmost, *non-overlapping* matching
  6054.      substrings it can find.  The `g' in `gsub' stands for "global,"
  6055.      which means replace everywhere.  For example:
  6056.           awk '{ gsub(/Britain/, "United Kingdom"); print }'
  6057.      replaces all occurrences of the string `Britain' with `United
  6058.      Kingdom' for all input records.
  6059.      The `gsub' function returns the number of substitutions made.  If
  6060.      the variable to be searched and altered, TARGET, is omitted, then
  6061.      the entire input record, `$0', is used.
  6062.      As in `sub', the characters `&' and `\' are special, and the third
  6063.      argument must be an lvalue.
  6064. `gensub(REGEXP, REPLACEMENT, HOW [, TARGET])'
  6065.      `gensub' is a general substitution function.  Like `sub' and
  6066.      `gsub', it searches the target string TARGET for matches of the
  6067.      regular expression REGEXP.  Unlike `sub' and `gsub', the modified
  6068.      string is returned as the result of the function, and the original
  6069.      target string is *not* changed.  If HOW is a string beginning with
  6070.      `g' or `G', then it replaces all matches of REGEXP with
  6071.      REPLACEMENT.  Otherwise, HOW is a number indicating which match of
  6072.      REGEXP to replace. If no TARGET is supplied, `$0' is used instead.
  6073.      `gensub' provides an additional feature that is not available in
  6074.      `sub' or `gsub': the ability to specify components of a regexp in
  6075.      the replacement text.  This is done by using parentheses in the
  6076.      regexp to mark the components, and then specifying `\N' in the
  6077.      replacement text, where N is a digit from one to nine.  For
  6078.      example:
  6079.           $ gawk '
  6080.           > BEGIN {
  6081.           >      a = "abc def"
  6082.           >      b = gensub(/(.+) (.+)/, "\\2 \\1", "g", a)
  6083.           >      print b
  6084.           > }'
  6085.           -| def abc
  6086.      As described above for `sub', you must type two backslashes in
  6087.      order to get one into the string.
  6088.      In the replacement text, the sequence `\0' represents the entire
  6089.      matched text, as does the character `&'.
  6090.      This example shows how you can use the third argument to control
  6091.      which match of the regexp should be changed.
  6092.           $ echo a b c a b c |
  6093.           > gawk '{ print gensub(/a/, "AA", 2) }'
  6094.           -| a b c AA b c
  6095.      In this case, `$0' is used as the default target string.  `gensub'
  6096.      returns the new string as its result, which is passed directly to
  6097.      `print' for printing.
  6098.      If the HOW argument is a string that does not begin with `g' or
  6099.      `G', or if it is a number that is less than zero, only one
  6100.      substitution is performed.
  6101.      `gensub' is a `gawk' extension; it is not available in
  6102.      compatibility mode (*note Command Line Options: Options.).
  6103. `substr(STRING, START [, LENGTH])'
  6104.      This returns a LENGTH-character-long substring of STRING, starting
  6105.      at character number START.  The first character of a string is
  6106.      character number one.  For example, `substr("washington", 5, 3)'
  6107.      returns `"ing"'.
  6108.      If LENGTH is not present, this function returns the whole suffix of
  6109.      STRING that begins at character number START.  For example,
  6110.      `substr("washington", 5)' returns `"ington"'.  The whole suffix is
  6111.      also returned if LENGTH is greater than the number of characters
  6112.      remaining in the string, counting from character number START.
  6113.      *Note:* The string returned by `substr' *cannot* be assigned to.
  6114.      Thus, it is a mistake to attempt to change a portion of a string,
  6115.      like this:
  6116.           string = "abcdef"
  6117.           # try to get "abCDEf", won't work
  6118.           substr(string, 3, 3) = "CDE"
  6119.      or to use `substr' as the third agument of `sub' or `gsub':
  6120.           gsub(/xyz/, "pdq", substr($0, 5, 20))  # WRONG
  6121. `tolower(STRING)'
  6122.      This returns a copy of STRING, with each upper-case character in
  6123.      the string replaced with its corresponding lower-case character.
  6124.      Non-alphabetic characters are left unchanged.  For example,
  6125.      `tolower("MiXeD cAsE 123")' returns `"mixed case 123"'.
  6126. `toupper(STRING)'
  6127.      This returns a copy of STRING, with each lower-case character in
  6128.      the string replaced with its corresponding upper-case character.
  6129.      Non-alphabetic characters are left unchanged.  For example,
  6130.      `toupper("MiXeD cAsE 123")' returns `"MIXED CASE 123"'.
  6131. More About `\' and `&' with `sub', `gsub' and `gensub'
  6132. ------------------------------------------------------
  6133.    When using `sub', `gsub' or `gensub', and trying to get literal
  6134. backslashes and ampersands into the replacement text, you need to
  6135. remember that there are several levels of "escape processing" going on.
  6136.    First, there is the "lexical" level, which is when `awk' reads your
  6137. program, and builds an internal copy of your program that can be
  6138. executed.
  6139.    Then there is the run-time level, when `awk' actually scans the
  6140. replacement string to determine what to generate.
  6141.    At both levels, `awk' looks for a defined set of characters that can
  6142. come after a backslash.  At the lexical level, it looks for the escape
  6143. sequences listed in *Note Escape Sequences::.  Thus, for every `\' that
  6144. `awk' will process at the run-time level, you type two `\'s at the
  6145. lexical level.  When a character that is not valid for an escape
  6146. sequence follows the `\', Unix `awk' and `gawk' both simply remove the
  6147. initial `\', and put the following character into the string. Thus, for
  6148. example, `"a\qb"' is treated as `"aqb"'.
  6149.    At the run-time level, the various functions handle sequences of `\'
  6150. and `&' differently.  The situation is (sadly) somewhat complex.
  6151.    Historically, the `sub' and `gsub' functions treated the two
  6152. character sequence `\&' specially; this sequence was replaced in the
  6153. generated text with a single `&'.  Any other `\' within the REPLACEMENT
  6154. string that did not precede an `&' was passed through unchanged.  To
  6155. illustrate with a table:
  6156.       You type         `sub' sees          `sub' generates
  6157.       --------         ----------          ---------------
  6158.           `\&'              `&'            the matched text
  6159.          `\\&'             `\&'            a literal `&'
  6160.         `\\\&'             `\&'            a literal `&'
  6161.        `\\\\&'            `\\&'            a literal `\&'
  6162.       `\\\\\&'            `\\&'            a literal `\&'
  6163.      `\\\\\\&'           `\\\&'            a literal `\\&'
  6164.          `\\q'             `\q'            a literal `\q'
  6165. This table shows both the lexical level processing, where an odd number
  6166. of backslashes becomes an even number at the run time level, and the
  6167. run-time processing done by `sub'.  (For the sake of simplicity, the
  6168. rest of the tables below only show the case of even numbers of `\'s
  6169. entered at the lexical level.)
  6170.    The problem with the historical approach is that there is no way to
  6171. get a literal `\' followed by the matched text.
  6172.    The 1992 POSIX standard attempted to fix this problem. The standard
  6173. says that `sub' and `gsub' look for either a `\' or an `&' after the
  6174. `\'. If either one follows a `\', that character is output literally.
  6175. The interpretation of `\' and `&' then becomes like this:
  6176.       You type         `sub' sees          `sub' generates
  6177.       --------         ----------          ---------------
  6178.            `&'              `&'            the matched text
  6179.          `\\&'             `\&'            a literal `&'
  6180.        `\\\\&'            `\\&'            a literal `\', then the matched text
  6181.      `\\\\\\&'           `\\\&'            a literal `\&'
  6182. This would appear to solve the problem.  Unfortunately, the phrasing of
  6183. the standard is unusual. It says, in effect, that `\' turns off the
  6184. special meaning of any following character, but that for anything other
  6185. than `\' and `&', such special meaning is undefined.  This wording
  6186. leads to two problems.
  6187.   1. Backslashes must now be doubled in the REPLACEMENT string, breaking
  6188.      historical `awk' programs.
  6189.   2. To make sure that an `awk' program is portable, *every* character
  6190.      in the REPLACEMENT string must be preceded with a backslash.(1)
  6191.    The POSIX standard is under revision.(2) Because of the above
  6192. problems, proposed text for the revised standard reverts to rules that
  6193. correspond more closely to the original existing practice. The proposed
  6194. rules have special cases that make it possible to produce a `\'
  6195. preceding the matched text.
  6196.       You type         `sub' sees         `sub' generates
  6197.       --------         ----------         ---------------
  6198.      `\\\\\\&'           `\\\&'            a literal `\&'
  6199.        `\\\\&'            `\\&'            a literal `\', followed by the matched text
  6200.          `\\&'             `\&'            a literal `&'
  6201.          `\\q'             `\q'            a literal `\q'
  6202.    In a nutshell, at the run-time level, there are now three special
  6203. sequences of characters, `\\\&', `\\&' and `\&', whereas historically,
  6204. there was only one.  However, as in the historical case, any `\' that
  6205. is not part of one of these three sequences is not special, and appears
  6206. in the output literally.
  6207.    `gawk' 3.0 follows these proposed POSIX rules for `sub' and `gsub'.
  6208. Whether these proposed rules will actually become codified into the
  6209. standard is unknown at this point. Subsequent `gawk' releases will
  6210. track the standard and implement whatever the final version specifies;
  6211. this Info file will be updated as well.
  6212.    The rules for `gensub' are considerably simpler. At the run-time
  6213. level, whenever `gawk' sees a `\', if the following character is a
  6214. digit, then the text that matched the corresponding parenthesized
  6215. subexpression is placed in the generated output.  Otherwise, no matter
  6216. what the character after the `\' is, that character will appear in the
  6217. generated text, and the `\' will not.
  6218.        You type          `gensub' sees         `gensub' generates
  6219.        --------          -------------         ------------------
  6220.            `&'                    `&'            the matched text
  6221.          `\\&'                   `\&'            a literal `&'
  6222.         `\\\\'                   `\\'            a literal `\'
  6223.        `\\\\&'                  `\\&'            a literal `\', then the matched text
  6224.      `\\\\\\&'                 `\\\&'            a literal `\&'
  6225.          `\\q'                   `\q'            a literal `q'
  6226.    Because of the complexity of the lexical and run-time level
  6227. processing, and the special cases for `sub' and `gsub', we recommend
  6228. the use of `gawk' and `gensub' for when you have to do substitutions.
  6229.    ---------- Footnotes ----------
  6230.    (1)  This consequence was certainly unintended.
  6231.    (2)  As of February 1997, with final approval and publication
  6232. hopefully sometime in 1997.
  6233. File: gawk.info,  Node: I/O Functions,  Next: Time Functions,  Prev: String Functions,  Up: Built-in
  6234. Built-in Functions for Input/Output
  6235. ===================================
  6236.    The following functions are related to Input/Output (I/O).  Optional
  6237. parameters are enclosed in square brackets ("[" and "]").
  6238. `close(FILENAME)'
  6239.      Close the file FILENAME, for input or output.  The argument may
  6240.      alternatively be a shell command that was used for redirecting to
  6241.      or from a pipe; then the pipe is closed.  *Note Closing Input and
  6242.      Output Files and Pipes: Close Files And Pipes, for more
  6243.      information.
  6244. `fflush([FILENAME])'
  6245.      Flush any buffered output associated FILENAME, which is either a
  6246.      file opened for writing, or a shell command for redirecting output
  6247.      to a pipe.
  6248.      Many utility programs will "buffer" their output; they save
  6249.      information to be written to a disk file or terminal in memory,
  6250.      until there is enough for it to be worthwhile to send the data to
  6251.      the ouput device.  This is often more efficient than writing every
  6252.      little bit of information as soon as it is ready.  However,
  6253.      sometimes it is necessary to force a program to "flush" its
  6254.      buffers; that is, write the information to its destination, even
  6255.      if a buffer is not full.  This is the purpose of the `fflush'
  6256.      function; `gawk' too buffers its output, and the `fflush' function
  6257.      can be used to force `gawk' to flush its buffers.
  6258.      `fflush' is a recent (1994) addition to the Bell Labs research
  6259.      version of `awk'; it is not part of the POSIX standard, and will
  6260.      not be available if `--posix' has been specified on the command
  6261.      line (*note Command Line Options: Options.).
  6262.      `gawk' extends the `fflush' function in two ways.  The first is to
  6263.      allow no argument at all. In this case, the buffer for the
  6264.      standard output is flushed.  The second way is to allow the null
  6265.      string (`""') as the argument. In this case, the buffers for *all*
  6266.      open output files and pipes are flushed.
  6267.      `fflush' returns zero if the buffer was successfully flushed, and
  6268.      nonzero otherwise.
  6269. `system(COMMAND)'
  6270.      The system function allows the user to execute operating system
  6271.      commands and then return to the `awk' program.  The `system'
  6272.      function executes the command given by the string COMMAND.  It
  6273.      returns, as its value, the status returned by the command that was
  6274.      executed.
  6275.      For example, if the following fragment of code is put in your `awk'
  6276.      program:
  6277.           END {
  6278.                system("date | mail -s 'awk run done' root")
  6279.           }
  6280.      the system administrator will be sent mail when the `awk' program
  6281.      finishes processing input and begins its end-of-input processing.
  6282.      Note that redirecting `print' or `printf' into a pipe is often
  6283.      enough to accomplish your task.  However, if your `awk' program is
  6284.      interactive, `system' is useful for cranking up large
  6285.      self-contained programs, such as a shell or an editor.
  6286.      Some operating systems cannot implement the `system' function.
  6287.      `system' causes a fatal error if it is not supported.
  6288. Interactive vs. Non-Interactive Buffering
  6289. -----------------------------------------
  6290.    As a side point, buffering issues can be even more confusing
  6291. depending upon whether or not your program is "interactive", i.e.,
  6292. communicating with a user sitting at a keyboard.(1)
  6293.    Interactive programs generally "line buffer" their output; they
  6294. write out every line.  Non-interactive programs wait until they have a
  6295. full buffer, which may be many lines of output.
  6296.    Here is an example of the difference.
  6297.      $ awk '{ print $1 + $2 }'
  6298.      1 1
  6299.      -| 2
  6300.      2 3
  6301.      -| 5
  6302.      Control-d
  6303. Each line of output is printed immediately. Compare that behavior with
  6304. this example.
  6305.      $ awk '{ print $1 + $2 }' | cat
  6306.      1 1
  6307.      2 3
  6308.      Control-d
  6309.      -| 2
  6310.      -| 5
  6311. Here, no output is printed until after the `Control-d' is typed, since
  6312. it is all buffered, and sent down the pipe to `cat' in one shot.
  6313. Controlling Output Buffering with `system'
  6314. ------------------------------------------
  6315.    The `fflush' function provides explicit control over output
  6316. buffering for individual files and pipes.  However, its use is not
  6317. portable to many other `awk' implementations.  An alternative method to
  6318. flush output buffers is by calling `system' with a null string as its
  6319. argument:
  6320.      system("")   # flush output
  6321. `gawk' treats this use of the `system' function as a special case, and
  6322. is smart enough not to run a shell (or other command interpreter) with
  6323. the empty command.  Therefore, with `gawk', this idiom is not only
  6324. useful, it is efficient.  While this method should work with other
  6325. `awk' implementations, it will not necessarily avoid starting an
  6326. unnecessary shell.  (Other implementations may only flush the buffer
  6327. associated with the standard output, and not necessarily all buffered
  6328. output.)
  6329.    If you think about what a programmer expects, it makes sense that
  6330. `system' should flush any pending output.  The following program:
  6331.      BEGIN {
  6332.           print "first print"
  6333.           system("echo system echo")
  6334.           print "second print"
  6335.      }
  6336. must print
  6337.      first print
  6338.      system echo
  6339.      second print
  6340. and not
  6341.      system echo
  6342.      first print
  6343.      second print
  6344.    If `awk' did not flush its buffers before calling `system', the
  6345. latter (undesirable) output is what you would see.
  6346.    ---------- Footnotes ----------
  6347.    (1)  A program is interactive if the standard output is connected to
  6348. a terminal device.
  6349. File: gawk.info,  Node: Time Functions,  Prev: I/O Functions,  Up: Built-in
  6350. Functions for Dealing with Time Stamps
  6351. ======================================
  6352.    A common use for `awk' programs is the processing of log files
  6353. containing time stamp information, indicating when a particular log
  6354. record was written.  Many programs log their time stamp in the form
  6355. returned by the `time' system call, which is the number of seconds
  6356. since a particular epoch.  On POSIX systems, it is the number of
  6357. seconds since Midnight, January 1, 1970, UTC.
  6358.    In order to make it easier to process such log files, and to produce
  6359. useful reports, `gawk' provides two functions for working with time
  6360. stamps.  Both of these are `gawk' extensions; they are not specified in
  6361. the POSIX standard, nor are they in any other known version of `awk'.
  6362.    Optional parameters are enclosed in square brackets ("[" and "]").
  6363. `systime()'
  6364.      This function returns the current time as the number of seconds
  6365.      since the system epoch.  On POSIX systems, this is the number of
  6366.      seconds since Midnight, January 1, 1970, UTC.  It may be a
  6367.      different number on other systems.
  6368. `strftime([FORMAT [, TIMESTAMP]])'
  6369.      This function returns a string.  It is similar to the function of
  6370.      the same name in ANSI C.  The time specified by TIMESTAMP is used
  6371.      to produce a string, based on the contents of the FORMAT string.
  6372.      The TIMESTAMP is in the same format as the value returned by the
  6373.      `systime' function.  If no TIMESTAMP argument is supplied, `gawk'
  6374.      will use the current time of day as the time stamp.  If no FORMAT
  6375.      argument is supplied, `strftime' uses `"%a %b %d %H:%M:%S %Z %Y"'.
  6376.      This format string produces output (almost) equivalent to that of
  6377.      the `date' utility.  (Versions of `gawk' prior to 3.0 require the
  6378.      FORMAT argument.)
  6379.    The `systime' function allows you to compare a time stamp from a log
  6380. file with the current time of day.  In particular, it is easy to
  6381. determine how long ago a particular record was logged.  It also allows
  6382. you to produce log records using the "seconds since the epoch" format.
  6383.    The `strftime' function allows you to easily turn a time stamp into
  6384. human-readable information.  It is similar in nature to the `sprintf'
  6385. function (*note Built-in Functions for String Manipulation: String
  6386. Functions.), in that it copies non-format specification characters
  6387. verbatim to the returned string, while substituting date and time
  6388. values for format specifications in the FORMAT string.
  6389.    `strftime' is guaranteed by the ANSI C standard to support the
  6390. following date format specifications:
  6391.      The locale's abbreviated weekday name.
  6392.      The locale's full weekday name.
  6393.      The locale's abbreviated month name.
  6394.      The locale's full month name.
  6395.      The locale's "appropriate" date and time representation.
  6396.      The day of the month as a decimal number (01-31).
  6397.      The hour (24-hour clock) as a decimal number (00-23).
  6398.      The hour (12-hour clock) as a decimal number (01-12).
  6399.      The day of the year as a decimal number (001-366).
  6400.      The month as a decimal number (01-12).
  6401.      The minute as a decimal number (00-59).
  6402.      The locale's equivalent of the AM/PM designations associated with
  6403.      a 12-hour clock.
  6404.      The second as a decimal number (00-60).(1)
  6405.      The week number of the year (the first Sunday as the first day of
  6406.      week one) as a decimal number (00-53).
  6407.      The weekday as a decimal number (0-6).  Sunday is day zero.
  6408.      The week number of the year (the first Monday as the first day of
  6409.      week one) as a decimal number (00-53).
  6410.      The locale's "appropriate" date representation.
  6411.      The locale's "appropriate" time representation.
  6412.      The year without century as a decimal number (00-99).
  6413.      The year with century as a decimal number (e.g., 1995).
  6414.      The time zone name or abbreviation, or no characters if no time
  6415.      zone is determinable.
  6416.      A literal `%'.
  6417.    If a conversion specifier is not one of the above, the behavior is
  6418. undefined.(2)
  6419.    Informally, a "locale" is the geographic place in which a program is
  6420. meant to run.  For example, a common way to abbreviate the date
  6421. September 4, 1991 in the United States would be "9/4/91".  In many
  6422. countries in Europe, however, it would be abbreviated "4.9.91".  Thus,
  6423. the `%x' specification in a `"US"' locale might produce `9/4/91', while
  6424. in a `"EUROPE"' locale, it might produce `4.9.91'.  The ANSI C standard
  6425. defines a default `"C"' locale, which is an environment that is typical
  6426. of what most C programmers are used to.
  6427.    A public-domain C version of `strftime' is supplied with `gawk' for
  6428. systems that are not yet fully ANSI-compliant.  If that version is used
  6429. to compile `gawk' (*note Installing `gawk': Installation.), then the
  6430. following additional format specifications are available:
  6431.      Equivalent to specifying `%m/%d/%y'.
  6432.      The day of the month, padded with a space if it is only one digit.
  6433.      Equivalent to `%b', above.
  6434.      A newline character (ASCII LF).
  6435.      Equivalent to specifying `%I:%M:%S %p'.
  6436.      Equivalent to specifying `%H:%M'.
  6437.      Equivalent to specifying `%H:%M:%S'.
  6438.      A tab character.
  6439.      The hour (24-hour clock) as a decimal number (0-23).  Single digit
  6440.      numbers are padded with a space.
  6441.      The hour (12-hour clock) as a decimal number (1-12).  Single digit
  6442.      numbers are padded with a space.
  6443.      The century, as a number between 00 and 99.
  6444.      The weekday as a decimal number [1 (Monday)-7].
  6445.      The week number of the year (the first Monday as the first day of
  6446.      week one) as a decimal number (01-53).  The method for determining
  6447.      the week number is as specified by ISO 8601 (to wit: if the week
  6448.      containing January 1 has four or more days in the new year, then
  6449.      it is week one, otherwise it is week 53 of the previous year and
  6450.      the next week is week one).
  6451.      The year with century of the ISO week number, as a decimal number.
  6452.      For example, January 1, 1993, is in week 53 of 1992. Thus, the year
  6453.      of its ISO week number is 1992, even though its year is 1993.
  6454.      Similarly, December 31, 1973, is in week 1 of 1974. Thus, the year
  6455.      of its ISO week number is 1974, even though its year is 1973.
  6456.      The year without century of the ISO week number, as a decimal
  6457.      number (00-99).
  6458. `%Ec %EC %Ex %Ey %EY %Od %Oe %OH %OI'
  6459. `%Om %OM %OS %Ou %OU %OV %Ow %OW %Oy'
  6460.      These are "alternate representations" for the specifications that
  6461.      use only the second letter (`%c', `%C', and so on).  They are
  6462.      recognized, but their normal representations are used.(3) (These
  6463.      facilitate compliance with the POSIX `date' utility.)
  6464.      The date in VMS format (e.g., 20-JUN-1991).
  6465.      The timezone offset in a +HHMM format (e.g., the format necessary
  6466.      to produce RFC-822/RFC-1036 date headers).
  6467.    This example is an `awk' implementation of the POSIX `date' utility.
  6468. Normally, the `date' utility prints the current date and time of day
  6469. in a well known format.  However, if you provide an argument to it that
  6470. begins with a `+', `date' will copy non-format specifier characters to
  6471. the standard output, and will interpret the current time according to
  6472. the format specifiers in the string.  For example:
  6473.      $ date '+Today is %A, %B %d, %Y.'
  6474.      -| Today is Thursday, July 11, 1991.
  6475.    Here is the `gawk' version of the `date' utility.  It has a shell
  6476. "wrapper", to handle the `-u' option, which requires that `date' run as
  6477. if the time zone was set to UTC.
  6478.      #! /bin/sh
  6479.      #
  6480.      # date --- approximate the P1003.2 'date' command
  6481.      
  6482.      case $1 in
  6483.      -u)  TZ=GMT0     # use UTC
  6484.           export TZ
  6485.           shift ;;
  6486.      esac
  6487.      
  6488.      gawk 'BEGIN  {
  6489.          format = "%a %b %d %H:%M:%S %Z %Y"
  6490.          exitval = 0
  6491.      
  6492.          if (ARGC > 2)
  6493.              exitval = 1
  6494.          else if (ARGC == 2) {
  6495.              format = ARGV[1]
  6496.              if (format ~ /^\+/)
  6497.                  format = substr(format, 2)   # remove leading +
  6498.          }
  6499.          print strftime(format)
  6500.          exit exitval
  6501.      }' "$@"
  6502.    ---------- Footnotes ----------
  6503.    (1)  Occasionally there are minutes in a year with a leap second,
  6504. which is why the seconds can go up to 60.
  6505.    (2)  This is because ANSI C leaves the behavior of the C version of
  6506. `strftime' undefined, and `gawk' will use the system's version of
  6507. `strftime' if it's there.  Typically, the conversion specifier will
  6508. either not appear in the returned string, or it will appear literally.
  6509.    (3)  If you don't understand any of this, don't worry about it;
  6510. these facilities are meant to make it easier to "internationalize"
  6511. programs.
  6512. File: gawk.info,  Node: User-defined,  Next: Invoking Gawk,  Prev: Built-in,  Up: Top
  6513. User-defined Functions
  6514. **********************
  6515.    Complicated `awk' programs can often be simplified by defining your
  6516. own functions.  User-defined functions can be called just like built-in
  6517. ones (*note Function Calls::.), but it is up to you to define them--to
  6518. tell `awk' what they should do.
  6519. * Menu:
  6520. * Definition Syntax::           How to write definitions and what they mean.
  6521. * Function Example::            An example function definition and what it
  6522.                                 does.
  6523. * Function Caveats::            Things to watch out for.
  6524. * Return Statement::            Specifying the value a function returns.
  6525. File: gawk.info,  Node: Definition Syntax,  Next: Function Example,  Prev: User-defined,  Up: User-defined
  6526. Function Definition Syntax
  6527. ==========================
  6528.    Definitions of functions can appear anywhere between the rules of an
  6529. `awk' program.  Thus, the general form of an `awk' program is extended
  6530. to include sequences of rules *and* user-defined function definitions.
  6531. There is no need in `awk' to put the definition of a function before
  6532. all uses of the function.  This is because `awk' reads the entire
  6533. program before starting to execute any of it.
  6534.    The definition of a function named NAME looks like this:
  6535.      function NAME(PARAMETER-LIST)
  6536.      {
  6537.           BODY-OF-FUNCTION
  6538.      }
  6539. NAME is the name of the function to be defined.  A valid function name
  6540. is like a valid variable name: a sequence of letters, digits and
  6541. underscores, not starting with a digit.  Within a single `awk' program,
  6542. any particular name can only be used as a variable, array or function.
  6543.    PARAMETER-LIST is a list of the function's arguments and local
  6544. variable names, separated by commas.  When the function is called, the
  6545. argument names are used to hold the argument values given in the call.
  6546. The local variables are initialized to the empty string.  A function
  6547. cannot have two parameters with the same name.
  6548.    The BODY-OF-FUNCTION consists of `awk' statements.  It is the most
  6549. important part of the definition, because it says what the function
  6550. should actually *do*.  The argument names exist to give the body a way
  6551. to talk about the arguments; local variables, to give the body places
  6552. to keep temporary values.
  6553.    Argument names are not distinguished syntactically from local
  6554. variable names; instead, the number of arguments supplied when the
  6555. function is called determines how many argument variables there are.
  6556. Thus, if three argument values are given, the first three names in
  6557. PARAMETER-LIST are arguments, and the rest are local variables.
  6558.    It follows that if the number of arguments is not the same in all
  6559. calls to the function, some of the names in PARAMETER-LIST may be
  6560. arguments on some occasions and local variables on others.  Another way
  6561. to think of this is that omitted arguments default to the null string.
  6562.    Usually when you write a function you know how many names you intend
  6563. to use for arguments and how many you intend to use as local variables.
  6564. It is conventional to place some extra space between the arguments and
  6565. the local variables, to document how your function is supposed to be
  6566. used.
  6567.    During execution of the function body, the arguments and local
  6568. variable values hide or "shadow" any variables of the same names used
  6569. in the rest of the program.  The shadowed variables are not accessible
  6570. in the function definition, because there is no way to name them while
  6571. their names have been taken away for the local variables.  All other
  6572. variables used in the `awk' program can be referenced or set normally
  6573. in the function's body.
  6574.    The arguments and local variables last only as long as the function
  6575. body is executing.  Once the body finishes, you can once again access
  6576. the variables that were shadowed while the function was running.
  6577.    The function body can contain expressions which call functions.  They
  6578. can even call this function, either directly or by way of another
  6579. function.  When this happens, we say the function is "recursive".
  6580.    In many `awk' implementations, including `gawk', the keyword
  6581. `function' may be abbreviated `func'.  However, POSIX only specifies
  6582. the use of the keyword `function'.  This actually has some practical
  6583. implications.  If `gawk' is in POSIX-compatibility mode (*note Command
  6584. Line Options: Options.), then the following statement will *not* define
  6585. a function:
  6586.      func foo() { a = sqrt($1) ; print a }
  6587. Instead it defines a rule that, for each record, concatenates the value
  6588. of the variable `func' with the return value of the function `foo'.  If
  6589. the resulting string is non-null, the action is executed.  This is
  6590. probably not what was desired.  (`awk' accepts this input as
  6591. syntactically valid, since functions may be used before they are defined
  6592. in `awk' programs.)
  6593.    To ensure that your `awk' programs are portable, always use the
  6594. keyword `function' when defining a function.
  6595. File: gawk.info,  Node: Function Example,  Next: Function Caveats,  Prev: Definition Syntax,  Up: User-defined
  6596. Function Definition Examples
  6597. ============================
  6598.    Here is an example of a user-defined function, called `myprint', that
  6599. takes a number and prints it in a specific format.
  6600.      function myprint(num)
  6601.      {
  6602.           printf "%6.3g\n", num
  6603.      }
  6604. To illustrate, here is an `awk' rule which uses our `myprint' function:
  6605.      $3 > 0     { myprint($3) }
  6606. This program prints, in our special format, all the third fields that
  6607. contain a positive number in our input.  Therefore, when given:
  6608.       1.2   3.4    5.6   7.8
  6609.       9.10 11.12 -13.14 15.16
  6610.      17.18 19.20  21.22 23.24
  6611. this program, using our function to format the results, prints:
  6612.         5.6
  6613.        21.2
  6614.    This function deletes all the elements in an array.
  6615.      function delarray(a,    i)
  6616.      {
  6617.          for (i in a)
  6618.             delete a[i]
  6619.      }
  6620.    When working with arrays, it is often necessary to delete all the
  6621. elements in an array and start over with a new list of elements (*note
  6622. The `delete' Statement: Delete.).  Instead of having to repeat this
  6623. loop everywhere in your program that you need to clear out an array,
  6624. your program can just call `delarray'.
  6625.    Here is an example of a recursive function.  It takes a string as an
  6626. input parameter, and returns the string in backwards order.
  6627.      function rev(str, start)
  6628.      {
  6629.          if (start == 0)
  6630.              return ""
  6631.      
  6632.          return (substr(str, start, 1) rev(str, start - 1))
  6633.      }
  6634.    If this function is in a file named `rev.awk', we can test it this
  6635.      $ echo "Don't Panic!" |
  6636.      > gawk --source '{ print rev($0, length($0)) }' -f rev.awk
  6637.      -| !cinaP t'noD
  6638.    Here is an example that uses the built-in function `strftime'.
  6639. (*Note Functions for Dealing with Time Stamps: Time Functions, for more
  6640. information on `strftime'.) The C `ctime' function takes a timestamp
  6641. and returns it in a string, formatted in a well known fashion.  Here is
  6642. an `awk' version:
  6643.      # ctime.awk
  6644.      #
  6645.      # awk version of C ctime(3) function
  6646.      
  6647.      function ctime(ts,    format)
  6648.      {
  6649.          format = "%a %b %d %H:%M:%S %Z %Y"
  6650.          if (ts == 0)
  6651.              ts = systime()       # use current time as default
  6652.          return strftime(format, ts)
  6653.      }
  6654. File: gawk.info,  Node: Function Caveats,  Next: Return Statement,  Prev: Function Example,  Up: User-defined
  6655. Calling User-defined Functions
  6656. ==============================
  6657.    "Calling a function" means causing the function to run and do its
  6658. job.  A function call is an expression, and its value is the value
  6659. returned by the function.
  6660.    A function call consists of the function name followed by the
  6661. arguments in parentheses.  What you write in the call for the arguments
  6662. are `awk' expressions; each time the call is executed, these
  6663. expressions are evaluated, and the values are the actual arguments.  For
  6664. example, here is a call to `foo' with three arguments (the first being
  6665. a string concatenation):
  6666.      foo(x y, "lose", 4 * z)
  6667.    *Caution:* whitespace characters (spaces and tabs) are not allowed
  6668. between the function name and the open-parenthesis of the argument list.
  6669. If you write whitespace by mistake, `awk' might think that you mean to
  6670. concatenate a variable with an expression in parentheses.  However, it
  6671. notices that you used a function name and not a variable name, and
  6672. reports an error.
  6673.    When a function is called, it is given a *copy* of the values of its
  6674. arguments.  This is known as "call by value".  The caller may use a
  6675. variable as the expression for the argument, but the called function
  6676. does not know this: it only knows what value the argument had.  For
  6677. example, if you write this code:
  6678.      foo = "bar"
  6679.      z = myfunc(foo)
  6680. then you should not think of the argument to `myfunc' as being "the
  6681. variable `foo'."  Instead, think of the argument as the string value,
  6682. `"bar"'.
  6683.    If the function `myfunc' alters the values of its local variables,
  6684. this has no effect on any other variables.  Thus, if `myfunc' does this:
  6685.      function myfunc(str)
  6686.      {
  6687.        print str
  6688.        str = "zzz"
  6689.        print str
  6690.      }
  6691. to change its first argument variable `str', this *does not* change the
  6692. value of `foo' in the caller.  The role of `foo' in calling `myfunc'
  6693. ended when its value, `"bar"', was computed.  If `str' also exists
  6694. outside of `myfunc', the function body cannot alter this outer value,
  6695. because it is shadowed during the execution of `myfunc' and cannot be
  6696. seen or changed from there.
  6697.    However, when arrays are the parameters to functions, they are *not*
  6698. copied.  Instead, the array itself is made available for direct
  6699. manipulation by the function.  This is usually called "call by
  6700. reference".  Changes made to an array parameter inside the body of a
  6701. function *are* visible outside that function.  This can be *very*
  6702. dangerous if you do not watch what you are doing.  For example:
  6703.      function changeit(array, ind, nvalue)
  6704.      {
  6705.           array[ind] = nvalue
  6706.      }
  6707.      
  6708.      BEGIN {
  6709.          a[1] = 1; a[2] = 2; a[3] = 3
  6710.          changeit(a, 2, "two")
  6711.          printf "a[1] = %s, a[2] = %s, a[3] = %s\n",
  6712.                  a[1], a[2], a[3]
  6713.      }
  6714. This program prints `a[1] = 1, a[2] = two, a[3] = 3', because
  6715. `changeit' stores `"two"' in the second element of `a'.
  6716.    Some `awk' implementations allow you to call a function that has not
  6717. been defined, and only report a problem at run-time when the program
  6718. actually tries to call the function. For example:
  6719.      BEGIN {
  6720.          if (0)
  6721.              foo()
  6722.          else
  6723.              bar()
  6724.      }
  6725.      function bar() { ... }
  6726.      # note that `foo' is not defined
  6727. Since the `if' statement will never be true, it is not really a problem
  6728. that `foo' has not been defined.  Usually though, it is a problem if a
  6729. program calls an undefined function.
  6730.    If `--lint' has been specified (*note Command Line Options:
  6731. Options.), `gawk' will report about calls to undefined functions.
  6732.    Some `awk' implementations generate a run-time error if you use the
  6733. `next' statement (*note The `next' Statement: Next Statement.) inside a
  6734. user-defined function.  `gawk' does not have this problem.
  6735. File: gawk.info,  Node: Return Statement,  Prev: Function Caveats,  Up: User-defined
  6736. The `return' Statement
  6737. ======================
  6738.    The body of a user-defined function can contain a `return' statement.
  6739. This statement returns control to the rest of the `awk' program.  It
  6740. can also be used to return a value for use in the rest of the `awk'
  6741. program.  It looks like this:
  6742.      return [EXPRESSION]
  6743.    The EXPRESSION part is optional.  If it is omitted, then the returned
  6744. value is undefined and, therefore, unpredictable.
  6745.    A `return' statement with no value expression is assumed at the end
  6746. of every function definition.  So if control reaches the end of the
  6747. function body, then the function returns an unpredictable value.  `awk'
  6748. will *not* warn you if you use the return value of such a function.
  6749.    Sometimes, you want to write a function for what it does, not for
  6750. what it returns.  Such a function corresponds to a `void' function in C
  6751. or to a `procedure' in Pascal.  Thus, it may be appropriate to not
  6752. return any value; you should simply bear in mind that if you use the
  6753. return value of such a function, you do so at your own risk.
  6754.    Here is an example of a user-defined function that returns a value
  6755. for the largest number among the elements of an array:
  6756.      function maxelt(vec,   i, ret)
  6757.      {
  6758.           for (i in vec) {
  6759.                if (ret == "" || vec[i] > ret)
  6760.                     ret = vec[i]
  6761.           }
  6762.           return ret
  6763.      }
  6764. You call `maxelt' with one argument, which is an array name.  The local
  6765. variables `i' and `ret' are not intended to be arguments; while there
  6766. is nothing to stop you from passing two or three arguments to `maxelt',
  6767. the results would be strange.  The extra space before `i' in the
  6768. function parameter list indicates that `i' and `ret' are not supposed
  6769. to be arguments.  This is a convention that you should follow when you
  6770. define functions.
  6771.    Here is a program that uses our `maxelt' function.  It loads an
  6772. array, calls `maxelt', and then reports the maximum number in that
  6773. array:
  6774.      awk '
  6775.      function maxelt(vec,   i, ret)
  6776.      {
  6777.           for (i in vec) {
  6778.                if (ret == "" || vec[i] > ret)
  6779.                     ret = vec[i]
  6780.           }
  6781.           return ret
  6782.      }
  6783.      
  6784.      # Load all fields of each record into nums.
  6785.      {
  6786.           for(i = 1; i <= NF; i++)
  6787.                nums[NR, i] = $i
  6788.      }
  6789.      
  6790.      END {
  6791.           print maxelt(nums)
  6792.      }'
  6793.    Given the following input:
  6794.       1 5 23 8 16
  6795.      44 3 5 2 8 26
  6796.      256 291 1396 2962 100
  6797.      -6 467 998 1101
  6798.      99385 11 0 225
  6799. our program tells us (predictably) that `99385' is the largest number
  6800. in our array.
  6801. File: gawk.info,  Node: Invoking Gawk,  Next: Library Functions,  Prev: User-defined,  Up: Top
  6802. Running `awk'
  6803. *************
  6804.    There are two ways to run `awk': with an explicit program, or with
  6805. one or more program files.  Here are templates for both of them; items
  6806. enclosed in `[...]' in these templates are optional.
  6807.    Besides traditional one-letter POSIX-style options, `gawk' also
  6808. supports GNU long options.
  6809.      awk [OPTIONS] -f progfile [`--'] FILE ...
  6810.      awk [OPTIONS] [`--'] 'PROGRAM' FILE ...
  6811.    It is possible to invoke `awk' with an empty program:
  6812.      $ awk '' datafile1 datafile2
  6813. Doing so makes little sense though; `awk' will simply exit silently
  6814. when given an empty program (d.c.).  If `--lint' has been specified on
  6815. the command line, `gawk' will issue a warning that the program is empty.
  6816. * Menu:
  6817. * Options::                     Command line options and their meanings.
  6818. * Other Arguments::             Input file names and variable assignments.
  6819. * AWKPATH Variable::            Searching directories for `awk' programs.
  6820. * Obsolete::                    Obsolete Options and/or features.
  6821. * Undocumented::                Undocumented Options and Features.
  6822. * Known Bugs::                  Known Bugs in `gawk'.
  6823. File: gawk.info,  Node: Options,  Next: Other Arguments,  Prev: Invoking Gawk,  Up: Invoking Gawk
  6824. Command Line Options
  6825. ====================
  6826.    Options begin with a dash, and consist of a single character.  GNU
  6827. style long options consist of two dashes and a keyword.  The keyword
  6828. can be abbreviated, as long the abbreviation allows the option to be
  6829. uniquely identified.  If the option takes an argument, then the keyword
  6830. is either immediately followed by an equals sign (`=') and the
  6831. argument's value, or the keyword and the argument's value are separated
  6832. by whitespace.  For brevity, the discussion below only refers to the
  6833. traditional short options; however the long and short options are
  6834. interchangeable in all contexts.
  6835.    Each long option for `gawk' has a corresponding POSIX-style option.
  6836. The options and their meanings are as follows:
  6837. `-F FS'
  6838. `--field-separator FS'
  6839.      Sets the `FS' variable to FS (*note Specifying How Fields are
  6840.      Separated: Field Separators.).
  6841. `-f SOURCE-FILE'
  6842. `--file SOURCE-FILE'
  6843.      Indicates that the `awk' program is to be found in SOURCE-FILE
  6844.      instead of in the first non-option argument.
  6845. `-v VAR=VAL'
  6846. `--assign VAR=VAL'
  6847.      Sets the variable VAR to the value VAL *before* execution of the
  6848.      program begins.  Such variable values are available inside the
  6849.      `BEGIN' rule (*note Other Command Line Arguments: Other
  6850.      Arguments.).
  6851.      The `-v' option can only set one variable, but you can use it more
  6852.      than once, setting another variable each time, like this: `awk
  6853.      -v foo=1 -v bar=2 ...'.
  6854. `-mf NNN'
  6855. `-mr NNN'
  6856.      Set various memory limits to the value NNN.  The `f' flag sets the
  6857.      maximum number of fields, and the `r' flag sets the maximum record
  6858.      size.  These two flags and the `-m' option are from the Bell Labs
  6859.      research version of Unix `awk'.  They are provided for
  6860.      compatibility, but otherwise ignored by `gawk', since `gawk' has
  6861.      no predefined limits.
  6862. `-W GAWK-OPT'
  6863.      Following the POSIX standard, options that are implementation
  6864.      specific are supplied as arguments to the `-W' option.  These
  6865.      options also have corresponding GNU style long options.  See below.
  6866.      Signals the end of the command line options.  The following
  6867.      arguments are not treated as options even if they begin with `-'.
  6868.      This interpretation of `--' follows the POSIX argument parsing
  6869.      conventions.
  6870.      This is useful if you have file names that start with `-', or in
  6871.      shell scripts, if you have file names that will be specified by
  6872.      the user which could start with `-'.
  6873.    The following `gawk'-specific options are available:
  6874. `-W traditional'
  6875. `-W compat'
  6876. `--traditional'
  6877. `--compat'
  6878.      Specifies "compatibility mode", in which the GNU extensions to the
  6879.      `awk' language are disabled, so that `gawk' behaves just like the
  6880.      Bell Labs research version of Unix `awk'.  `--traditional' is the
  6881.      preferred form of this option.  *Note Extensions in `gawk' Not in
  6882.      POSIX `awk': POSIX/GNU, which summarizes the extensions.  Also see
  6883.      *Note Downward Compatibility and Debugging: Compatibility Mode.
  6884. `-W copyleft'
  6885. `-W copyright'
  6886. `--copyleft'
  6887. `--copyright'
  6888.      Print the short version of the General Public License, and then
  6889.      exit.  This option may disappear in a future version of `gawk'.
  6890. `-W help'
  6891. `-W usage'
  6892. `--help'
  6893. `--usage'
  6894.      Print a "usage" message summarizing the short and long style
  6895.      options that `gawk' accepts, and then exit.
  6896. `-W lint'
  6897. `--lint'
  6898.      Warn about constructs that are dubious or non-portable to other
  6899.      `awk' implementations.  Some warnings are issued when `gawk' first
  6900.      reads your program.  Others are issued at run-time, as your
  6901.      program executes.
  6902. `-W lint-old'
  6903. `--lint-old'
  6904.      Warn about constructs that are not available in the original
  6905.      Version 7 Unix version of `awk' (*note Major Changes between V7
  6906.      and SVR3.1: V7/SVR3.1.).
  6907. `-W posix'
  6908. `--posix'
  6909.      Operate in strict POSIX mode.  This disables all `gawk' extensions
  6910.      (just like `--traditional'), and adds the following additional
  6911.      restrictions:
  6912.         * `\x' escape sequences are not recognized (*note Escape
  6913.           Sequences::.).
  6914.         * Newlines do not act as whitespace to separate fields when
  6915.           `FS' is equal to a single space.
  6916.         * The synonym `func' for the keyword `function' is not
  6917.           recognized (*note Function Definition Syntax: Definition
  6918.           Syntax.).
  6919.         * The operators `**' and `**=' cannot be used in place of `^'
  6920.           and `^=' (*note Arithmetic Operators: Arithmetic Ops., and
  6921.           also *note Assignment Expressions: Assignment Ops.).
  6922.         * Specifying `-Ft' on the command line does not set the value
  6923.           of `FS' to be a single tab character (*note Specifying How
  6924.           Fields are Separated: Field Separators.).
  6925.         * The `fflush' built-in function is not supported (*note
  6926.           Built-in Functions for Input/Output: I/O Functions.).
  6927.      If you supply both `--traditional' and `--posix' on the command
  6928.      line, `--posix' will take precedence. `gawk' will also issue a
  6929.      warning if both options are supplied.
  6930. `-W re-interval'
  6931. `--re-interval'
  6932.      Allow interval expressions (*note Regular Expression Operators:
  6933.      Regexp Operators.), in regexps.  Because interval expressions were
  6934.      traditionally not available in `awk', `gawk' does not provide them
  6935.      by default. This prevents old `awk' programs from breaking.
  6936. `-W source PROGRAM-TEXT'
  6937. `--source PROGRAM-TEXT'
  6938.      Program source code is taken from the PROGRAM-TEXT.  This option
  6939.      allows you to mix source code in files with source code that you
  6940.      enter on the command line. This is particularly useful when you
  6941.      have library functions that you wish to use from your command line
  6942.      programs (*note The `AWKPATH' Environment Variable: AWKPATH
  6943.      Variable.).
  6944. `-W version'
  6945. `--version'
  6946.      Prints version information for this particular copy of `gawk'.
  6947.      This allows you to determine if your copy of `gawk' is up to date
  6948.      with respect to whatever the Free Software Foundation is currently
  6949.      distributing.  It is also useful for bug reports (*note Reporting
  6950.      Problems and Bugs: Bugs.).
  6951.    Any other options are flagged as invalid with a warning message, but
  6952. are otherwise ignored.
  6953.    In compatibility mode, as a special case, if the value of FS supplied
  6954. to the `-F' option is `t', then `FS' is set to the tab character
  6955. (`"\t"').  This is only true for `--traditional', and not for `--posix'
  6956. (*note Specifying How Fields are Separated: Field Separators.).
  6957.    The `-f' option may be used more than once on the command line.  If
  6958. it is, `awk' reads its program source from all of the named files, as
  6959. if they had been concatenated together into one big file.  This is
  6960. useful for creating libraries of `awk' functions.  Useful functions can
  6961. be written once, and then retrieved from a standard place, instead of
  6962. having to be included into each individual program.
  6963.    You can type in a program at the terminal and still use library
  6964. functions, by specifying `-f /dev/tty'.  `awk' will read a file from
  6965. the terminal to use as part of the `awk' program.  After typing your
  6966. program, type `Control-d' (the end-of-file character) to terminate it.
  6967. (You may also use `-f -' to read program source from the standard
  6968. input, but then you will not be able to also use the standard input as a
  6969. source of data.)
  6970.    Because it is clumsy using the standard `awk' mechanisms to mix
  6971. source file and command line `awk' programs, `gawk' provides the
  6972. `--source' option.  This does not require you to pre-empt the standard
  6973. input for your source code, and allows you to easily mix command line
  6974. and library source code (*note The `AWKPATH' Environment Variable:
  6975. AWKPATH Variable.).
  6976.    If no `-f' or `--source' option is specified, then `gawk' will use
  6977. the first non-option command line argument as the text of the program
  6978. source code.
  6979.    If the environment variable `POSIXLY_CORRECT' exists, then `gawk'
  6980. will behave in strict POSIX mode, exactly as if you had supplied the
  6981. `--posix' command line option.  Many GNU programs look for this
  6982. environment variable to turn on strict POSIX mode. If you supply
  6983. `--lint' on the command line, and `gawk' turns on POSIX mode because of
  6984. `POSIXLY_CORRECT', then it will print a warning message indicating that
  6985. POSIX mode is in effect.
  6986.    You would typically set this variable in your shell's startup file.
  6987. For a Bourne compatible shell (such as Bash), you would add these lines
  6988. to the `.profile' file in your home directory.
  6989.      POSIXLY_CORRECT=true
  6990.      export POSIXLY_CORRECT
  6991.    For a `csh' compatible shell,(1) you would add this line to the
  6992. `.login' file in your home directory.
  6993.      setenv POSIXLY_CORRECT true
  6994.    ---------- Footnotes ----------
  6995.    (1)  Not recommended.
  6996. File: gawk.info,  Node: Other Arguments,  Next: AWKPATH Variable,  Prev: Options,  Up: Invoking Gawk
  6997. Other Command Line Arguments
  6998. ============================
  6999.    Any additional arguments on the command line are normally treated as
  7000. input files to be processed in the order specified.   However, an
  7001. argument that has the form `VAR=VALUE', assigns the value VALUE to the
  7002. variable VAR--it does not specify a file at all.
  7003.    All these arguments are made available to your `awk' program in the
  7004. `ARGV' array (*note Built-in Variables::.).  Command line options and
  7005. the program text (if present) are omitted from `ARGV'.  All other
  7006. arguments, including variable assignments, are included.   As each
  7007. element of `ARGV' is processed, `gawk' sets the variable `ARGIND' to
  7008. the index in `ARGV' of the current element.
  7009.    The distinction between file name arguments and variable-assignment
  7010. arguments is made when `awk' is about to open the next input file.  At
  7011. that point in execution, it checks the "file name" to see whether it is
  7012. really a variable assignment; if so, `awk' sets the variable instead of
  7013. reading a file.
  7014.    Therefore, the variables actually receive the given values after all
  7015. previously specified files have been read.  In particular, the values of
  7016. variables assigned in this fashion are *not* available inside a `BEGIN'
  7017. rule (*note The `BEGIN' and `END' Special Patterns: BEGIN/END.), since
  7018. such rules are run before `awk' begins scanning the argument list.
  7019.    The variable values given on the command line are processed for
  7020. escape sequences (d.c.) (*note Escape Sequences::.).
  7021.    In some earlier implementations of `awk', when a variable assignment
  7022. occurred before any file names, the assignment would happen *before*
  7023. the `BEGIN' rule was executed.  `awk''s behavior was thus inconsistent;
  7024. some command line assignments were available inside the `BEGIN' rule,
  7025. while others were not.  However, some applications came to depend upon
  7026. this "feature."  When `awk' was changed to be more consistent, the `-v'
  7027. option was added to accommodate applications that depended upon the old
  7028. behavior.
  7029.    The variable assignment feature is most useful for assigning to
  7030. variables such as `RS', `OFS', and `ORS', which control input and
  7031. output formats, before scanning the data files.  It is also useful for
  7032. controlling state if multiple passes are needed over a data file.  For
  7033. example:
  7034.      awk 'pass == 1  { PASS 1 STUFF }
  7035.           pass == 2  { PASS 2 STUFF }' pass=1 mydata pass=2 mydata
  7036.    Given the variable assignment feature, the `-F' option for setting
  7037. the value of `FS' is not strictly necessary.  It remains for historical
  7038. compatibility.
  7039. File: gawk.info,  Node: AWKPATH Variable,  Next: Obsolete,  Prev: Other Arguments,  Up: Invoking Gawk
  7040. The `AWKPATH' Environment Variable
  7041. ==================================
  7042.    The previous section described how `awk' program files can be named
  7043. on the command line with the `-f' option.  In most `awk'
  7044. implementations, you must supply a precise path name for each program
  7045. file, unless the file is in the current directory.
  7046.    But in `gawk', if the file name supplied to the `-f' option does not
  7047. contain a `/', then `gawk' searches a list of directories (called the
  7048. "search path"), one by one, looking for a file with the specified name.
  7049.    The search path is a string consisting of directory names separated
  7050. by colons.  `gawk' gets its search path from the `AWKPATH' environment
  7051. variable.  If that variable does not exist, `gawk' uses a default path,
  7052. which is `.:/usr/local/share/awk'.(1) (Programs written for use by
  7053. system administrators should use an `AWKPATH' variable that does not
  7054. include the current directory, `.'.)
  7055.    The search path feature is particularly useful for building up
  7056. libraries of useful `awk' functions.  The library files can be placed
  7057. in a standard directory that is in the default path, and then specified
  7058. on the command line with a short file name.  Otherwise, the full file
  7059. name would have to be typed for each file.
  7060.    By using both the `--source' and `-f' options, your command line
  7061. `awk' programs can use facilities in `awk' library files.  *Note A
  7062. Library of `awk' Functions: Library Functions.
  7063.    Path searching is not done if `gawk' is in compatibility mode.  This
  7064. is true for both `--traditional' and `--posix'.  *Note Command Line
  7065. Options: Options.
  7066.    *Note:* if you want files in the current directory to be found, you
  7067. must include the current directory in the path, either by including `.'
  7068. explicitly in the path, or by writing a null entry in the path.  (A
  7069. null entry is indicated by starting or ending the path with a colon, or
  7070. by placing two colons next to each other (`::').)  If the current
  7071. directory is not included in the path, then files cannot be found in
  7072. the current directory.  This path search mechanism is identical to the
  7073. shell's.
  7074.    Starting with version 3.0, if `AWKPATH' is not defined in the
  7075. environment, `gawk' will place its default search path into
  7076. `ENVIRON["AWKPATH"]'. This makes it easy to determine the actual search
  7077. path `gawk' will use.
  7078.    ---------- Footnotes ----------
  7079.    (1)  Your version of `gawk' may use a directory that is different
  7080. than `/usr/local/share/awk'; it will depend upon how `gawk' was built
  7081. and installed. The actual directory will be the value of `$(datadir)'
  7082. generated when `gawk' was configured.  You probably don't need to worry
  7083. about this though.
  7084. File: gawk.info,  Node: Obsolete,  Next: Undocumented,  Prev: AWKPATH Variable,  Up: Invoking Gawk
  7085. Obsolete Options and/or Features
  7086. ================================
  7087.    This section describes features and/or command line options from
  7088. previous releases of `gawk' that are either not available in the
  7089. current version, or that are still supported but deprecated (meaning
  7090. that they will *not* be in the next release).
  7091.    For version 3.0.3 of `gawk', there are no command line options or
  7092. other deprecated features from the previous version of `gawk'.  This
  7093. node is thus essentially a place holder, in case some option becomes
  7094. obsolete in a future version of `gawk'.
  7095. File: gawk.info,  Node: Undocumented,  Next: Known Bugs,  Prev: Obsolete,  Up: Invoking Gawk
  7096. Undocumented Options and Features
  7097. =================================
  7098.      Use the Source, Luke!
  7099.      Obi-Wan
  7100.    This section intentionally left blank.
  7101. File: gawk.info,  Node: Known Bugs,  Prev: Undocumented,  Up: Invoking Gawk
  7102. Known Bugs in `gawk'
  7103. ====================
  7104.    * The `-F' option for changing the value of `FS' (*note Command Line
  7105.      Options: Options.) is not necessary given the command line variable
  7106.      assignment feature; it remains only for backwards compatibility.
  7107.    * If your system actually has support for `/dev/fd' and the
  7108.      associated `/dev/stdin', `/dev/stdout', and `/dev/stderr' files,
  7109.      you may get different output from `gawk' than you would get on a
  7110.      system without those files.  When `gawk' interprets these files
  7111.      internally, it synchronizes output to the standard output with
  7112.      output to `/dev/stdout', while on a system with those files, the
  7113.      output is actually to different open files (*note Special File
  7114.      Names in `gawk': Special Files.).
  7115.    * Syntactically invalid single character programs tend to overflow
  7116.      the parse stack, generating a rather unhelpful message.  Such
  7117.      programs are surprisingly difficult to diagnose in the completely
  7118.      general case, and the effort to do so really is not worth it.
  7119. File: gawk.info,  Node: Library Functions,  Next: Sample Programs,  Prev: Invoking Gawk,  Up: Top
  7120. A Library of `awk' Functions
  7121. ****************************
  7122.    This chapter presents a library of useful `awk' functions.  The
  7123. sample programs presented later (*note Practical `awk' Programs: Sample
  7124. Programs.) use these functions.  The functions are presented here in a
  7125. progression from simple to complex.
  7126.    *Note Extracting Programs from Texinfo Source Files: Extract Program,
  7127. presents a program that you can use to extract the source code for
  7128. these example library functions and programs from the Texinfo source
  7129. for this Info file.  (This has already been done as part of the `gawk'
  7130. distribution.)
  7131.    If you have written one or more useful, general purpose `awk'
  7132. functions, and would like to contribute them for a subsequent edition
  7133. of this Info file, please contact the author.  *Note Reporting Problems
  7134. and Bugs: Bugs, for information on doing this.  Don't just send code,
  7135. as you will be required to either place your code in the public domain,
  7136. publish it under the GPL (*note GNU GENERAL PUBLIC LICENSE: Copying.),
  7137. or assign the copyright in it to the Free Software Foundation.
  7138. * Menu:
  7139. * Portability Notes::           What to do if you don't have `gawk'.
  7140. * Nextfile Function::           Two implementations of a `nextfile'
  7141.                                 function.
  7142. * Assert Function::             A function for assertions in `awk'
  7143.                                 programs.
  7144. * Round Function::              A function for rounding if `sprintf' does
  7145.                                 not do it correctly.
  7146. * Ordinal Functions::           Functions for using characters as numbers and
  7147.                                 vice versa.
  7148. * Join Function::               A function to join an array into a string.
  7149. * Mktime Function::             A function to turn a date into a timestamp.
  7150. * Gettimeofday Function::       A function to get formatted times.
  7151. * Filetrans Function::          A function for handling data file transitions.
  7152. * Getopt Function::             A function for processing command line
  7153.                                 arguments.
  7154. * Passwd Functions::            Functions for getting user information.
  7155. * Group Functions::             Functions for getting group information.
  7156. * Library Names::               How to best name private global variables in
  7157.                                 library functions.
  7158. File: gawk.info,  Node: Portability Notes,  Next: Nextfile Function,  Prev: Library Functions,  Up: Library Functions
  7159. Simulating `gawk'-specific Features
  7160. ===================================
  7161.    The programs in this chapter and in *Note Practical `awk' Programs:
  7162. Sample Programs, freely use features that are specific to `gawk'.  This
  7163. section briefly discusses how you can rewrite these programs for
  7164. different implementations of `awk'.
  7165.    Diagnostic error messages are sent to `/dev/stderr'.  Use `| "cat
  7166. 1>&2"' instead of `> "/dev/stderr"', if your system does not have a
  7167. `/dev/stderr', or if you cannot use `gawk'.
  7168.    A number of programs use `nextfile' (*note The `nextfile' Statement:
  7169. Nextfile Statement.), to skip any remaining input in the input file.
  7170. *Note Implementing `nextfile' as a Function: Nextfile Function, shows
  7171. you how to write a function that will do the same thing.
  7172.    Finally, some of the programs choose to ignore upper-case and
  7173. lower-case distinctions in their input. They do this by assigning one
  7174. to `IGNORECASE'.  You can achieve the same effect by adding the
  7175. following rule to the beginning of the program:
  7176.      # ignore case
  7177.      { $0 = tolower($0) }
  7178. Also, verify that all regexp and string constants used in comparisons
  7179. only use lower-case letters.
  7180. File: gawk.info,  Node: Nextfile Function,  Next: Assert Function,  Prev: Portability Notes,  Up: Library Functions
  7181. Implementing `nextfile' as a Function
  7182. =====================================
  7183.    The `nextfile' statement presented in *Note The `nextfile'
  7184. Statement: Nextfile Statement, is a `gawk'-specific extension.  It is
  7185. not available in other implementations of `awk'.  This section shows
  7186. two versions of a `nextfile' function that you can use to simulate
  7187. `gawk''s `nextfile' statement if you cannot use `gawk'.
  7188.    Here is a first attempt at writing a `nextfile' function.
  7189.      # nextfile --- skip remaining records in current file
  7190.      
  7191.      # this should be read in before the "main" awk program
  7192.      
  7193.      function nextfile()    { _abandon_ = FILENAME; next }
  7194.      
  7195.      _abandon_ == FILENAME  { next }
  7196.    This file should be included before the main program, because it
  7197. supplies a rule that must be executed first.  This rule compares the
  7198. current data file's name (which is always in the `FILENAME' variable)
  7199. to a private variable named `_abandon_'.  If the file name matches,
  7200. then the action part of the rule executes a `next' statement, to go on
  7201. to the next record.  (The use of `_' in the variable name is a
  7202. convention.  It is discussed more fully in *Note Naming Library
  7203. Function Global Variables: Library Names.)
  7204.    The use of the `next' statement effectively creates a loop that reads
  7205. all the records from the current data file.  Eventually, the end of the
  7206. file is reached, and a new data file is opened, changing the value of
  7207. `FILENAME'.  Once this happens, the comparison of `_abandon_' to
  7208. `FILENAME' fails, and execution continues with the first rule of the
  7209. "real" program.
  7210.    The `nextfile' function itself simply sets the value of `_abandon_'
  7211. and then executes a `next' statement to start the loop going.(1)
  7212.    This initial version has a subtle problem.  What happens if the same
  7213. data file is listed *twice* on the command line, one right after the
  7214. other, or even with just a variable assignment between the two
  7215. occurrences of the file name?
  7216.    In such a case, this code will skip right through the file, a second
  7217. time, even though it should stop when it gets to the end of the first
  7218. occurrence.  Here is a second version of `nextfile' that remedies this
  7219. problem.
  7220.      # nextfile --- skip remaining records in current file
  7221.      # correctly handle successive occurrences of the same file
  7222.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  7223.      # May, 1993
  7224.      
  7225.      # this should be read in before the "main" awk program
  7226.      
  7227.      function nextfile()   { _abandon_ = FILENAME; next }
  7228.      
  7229.      _abandon_ == FILENAME {
  7230.            if (FNR == 1)
  7231.                _abandon_ = ""
  7232.            else
  7233.                next
  7234.      }
  7235.    The `nextfile' function has not changed.  It sets `_abandon_' equal
  7236. to the current file name and then executes a `next' satement.  The
  7237. `next' statement reads the next record and increments `FNR', so `FNR'
  7238. is guaranteed to have a value of at least two.  However, if `nextfile'
  7239. is called for the last record in the file, then `awk' will close the
  7240. current data file and move on to the next one.  Upon doing so,
  7241. `FILENAME' will be set to the name of the new file, and `FNR' will be
  7242. reset to one.  If this next file is the same as the previous one,
  7243. `_abandon_' will still be equal to `FILENAME'.  However, `FNR' will be
  7244. equal to one, telling us that this is a new occurrence of the file, and
  7245. not the one we were reading when the `nextfile' function was executed.
  7246. In that case, `_abandon_' is reset to the empty string, so that further
  7247. executions of this rule will fail (until the next time that `nextfile'
  7248. is called).
  7249.    If `FNR' is not one, then we are still in the original data file,
  7250. and the program executes a `next' statement to skip through it.
  7251.    An important question to ask at this point is: "Given that the
  7252. functionality of `nextfile' can be provided with a library file, why is
  7253. it built into `gawk'?"  This is an important question.  Adding features
  7254. for little reason leads to larger, slower programs that are harder to
  7255. maintain.
  7256.    The answer is that building `nextfile' into `gawk' provides
  7257. significant gains in efficiency.  If the `nextfile' function is executed
  7258. at the beginning of a large data file, `awk' still has to scan the
  7259. entire file, splitting it up into records, just to skip over it.  The
  7260. built-in `nextfile' can simply close the file immediately and proceed
  7261. to the next one, saving a lot of time.  This is particularly important
  7262. in `awk', since `awk' programs are generally I/O bound (i.e.  they
  7263. spend most of their time doing input and output, instead of performing
  7264. computations).
  7265.    ---------- Footnotes ----------
  7266.    (1)  Some implementations of `awk' do not allow you to execute
  7267. `next' from within a function body. Some other work-around will be
  7268. necessary if you use such a version.
  7269. File: gawk.info,  Node: Assert Function,  Next: Round Function,  Prev: Nextfile Function,  Up: Library Functions
  7270. Assertions
  7271. ==========
  7272.    When writing large programs, it is often useful to be able to know
  7273. that a condition or set of conditions is true.  Before proceeding with a
  7274. particular computation, you make a statement about what you believe to
  7275. be the case.  Such a statement is known as an "assertion."  The C
  7276. language provides an `<assert.h>' header file and corresponding
  7277. `assert' macro that the programmer can use to make assertions.  If an
  7278. assertion fails, the `assert' macro arranges to print a diagnostic
  7279. message describing the condition that should have been true but was
  7280. not, and then it kills the program.  In C, using `assert' looks this:
  7281.      #include <assert.h>
  7282.      
  7283.      int myfunc(int a, double b)
  7284.      {
  7285.           assert(a <= 5 && b >= 17);
  7286.           ...
  7287.      }
  7288.    If the assertion failed, the program would print a message similar to
  7289. this:
  7290.      prog.c:5: assertion failed: a <= 5 && b >= 17
  7291.    The ANSI C language makes it possible to turn the condition into a
  7292. string for use in printing the diagnostic message.  This is not
  7293. possible in `awk', so this `assert' function also requires a string
  7294. version of the condition that is being tested.
  7295.      # assert --- assert that a condition is true. Otherwise exit.
  7296.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  7297.      # May, 1993
  7298.      
  7299.      function assert(condition, string)
  7300.      {
  7301.          if (! condition) {
  7302.              printf("%s:%d: assertion failed: %s\n",
  7303.                  FILENAME, FNR, string) > "/dev/stderr"
  7304.              _assert_exit = 1
  7305.              exit 1
  7306.          }
  7307.      }
  7308.      
  7309.      END {
  7310.          if (_assert_exit)
  7311.              exit 1
  7312.      }
  7313.    The `assert' function tests the `condition' parameter. If it is
  7314. false, it prints a message to standard error, using the `string'
  7315. parameter to describe the failed condition.  It then sets the variable
  7316. `_assert_exit' to one, and executes the `exit' statement.  The `exit'
  7317. statement jumps to the `END' rule. If the `END' rules finds
  7318. `_assert_exit' to be true, then it exits immediately.
  7319.    The purpose of the `END' rule with its test is to keep any other
  7320. `END' rules from running.  When an assertion fails, the program should
  7321. exit immediately.  If no assertions fail, then `_assert_exit' will
  7322. still be false when the `END' rule is run normally, and the rest of the
  7323. program's `END' rules will execute.  For all of this to work correctly,
  7324. `assert.awk' must be the first source file read by `awk'.
  7325.    You would use this function in your programs this way:
  7326.      function myfunc(a, b)
  7327.      {
  7328.           assert(a <= 5 && b >= 17, "a <= 5 && b >= 17")
  7329.           ...
  7330.      }
  7331. If the assertion failed, you would see a message like this:
  7332.      mydata:1357: assertion failed: a <= 5 && b >= 17
  7333.    There is a problem with this version of `assert', that it may not be
  7334. possible to work around.  An `END' rule is automatically added to the
  7335. program calling `assert'.  Normally, if a program consists of just a
  7336. `BEGIN' rule, the input files and/or standard input are not read.
  7337. However, now that the program has an `END' rule, `awk' will attempt to
  7338. read the input data files, or standard input (*note Startup and Cleanup
  7339. Actions: Using BEGIN/END.), most likely causing the program to hang,
  7340. waiting for input.
  7341. File: gawk.info,  Node: Round Function,  Next: Ordinal Functions,  Prev: Assert Function,  Up: Library Functions
  7342. Rounding Numbers
  7343. ================
  7344.    The way `printf' and `sprintf' (*note Using `printf' Statements for
  7345. Fancier Printing: Printf.) do rounding will often depend upon the
  7346. system's C `sprintf' subroutine.  On many machines, `sprintf' rounding
  7347. is "unbiased," which means it doesn't always round a trailing `.5' up,
  7348. contrary to naive expectations.  In unbiased rounding, `.5' rounds to
  7349. even, rather than always up, so 1.5 rounds to 2 but 4.5 rounds to 4.
  7350. The result is that if you are using a format that does rounding (e.g.,
  7351. `"%.0f"') you should check what your system does.  The following
  7352. function does traditional rounding; it might be useful if your awk's
  7353. `printf' does unbiased rounding.
  7354.      # round --- do normal rounding
  7355.      #
  7356.      # Arnold Robbins, arnold@gnu.ai.mit.edu, August, 1996
  7357.      # Public Domain
  7358.      
  7359.      function round(x,   ival, aval, fraction)
  7360.      {
  7361.         ival = int(x)    # integer part, int() truncates
  7362.      
  7363.         # see if fractional part
  7364.         if (ival == x)   # no fraction
  7365.            return x
  7366.      
  7367.         if (x < 0) {
  7368.            aval = -x     # absolute value
  7369.            ival = int(aval)
  7370.            fraction = aval - ival
  7371.            if (fraction >= .5)
  7372.               return int(x) - 1   # -2.5 --> -3
  7373.            else
  7374.               return int(x)       # -2.3 --> -2
  7375.         } else {
  7376.            fraction = x - ival
  7377.            if (fraction >= .5)
  7378.               return ival + 1
  7379.            else
  7380.               return ival
  7381.         }
  7382.      }
  7383.      
  7384.      # test harness
  7385.      { print $0, round($0) }
  7386. File: gawk.info,  Node: Ordinal Functions,  Next: Join Function,  Prev: Round Function,  Up: Library Functions
  7387. Translating Between Characters and Numbers
  7388. ==========================================
  7389.    One commercial implementation of `awk' supplies a built-in function,
  7390. `ord', which takes a character and returns the numeric value for that
  7391. character in the machine's character set.  If the string passed to
  7392. `ord' has more than one character, only the first one is used.
  7393.    The inverse of this function is `chr' (from the function of the same
  7394. name in Pascal), which takes a number and returns the corresponding
  7395. character.
  7396.    Both functions can be written very nicely in `awk'; there is no real
  7397. reason to build them into the `awk' interpreter.
  7398.      # ord.awk --- do ord and chr
  7399.      #
  7400.      # Global identifiers:
  7401.      #    _ord_:        numerical values indexed by characters
  7402.      #    _ord_init:    function to initialize _ord_
  7403.      #
  7404.      # Arnold Robbins
  7405.      # arnold@gnu.ai.mit.edu
  7406.      # Public Domain
  7407.      # 16 January, 1992
  7408.      # 20 July, 1992, revised
  7409.      
  7410.      BEGIN    { _ord_init() }
  7411.      
  7412.      function _ord_init(    low, high, i, t)
  7413.      {
  7414.          low = sprintf("%c", 7) # BEL is ascii 7
  7415.          if (low == "\a") {    # regular ascii
  7416.              low = 0
  7417.              high = 127
  7418.          } else if (sprintf("%c", 128 + 7) == "\a") {
  7419.              # ascii, mark parity
  7420.              low = 128
  7421.              high = 255
  7422.          } else {        # ebcdic(!)
  7423.              low = 0
  7424.              high = 255
  7425.          }
  7426.      
  7427.          for (i = low; i <= high; i++) {
  7428.              t = sprintf("%c", i)
  7429.              _ord_[t] = i
  7430.          }
  7431.      }
  7432.    Some explanation of the numbers used by `chr' is worthwhile.  The
  7433. most prominent character set in use today is ASCII. Although an
  7434. eight-bit byte can hold 256 distinct values (from zero to 255), ASCII
  7435. only defines characters that use the values from zero to 127.(1) At
  7436. least one computer manufacturer that we know of uses ASCII, but with
  7437. mark parity, meaning that the leftmost bit in the byte is always one.
  7438. What this means is that on those systems, characters have numeric
  7439. values from 128 to 255.  Finally, large mainframe systems use the
  7440. EBCDIC character set, which uses all 256 values.  While there are other
  7441. character sets in use on some older systems, they are not really worth
  7442. worrying about.
  7443.      function ord(str,    c)
  7444.      {
  7445.          # only first character is of interest
  7446.          c = substr(str, 1, 1)
  7447.          return _ord_[c]
  7448.      }
  7449.      
  7450.      function chr(c)
  7451.      {
  7452.          # force c to be numeric by adding 0
  7453.          return sprintf("%c", c + 0)
  7454.      }
  7455.      
  7456.      #### test code ####
  7457.      # BEGIN    \
  7458.      # {
  7459.      #    for (;;) {
  7460.      #        printf("enter a character: ")
  7461.      #        if (getline var <= 0)
  7462.      #            break
  7463.      #        printf("ord(%s) = %d\n", var, ord(var))
  7464.      #    }
  7465.      # }
  7466.    An obvious improvement to these functions would be to move the code
  7467. for the `_ord_init' function into the body of the `BEGIN' rule.  It was
  7468. written this way initially for ease of development.
  7469.    There is a "test program" in a `BEGIN' rule, for testing the
  7470. function.  It is commented out for production use.
  7471.    ---------- Footnotes ----------
  7472.    (1)  ASCII has been extended in many countries to use the values
  7473. from 128 to 255 for country-specific characters.  If your  system uses
  7474. these extensions, you can simplify `_ord_init' to simply loop from zero
  7475. to 255.
  7476. File: gawk.info,  Node: Join Function,  Next: Mktime Function,  Prev: Ordinal Functions,  Up: Library Functions
  7477. Merging an Array Into a String
  7478. ==============================
  7479.    When doing string processing, it is often useful to be able to join
  7480. all the strings in an array into one long string.  The following
  7481. function, `join', accomplishes this task.  It is used later in several
  7482. of the application programs (*note Practical `awk' Programs: Sample
  7483. Programs.).
  7484.    Good function design is important; this function needs to be
  7485. general, but it should also have a reasonable default behavior.  It is
  7486. called with an array and the beginning and ending indices of the
  7487. elements in the array to be merged.  This assumes that the array
  7488. indices are numeric--a reasonable assumption since the array was likely
  7489. created with `split' (*note Built-in Functions for String Manipulation:
  7490. String Functions.).
  7491.      # join.awk --- join an array into a string
  7492.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  7493.      # May 1993
  7494.      
  7495.      function join(array, start, end, sep,    result, i)
  7496.      {
  7497.          if (sep == "")
  7498.             sep = " "
  7499.          else if (sep == SUBSEP) # magic value
  7500.             sep = ""
  7501.          result = array[start]
  7502.          for (i = start + 1; i <= end; i++)
  7503.              result = result sep array[i]
  7504.          return result
  7505.      }
  7506.    An optional additional argument is the separator to use when joining
  7507. the strings back together.  If the caller supplies a non-empty value,
  7508. `join' uses it.  If it is not supplied, it will have a null value.  In
  7509. this case, `join' uses a single blank as a default separator for the
  7510. strings.  If the value is equal to `SUBSEP', then `join' joins the
  7511. strings with no separator between them.  `SUBSEP' serves as a "magic"
  7512. value to indicate that there should be no separation between the
  7513. component strings.
  7514.    It would be nice if `awk' had an assignment operator for
  7515. concatenation.  The lack of an explicit operator for concatenation
  7516. makes string operations more difficult than they really need to be.
  7517. File: gawk.info,  Node: Mktime Function,  Next: Gettimeofday Function,  Prev: Join Function,  Up: Library Functions
  7518. Turning Dates Into Timestamps
  7519. =============================
  7520.    The `systime' function built in to `gawk' returns the current time
  7521. of day as a timestamp in "seconds since the Epoch."  This timestamp can
  7522. be converted into a printable date of almost infinitely variable format
  7523. using the built-in `strftime' function.  (For more information on
  7524. `systime' and `strftime', *note Functions for Dealing with Time Stamps:
  7525. Time Functions..)
  7526.    An interesting but difficult problem is to convert a readable
  7527. representation of a date back into a timestamp.  The ANSI C library
  7528. provides a `mktime' function that does the basic job, converting a
  7529. canonical representation of a date into a timestamp.
  7530.    It would appear at first glance that `gawk' would have to supply a
  7531. `mktime' built-in function that was simply a "hook" to the C language
  7532. version.  In fact though, `mktime' can be implemented entirely in `awk'.
  7533.    Here is a version of `mktime' for `awk'.  It takes a simple
  7534. representation of the date and time, and converts it into a timestamp.
  7535.    The code is presented here intermixed with explanatory prose.  In
  7536. *Note Extracting Programs from Texinfo Source Files: Extract Program,
  7537. you will see how the Texinfo source file for this Info file can be
  7538. processed to extract the code into a single source file.
  7539.    The program begins with a descriptive comment and a `BEGIN' rule
  7540. that initializes a table `_tm_months'.  This table is a two-dimensional
  7541. array that has the lengths of the months.  The first index is zero for
  7542. regular years, and one for leap years.  The values are the same for all
  7543. the months in both kinds of years, except for February; thus the use of
  7544. multiple assignment.
  7545.      # mktime.awk --- convert a canonical date representation
  7546.      #                into a timestamp
  7547.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  7548.      # May 1993
  7549.      
  7550.      BEGIN    \
  7551.      {
  7552.          # Initialize table of month lengths
  7553.          _tm_months[0,1] = _tm_months[1,1] = 31
  7554.          _tm_months[0,2] = 28; _tm_months[1,2] = 29
  7555.          _tm_months[0,3] = _tm_months[1,3] = 31
  7556.          _tm_months[0,4] = _tm_months[1,4] = 30
  7557.          _tm_months[0,5] = _tm_months[1,5] = 31
  7558.          _tm_months[0,6] = _tm_months[1,6] = 30
  7559.          _tm_months[0,7] = _tm_months[1,7] = 31
  7560.          _tm_months[0,8] = _tm_months[1,8] = 31
  7561.          _tm_months[0,9] = _tm_months[1,9] = 30
  7562.          _tm_months[0,10] = _tm_months[1,10] = 31
  7563.          _tm_months[0,11] = _tm_months[1,11] = 30
  7564.          _tm_months[0,12] = _tm_months[1,12] = 31
  7565.      }
  7566.    The benefit of merging multiple `BEGIN' rules (*note The `BEGIN' and
  7567. `END' Special Patterns: BEGIN/END.) is particularly clear when writing
  7568. library files.  Functions in library files can cleanly initialize their
  7569. own private data and also provide clean-up actions in private `END'
  7570. rules.
  7571.    The next function is a simple one that computes whether a given year
  7572. is or is not a leap year.  If a year is evenly divisible by four, but
  7573. not evenly divisible by 100, or if it is evenly divisible by 400, then
  7574. it is a leap year.  Thus, 1904 was a leap year, 1900 was not, but 2000
  7575. will be.
  7576.      # decide if a year is a leap year
  7577.      function _tm_isleap(year,    ret)
  7578.      {
  7579.          ret = (year % 4 == 0 && year % 100 != 0) ||
  7580.                  (year % 400 == 0)
  7581.      
  7582.          return ret
  7583.      }
  7584.    This function is only used a few times in this file, and its
  7585. computation could have been written "in-line" (at the point where it's
  7586. used).  Making it a separate function made the original development
  7587. easier, and also avoids the possibility of typing errors when
  7588. duplicating the code in multiple places.
  7589.    The next function is more interesting.  It does most of the work of
  7590. generating a timestamp, which is converting a date and time into some
  7591. number of seconds since the Epoch.  The caller passes an array (rather
  7592. imaginatively named `a') containing six values: the year including
  7593. century, the month as a number between one and 12, the day of the
  7594. month, the hour as a number between zero and 23, the minute in the
  7595. hour, and the seconds within the minute.
  7596.    The function uses several local variables to precompute the number of
  7597. seconds in an hour, seconds in a day, and seconds in a year.  Often,
  7598. similar C code simply writes out the expression in-line, expecting the
  7599. compiler to do "constant folding".  E.g., most C compilers would turn
  7600. `60 * 60' into `3600' at compile time, instead of recomputing it every
  7601. time at run time.  Precomputing these values makes the function more
  7602. efficient.
  7603.      # convert a date into seconds
  7604.      function _tm_addup(a,    total, yearsecs, daysecs,
  7605.                               hoursecs, i, j)
  7606.      {
  7607.          hoursecs = 60 * 60
  7608.          daysecs = 24 * hoursecs
  7609.          yearsecs = 365 * daysecs
  7610.      
  7611.          total = (a[1] - 1970) * yearsecs
  7612.      
  7613.          # extra day for leap years
  7614.          for (i = 1970; i < a[1]; i++)
  7615.              if (_tm_isleap(i))
  7616.                  total += daysecs
  7617.      
  7618.          j = _tm_isleap(a[1])
  7619.          for (i = 1; i < a[2]; i++)
  7620.              total += _tm_months[j, i] * daysecs
  7621.      
  7622.          total += (a[3] - 1) * daysecs
  7623.          total += a[4] * hoursecs
  7624.          total += a[5] * 60
  7625.          total += a[6]
  7626.      
  7627.          return total
  7628.      }
  7629.    The function starts with a first approximation of all the seconds
  7630. between Midnight, January 1, 1970,(1) and the beginning of the current
  7631. year.  It then goes through all those years, and for every leap year,
  7632. adds an additional day's worth of seconds.
  7633.    The variable `j' holds either one or zero, if the current year is or
  7634. is not a leap year.  For every month in the current year prior to the
  7635. current month, it adds the number of seconds in the month, using the
  7636. appropriate entry in the `_tm_months' array.
  7637.    Finally, it adds in the seconds for the number of days prior to the
  7638. current day, and the number of hours, minutes, and seconds in the
  7639. current day.
  7640.    The result is a count of seconds since January 1, 1970.  This value
  7641. is not yet what is needed though.  The reason why is described shortly.
  7642.    The main `mktime' function takes a single character string argument.
  7643. This string is a representation of a date and time in a "canonical"
  7644. (fixed) form.  This string should be `"YEAR MONTH DAY HOUR MINUTE
  7645. SECOND"'.
  7646.      # mktime --- convert a date into seconds,
  7647.      #            compensate for time zone
  7648.      
  7649.      function mktime(str,    res1, res2, a, b, i, j, t, diff)
  7650.      {
  7651.          i = split(str, a, " ")    # don't rely on FS
  7652.      
  7653.          if (i != 6)
  7654.              return -1
  7655.      
  7656.          # force numeric
  7657.          for (j in a)
  7658.              a[j] += 0
  7659.      
  7660.          # validate
  7661.          if (a[1] < 1970 ||
  7662.              a[2] < 1 || a[2] > 12 ||
  7663.              a[3] < 1 || a[3] > 31 ||
  7664.              a[4] < 0 || a[4] > 23 ||
  7665.              a[5] < 0 || a[5] > 59 ||
  7666.              a[6] < 0 || a[6] > 60 )
  7667.                  return -1
  7668.      
  7669.          res1 = _tm_addup(a)
  7670.          t = strftime("%Y %m %d %H %M %S", res1)
  7671.      
  7672.          if (_tm_debug)
  7673.              printf("(%s) -> (%s)\n", str, t) > "/dev/stderr"
  7674.      
  7675.          split(t, b, " ")
  7676.          res2 = _tm_addup(b)
  7677.      
  7678.          diff = res1 - res2
  7679.      
  7680.          if (_tm_debug)
  7681.              printf("diff = %d seconds\n", diff) > "/dev/stderr"
  7682.      
  7683.          res1 += diff
  7684.      
  7685.          return res1
  7686.      }
  7687.    The function first splits the string into an array, using spaces and
  7688. tabs as separators.  If there are not six elements in the array, it
  7689. returns an error, signaled as the value -1.  Next, it forces each
  7690. element of the array to be numeric, by adding zero to it.  The
  7691. following `if' statement then makes sure that each element is within an
  7692. allowable range.  (This checking could be extended further, e.g., to
  7693. make sure that the day of the month is within the correct range for the
  7694. particular month supplied.)  All of this is essentially preliminary
  7695. set-up and error checking.
  7696.    Recall that `_tm_addup' generated a value in seconds since Midnight,
  7697. January 1, 1970.  This value is not directly usable as the result we
  7698. want, *since the calculation does not account for the local timezone*.
  7699. In other words, the value represents the count in seconds since the
  7700. Epoch, but only for UTC (Universal Coordinated Time).  If the local
  7701. timezone is east or west of UTC, then some number of hours should be
  7702. either added to, or subtracted from the resulting timestamp.
  7703.    For example, 6:23 p.m. in Atlanta, Georgia (USA), is normally five
  7704. hours west of (behind) UTC.  It is only four hours behind UTC if
  7705. daylight savings time is in effect.  If you are calling `mktime' in
  7706. Atlanta, with the argument `"1993 5 23 18 23 12"', the result from
  7707. `_tm_addup' will be for 6:23 p.m. UTC, which is only 2:23 p.m. in
  7708. Atlanta.  It is necessary to add another four hours worth of seconds to
  7709. the result.
  7710.    How can `mktime' determine how far away it is from UTC?  This is
  7711. surprisingly easy.  The returned timestamp represents the time passed to
  7712. `mktime' *as UTC*.  This timestamp can be fed back to `strftime', which
  7713. will format it as a *local* time; i.e. as if it already had the UTC
  7714. difference added in to it.  This is done by giving
  7715. `"%Y %m %d %H %M %S"' to `strftime' as the format argument.  It returns
  7716. the computed timestamp in the original string format.  The result
  7717. represents a time that accounts for the UTC difference.  When the new
  7718. time is converted back to a timestamp, the difference between the two
  7719. timestamps is the difference (in seconds) between the local timezone
  7720. and UTC.  This difference is then added back to the original result.
  7721. An example demonstrating this is presented below.
  7722.    Finally, there is a "main" program for testing the function.
  7723.      BEGIN  {
  7724.          if (_tm_test) {
  7725.              printf "Enter date as yyyy mm dd hh mm ss: "
  7726.              getline _tm_test_date
  7727.      
  7728.              t = mktime(_tm_test_date)
  7729.              r = strftime("%Y %m %d %H %M %S", t)
  7730.              printf "Got back (%s)\n", r
  7731.          }
  7732.      }
  7733.    The entire program uses two variables that can be set on the command
  7734. line to control debugging output and to enable the test in the final
  7735. `BEGIN' rule.  Here is the result of a test run. (Note that debugging
  7736. output is to standard error, and test output is to standard output.)
  7737.      $ gawk -f mktime.awk -v _tm_test=1 -v _tm_debug=1
  7738.      -| Enter date as yyyy mm dd hh mm ss: 1993 5 23 15 35 10
  7739.      error--> (1993 5 23 15 35 10) -> (1993 05 23 11 35 10)
  7740.      error--> diff = 14400 seconds
  7741.      -| Got back (1993 05 23 15 35 10)
  7742.    The time entered was 3:35 p.m. (15:35 on a 24-hour clock), on May
  7743. 23, 1993.  The first line of debugging output shows the resulting time
  7744. as UTC--four hours ahead of the local time zone.  The second line shows
  7745. that the difference is 14400 seconds, which is four hours.  (The
  7746. difference is only four hours, since daylight savings time is in effect
  7747. during May.) The final line of test output shows that the timezone
  7748. compensation algorithm works; the returned time is the same as the
  7749. entered time.
  7750.    This program does not solve the general problem of turning an
  7751. arbitrary date representation into a timestamp.  That problem is very
  7752. involved.  However, the `mktime' function provides a foundation upon
  7753. which to build. Other software can convert month names into numeric
  7754. months, and AM/PM times into 24-hour clocks, to generate the
  7755. "canonical" format that `mktime' requires.
  7756.    ---------- Footnotes ----------
  7757.    (1)  This is the Epoch on POSIX systems.  It may be different on
  7758. other systems.
  7759. File: gawk.info,  Node: Gettimeofday Function,  Next: Filetrans Function,  Prev: Mktime Function,  Up: Library Functions
  7760. Managing the Time of Day
  7761. ========================
  7762.    The `systime' and `strftime' functions described in *Note Functions
  7763. for Dealing with Time Stamps: Time Functions, provide the minimum
  7764. functionality necessary for dealing with the time of day in human
  7765. readable form.  While `strftime' is extensive, the control formats are
  7766. not necessarily easy to remember or intuitively obvious when reading a
  7767. program.
  7768.    The following function, `gettimeofday', populates a user-supplied
  7769. array with pre-formatted time information.  It returns a string with
  7770. the current time formatted in the same way as the `date' utility.
  7771.      # gettimeofday --- get the time of day in a usable format
  7772.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain, May 1993
  7773.      #
  7774.      # Returns a string in the format of output of date(1)
  7775.      # Populates the array argument time with individual values:
  7776.      #    time["second"]       -- seconds (0 - 59)
  7777.      #    time["minute"]       -- minutes (0 - 59)
  7778.      #    time["hour"]         -- hours (0 - 23)
  7779.      #    time["althour"]      -- hours (0 - 12)
  7780.      #    time["monthday"]     -- day of month (1 - 31)
  7781.      #    time["month"]        -- month of year (1 - 12)
  7782.      #    time["monthname"]    -- name of the month
  7783.      #    time["shortmonth"]   -- short name of the month
  7784.      #    time["year"]         -- year within century (0 - 99)
  7785.      #    time["fullyear"]     -- year with century (19xx or 20xx)
  7786.      #    time["weekday"]      -- day of week (Sunday = 0)
  7787.      #    time["altweekday"]   -- day of week (Monday = 0)
  7788.      #    time["weeknum"]      -- week number, Sunday first day
  7789.      #    time["altweeknum"]   -- week number, Monday first day
  7790.      #    time["dayname"]      -- name of weekday
  7791.      #    time["shortdayname"] -- short name of weekday
  7792.      #    time["yearday"]      -- day of year (0 - 365)
  7793.      #    time["timezone"]     -- abbreviation of timezone name
  7794.      #    time["ampm"]         -- AM or PM designation
  7795.      
  7796.      function gettimeofday(time,    ret, now, i)
  7797.      {
  7798.          # get time once, avoids unnecessary system calls
  7799.          now = systime()
  7800.      
  7801.          # return date(1)-style output
  7802.          ret = strftime("%a %b %d %H:%M:%S %Z %Y", now)
  7803.      
  7804.          # clear out target array
  7805.          for (i in time)
  7806.              delete time[i]
  7807.      
  7808.          # fill in values, force numeric values to be
  7809.          # numeric by adding 0
  7810.          time["second"]       = strftime("%S", now) + 0
  7811.          time["minute"]       = strftime("%M", now) + 0
  7812.          time["hour"]         = strftime("%H", now) + 0
  7813.          time["althour"]      = strftime("%I", now) + 0
  7814.          time["monthday"]     = strftime("%d", now) + 0
  7815.          time["month"]        = strftime("%m", now) + 0
  7816.          time["monthname"]    = strftime("%B", now)
  7817.          time["shortmonth"]   = strftime("%b", now)
  7818.          time["year"]         = strftime("%y", now) + 0
  7819.          time["fullyear"]     = strftime("%Y", now) + 0
  7820.          time["weekday"]      = strftime("%w", now) + 0
  7821.          time["altweekday"]   = strftime("%u", now) + 0
  7822.          time["dayname"]      = strftime("%A", now)
  7823.          time["shortdayname"] = strftime("%a", now)
  7824.          time["yearday"]      = strftime("%j", now) + 0
  7825.          time["timezone"]     = strftime("%Z", now)
  7826.          time["ampm"]         = strftime("%p", now)
  7827.          time["weeknum"]      = strftime("%U", now) + 0
  7828.          time["altweeknum"]   = strftime("%W", now) + 0
  7829.      
  7830.          return ret
  7831.      }
  7832.    The string indices are easier to use and read than the various
  7833. formats required by `strftime'.  The `alarm' program presented in *Note
  7834. An Alarm Clock Program: Alarm Program, uses this function.
  7835.    The `gettimeofday' function is presented above as it was written. A
  7836. more general design for this function would have allowed the user to
  7837. supply an optional timestamp value that would have been used instead of
  7838. the current time.
  7839. File: gawk.info,  Node: Filetrans Function,  Next: Getopt Function,  Prev: Gettimeofday Function,  Up: Library Functions
  7840. Noting Data File Boundaries
  7841. ===========================
  7842.    The `BEGIN' and `END' rules are each executed exactly once, at the
  7843. beginning and end respectively of your `awk' program (*note The `BEGIN'
  7844. and `END' Special Patterns: BEGIN/END.).  We (the `gawk' authors) once
  7845. had a user who mistakenly thought that the `BEGIN' rule was executed at
  7846. the beginning of each data file and the `END' rule was executed at the
  7847. end of each data file.  When informed that this was not the case, the
  7848. user requested that we add new special patterns to `gawk', named
  7849. `BEGIN_FILE' and `END_FILE', that would have the desired behavior.  He
  7850. even supplied us the code to do so.
  7851.    However, after a little thought, I came up with the following
  7852. library program.  It arranges to call two user-supplied functions,
  7853. `beginfile' and `endfile', at the beginning and end of each data file.
  7854. Besides solving the problem in only nine(!) lines of code, it does so
  7855. *portably*; this will work with any implementation of `awk'.
  7856.      # transfile.awk
  7857.      #
  7858.      # Give the user a hook for filename transitions
  7859.      #
  7860.      # The user must supply functions beginfile() and endfile()
  7861.      # that each take the name of the file being started or
  7862.      # finished, respectively.
  7863.      #
  7864.      # Arnold Robbins, arnold@gnu.ai.mit.edu, January 1992
  7865.      # Public Domain
  7866.      
  7867.      FILENAME != _oldfilename \
  7868.      {
  7869.          if (_oldfilename != "")
  7870.              endfile(_oldfilename)
  7871.          _oldfilename = FILENAME
  7872.          beginfile(FILENAME)
  7873.      }
  7874.      
  7875.      END   { endfile(FILENAME) }
  7876.    This file must be loaded before the user's "main" program, so that
  7877. the rule it supplies will be executed first.
  7878.    This rule relies on `awk''s `FILENAME' variable that automatically
  7879. changes for each new data file.  The current file name is saved in a
  7880. private variable, `_oldfilename'.  If `FILENAME' does not equal
  7881. `_oldfilename', then a new data file is being processed, and it is
  7882. necessary to call `endfile' for the old file.  Since `endfile' should
  7883. only be called if a file has been processed, the program first checks
  7884. to make sure that `_oldfilename' is not the null string.  The program
  7885. then assigns the current file name to `_oldfilename', and calls
  7886. `beginfile' for the file.  Since, like all `awk' variables,
  7887. `_oldfilename' will be initialized to the null string, this rule
  7888. executes correctly even for the first data file.
  7889.    The program also supplies an `END' rule, to do the final processing
  7890. for the last file.  Since this `END' rule comes before any `END' rules
  7891. supplied in the "main" program, `endfile' will be called first.  Once
  7892. again the value of multiple `BEGIN' and `END' rules should be clear.
  7893.    This version has same problem as the first version of `nextfile'
  7894. (*note Implementing `nextfile' as a Function: Nextfile Function.).  If
  7895. the same data file occurs twice in a row on command line, then
  7896. `endfile' and `beginfile' will not be executed at the end of the first
  7897. pass and at the beginning of the second pass.  This version solves the
  7898. problem.
  7899.      # ftrans.awk --- handle data file transitions
  7900.      #
  7901.      # user supplies beginfile() and endfile() functions
  7902.      #
  7903.      # Arnold Robbins, arnold@gnu.ai.mit.edu. November 1992
  7904.      # Public Domain
  7905.      
  7906.      FNR == 1 {
  7907.          if (_filename_ != "")
  7908.              endfile(_filename_)
  7909.          _filename_ = FILENAME
  7910.          beginfile(FILENAME)
  7911.      }
  7912.      
  7913.      END  { endfile(_filename_) }
  7914.    In *Note Counting Things: Wc Program, you will see how this library
  7915. function can be used, and how it simplifies writing the main program.
  7916. File: gawk.info,  Node: Getopt Function,  Next: Passwd Functions,  Prev: Filetrans Function,  Up: Library Functions
  7917. Processing Command Line Options
  7918. ===============================
  7919.    Most utilities on POSIX compatible systems take options or
  7920. "switches" on the command line that can be used to change the way a
  7921. program behaves.  `awk' is an example of such a program (*note Command
  7922. Line Options: Options.).  Often, options take "arguments", data that
  7923. the program needs to correctly obey the command line option.  For
  7924. example, `awk''s `-F' option requires a string to use as the field
  7925. separator.  The first occurrence on the command line of either `--' or a
  7926. string that does not begin with `-' ends the options.
  7927.    Most Unix systems provide a C function named `getopt' for processing
  7928. command line arguments.  The programmer provides a string describing
  7929. the one letter options. If an option requires an argument, it is
  7930. followed in the string with a colon.  `getopt' is also passed the count
  7931. and values of the command line arguments, and is called in a loop.
  7932. `getopt' processes the command line arguments for option letters.  Each
  7933. time around the loop, it returns a single character representing the
  7934. next option letter that it found, or `?' if it found an invalid option.
  7935. When it returns -1, there are no options left on the command line.
  7936.    When using `getopt', options that do not take arguments can be
  7937. grouped together.  Furthermore, options that take arguments require
  7938. that the argument be present.  The argument can immediately follow the
  7939. option letter, or it can be a separate command line argument.
  7940.    Given a hypothetical program that takes three command line options,
  7941. `-a', `-b', and `-c', and `-b' requires an argument, all of the
  7942. following are valid ways of invoking the program:
  7943.      prog -a -b foo -c data1 data2 data3
  7944.      prog -ac -bfoo -- data1 data2 data3
  7945.      prog -acbfoo data1 data2 data3
  7946.    Notice that when the argument is grouped with its option, the rest of
  7947. the command line argument is considered to be the option's argument.
  7948. In the above example, `-acbfoo' indicates that all of the `-a', `-b',
  7949. and `-c' options were supplied, and that `foo' is the argument to the
  7950. `-b' option.
  7951.    `getopt' provides four external variables that the programmer can
  7952. `optind'
  7953.      The index in the argument value array (`argv') where the first
  7954.      non-option command line argument can be found.
  7955. `optarg'
  7956.      The string value of the argument to an option.
  7957. `opterr'
  7958.      Usually `getopt' prints an error message when it finds an invalid
  7959.      option.  Setting `opterr' to zero disables this feature.  (An
  7960.      application might wish to print its own error message.)
  7961. `optopt'
  7962.      The letter representing the command line option.  While not
  7963.      usually documented, most versions supply this variable.
  7964.    The following C fragment shows how `getopt' might process command
  7965. line arguments for `awk'.
  7966.      int
  7967.      main(int argc, char *argv[])
  7968.      {
  7969.          ...
  7970.          /* print our own message */
  7971.          opterr = 0;
  7972.          while ((c = getopt(argc, argv, "v:f:F:W:")) != -1) {
  7973.              switch (c) {
  7974.              case 'f':    /* file */
  7975.                  ...
  7976.                  break;
  7977.              case 'F':    /* field separator */
  7978.                  ...
  7979.                  break;
  7980.              case 'v':    /* variable assignment */
  7981.                  ...
  7982.                  break;
  7983.              case 'W':    /* extension */
  7984.                  ...
  7985.                  break;
  7986.              case '?':
  7987.              default:
  7988.                  usage();
  7989.                  break;
  7990.              }
  7991.          }
  7992.          ...
  7993.      }
  7994.    As a side point, `gawk' actually uses the GNU `getopt_long' function
  7995. to process both normal and GNU-style long options (*note Command Line
  7996. Options: Options.).
  7997.    The abstraction provided by `getopt' is very useful, and would be
  7998. quite handy in `awk' programs as well.  Here is an `awk' version of
  7999. `getopt'.  This function highlights one of the greatest weaknesses in
  8000. `awk', which is that it is very poor at manipulating single characters.
  8001. Repeated calls to `substr' are necessary for accessing individual
  8002. characters (*note Built-in Functions for String Manipulation: String
  8003. Functions.).
  8004.    The discussion walks through the code a bit at a time.
  8005.      # getopt --- do C library getopt(3) function in awk
  8006.      #
  8007.      # arnold@gnu.ai.mit.edu
  8008.      # Public domain
  8009.      #
  8010.      # Initial version: March, 1991
  8011.      # Revised: May, 1993
  8012.      
  8013.      # External variables:
  8014.      #    Optind -- index of ARGV for first non-option argument
  8015.      #    Optarg -- string value of argument to current option
  8016.      #    Opterr -- if non-zero, print our own diagnostic
  8017.      #    Optopt -- current option letter
  8018.      
  8019.      # Returns
  8020.      #    -1     at end of options
  8021.      #    ?      for unrecognized option
  8022.      #    <c>    a character representing the current option
  8023.      
  8024.      # Private Data
  8025.      #    _opti  index in multi-flag option, e.g., -abc
  8026.    The function starts out with some documentation: who wrote the code,
  8027. and when it was revised, followed by a list of the global variables it
  8028. uses, what the return values are and what they mean, and any global
  8029. variables that are "private" to this library function.  Such
  8030. documentation is essential for any program, and particularly for
  8031. library functions.
  8032.      function getopt(argc, argv, options,    optl, thisopt, i)
  8033.      {
  8034.          optl = length(options)
  8035.          if (optl == 0)        # no options given
  8036.              return -1
  8037.      
  8038.          if (argv[Optind] == "--") {  # all done
  8039.              Optind++
  8040.              _opti = 0
  8041.              return -1
  8042.          } else if (argv[Optind] !~ /^-[^: \t\n\f\r\v\b]/) {
  8043.              _opti = 0
  8044.              return -1
  8045.          }
  8046.    The function first checks that it was indeed called with a string of
  8047. options (the `options' parameter).  If `options' has a zero length,
  8048. `getopt' immediately returns -1.
  8049.    The next thing to check for is the end of the options.  A `--' ends
  8050. the command line options, as does any command line argument that does
  8051. not begin with a `-'.  `Optind' is used to step through the array of
  8052. command line arguments; it retains its value across calls to `getopt',
  8053. since it is a global variable.
  8054.    The regexp used, `/^-[^: \t\n\f\r\v\b]/', is perhaps a bit of
  8055. overkill; it checks for a `-' followed by anything that is not
  8056. whitespace and not a colon.  If the current command line argument does
  8057. not match this pattern, it is not an option, and it ends option
  8058. processing.
  8059.          if (_opti == 0)
  8060.              _opti = 2
  8061.          thisopt = substr(argv[Optind], _opti, 1)
  8062.          Optopt = thisopt
  8063.          i = index(options, thisopt)
  8064.          if (i == 0) {
  8065.              if (Opterr)
  8066.                  printf("%c -- invalid option\n",
  8067.                                        thisopt) > "/dev/stderr"
  8068.              if (_opti >= length(argv[Optind])) {
  8069.                  Optind++
  8070.                  _opti = 0
  8071.              } else
  8072.                  _opti++
  8073.              return "?"
  8074.          }
  8075.    The `_opti' variable tracks the position in the current command line
  8076. argument (`argv[Optind]').  In the case that multiple options were
  8077. grouped together with one `-' (e.g., `-abx'), it is necessary to return
  8078. them to the user one at a time.
  8079.    If `_opti' is equal to zero, it is set to two, the index in the
  8080. string of the next character to look at (we skip the `-', which is at
  8081. position one).  The variable `thisopt' holds the character, obtained
  8082. with `substr'.  It is saved in `Optopt' for the main program to use.
  8083.    If `thisopt' is not in the `options' string, then it is an invalid
  8084. option.  If `Opterr' is non-zero, `getopt' prints an error message on
  8085. the standard error that is similar to the message from the C version of
  8086. `getopt'.
  8087.    Since the option is invalid, it is necessary to skip it and move on
  8088. to the next option character.  If `_opti' is greater than or equal to
  8089. the length of the current command line argument, then it is necessary
  8090. to move on to the next one, so `Optind' is incremented and `_opti' is
  8091. reset to zero. Otherwise, `Optind' is left alone and `_opti' is merely
  8092. incremented.
  8093.    In any case, since the option was invalid, `getopt' returns `?'.
  8094. The main program can examine `Optopt' if it needs to know what the
  8095. invalid option letter actually was.
  8096.          if (substr(options, i + 1, 1) == ":") {
  8097.              # get option argument
  8098.              if (length(substr(argv[Optind], _opti + 1)) > 0)
  8099.                  Optarg = substr(argv[Optind], _opti + 1)
  8100.              else
  8101.                  Optarg = argv[++Optind]
  8102.              _opti = 0
  8103.          } else
  8104.              Optarg = ""
  8105.    If the option requires an argument, the option letter is followed by
  8106. a colon in the `options' string.  If there are remaining characters in
  8107. the current command line argument (`argv[Optind]'), then the rest of
  8108. that string is assigned to `Optarg'.  Otherwise, the next command line
  8109. argument is used (`-xFOO' vs. `-x FOO'). In either case, `_opti' is
  8110. reset to zero, since there are no more characters left to examine in
  8111. the current command line argument.
  8112.          if (_opti == 0 || _opti >= length(argv[Optind])) {
  8113.              Optind++
  8114.              _opti = 0
  8115.          } else
  8116.              _opti++
  8117.          return thisopt
  8118.      }
  8119.    Finally, if `_opti' is either zero or greater than the length of the
  8120. current command line argument, it means this element in `argv' is
  8121. through being processed, so `Optind' is incremented to point to the
  8122. next element in `argv'.  If neither condition is true, then only
  8123. `_opti' is incremented, so that the next option letter can be processed
  8124. on the next call to `getopt'.
  8125.      BEGIN {
  8126.          Opterr = 1    # default is to diagnose
  8127.          Optind = 1    # skip ARGV[0]
  8128.      
  8129.          # test program
  8130.          if (_getopt_test) {
  8131.              while ((_go_c = getopt(ARGC, ARGV, "ab:cd")) != -1)
  8132.                  printf("c = <%c>, optarg = <%s>\n",
  8133.                                             _go_c, Optarg)
  8134.              printf("non-option arguments:\n")
  8135.              for (; Optind < ARGC; Optind++)
  8136.                  printf("\tARGV[%d] = <%s>\n",
  8137.                                          Optind, ARGV[Optind])
  8138.          }
  8139.      }
  8140.    The `BEGIN' rule initializes both `Opterr' and `Optind' to one.
  8141. `Opterr' is set to one, since the default behavior is for `getopt' to
  8142. print a diagnostic message upon seeing an invalid option.  `Optind' is
  8143. set to one, since there's no reason to look at the program name, which
  8144. is in `ARGV[0]'.
  8145.    The rest of the `BEGIN' rule is a simple test program.  Here is the
  8146. result of two sample runs of the test program.
  8147.      $ awk -f getopt.awk -v _getopt_test=1 -- -a -cbARG bax -x
  8148.      -| c = <a>, optarg = <>
  8149.      -| c = <c>, optarg = <>
  8150.      -| c = <b>, optarg = <ARG>
  8151.      -| non-option arguments:
  8152.      -|         ARGV[3] = <bax>
  8153.      -|         ARGV[4] = <-x>
  8154.      
  8155.      $ awk -f getopt.awk -v _getopt_test=1 -- -a -x -- xyz abc
  8156.      -| c = <a>, optarg = <>
  8157.      error--> x -- invalid option
  8158.      -| c = <?>, optarg = <>
  8159.      -| non-option arguments:
  8160.      -|         ARGV[4] = <xyz>
  8161.      -|         ARGV[5] = <abc>
  8162.    The first `--' terminates the arguments to `awk', so that it does
  8163. not try to interpret the `-a' etc. as its own options.
  8164.    Several of the sample programs presented in *Note Practical `awk'
  8165. Programs: Sample Programs, use `getopt' to process their arguments.
  8166. File: gawk.info,  Node: Passwd Functions,  Next: Group Functions,  Prev: Getopt Function,  Up: Library Functions
  8167. Reading the User Database
  8168. =========================
  8169.    The `/dev/user' special file (*note Special File Names in `gawk':
  8170. Special Files.) provides access to the current user's real and
  8171. effective user and group id numbers, and if available, the user's
  8172. supplementary group set.  However, since these are numbers, they do not
  8173. provide very useful information to the average user.  There needs to be
  8174. some way to find the user information associated with the user and
  8175. group numbers.  This section presents a suite of functions for
  8176. retrieving information from the user database.  *Note Reading the Group
  8177. Database: Group Functions, for a similar suite that retrieves
  8178. information from the group database.
  8179.    The POSIX standard does not define the file where user information is
  8180. kept.  Instead, it provides the `<pwd.h>' header file and several C
  8181. language subroutines for obtaining user information.  The primary
  8182. function is `getpwent', for "get password entry." The "password" comes
  8183. from the original user database file, `/etc/passwd', which kept user
  8184. information, along with the encrypted passwords (hence the name).
  8185.    While an `awk' program could simply read `/etc/passwd' directly (the
  8186. format is well known), because of the way password files are handled on
  8187. networked systems, this file may not contain complete information about
  8188. the system's set of users.
  8189.    To be sure of being able to produce a readable, complete version of
  8190. the user database, it is necessary to write a small C program that
  8191. calls `getpwent'.  `getpwent' is defined to return a pointer to a
  8192. `struct passwd'.  Each time it is called, it returns the next entry in
  8193. the database.  When there are no more entries, it returns `NULL', the
  8194. null pointer.  When this happens, the C program should call `endpwent'
  8195. to close the database.  Here is `pwcat', a C program that "cats" the
  8196. password database.
  8197.      /*
  8198.       * pwcat.c
  8199.       *
  8200.       * Generate a printable version of the password database
  8201.       *
  8202.       * Arnold Robbins
  8203.       * arnold@gnu.ai.mit.edu
  8204.       * May 1993
  8205.       * Public Domain
  8206.       */
  8207.      
  8208.      #include <stdio.h>
  8209.      #include <pwd.h>
  8210.      
  8211.      int
  8212.      main(argc, argv)
  8213.      int argc;
  8214.      char **argv;
  8215.      {
  8216.          struct passwd *p;
  8217.      
  8218.          while ((p = getpwent()) != NULL)
  8219.              printf("%s:%s:%d:%d:%s:%s:%s\n",
  8220.                  p->pw_name, p->pw_passwd, p->pw_uid,
  8221.                  p->pw_gid, p->pw_gecos, p->pw_dir, p->pw_shell);
  8222.      
  8223.          endpwent();
  8224.          exit(0);
  8225.      }
  8226.    If you don't understand C, don't worry about it.  The output from
  8227. `pwcat' is the user database, in the traditional `/etc/passwd' format
  8228. of colon-separated fields.  The fields are:
  8229. Login name
  8230.      The user's login name.
  8231. Encrypted password
  8232.      The user's encrypted password.  This may not be available on some
  8233.      systems.
  8234. User-ID
  8235.      The user's numeric user-id number.
  8236. Group-ID
  8237.      The user's numeric group-id number.
  8238. Full name
  8239.      The user's full name, and perhaps other information associated
  8240.      with the user.
  8241. Home directory
  8242.      The user's login, or "home" directory (familiar to shell
  8243.      programmers as `$HOME').
  8244. Login shell
  8245.      The program that will be run when the user logs in.  This is
  8246.      usually a shell, such as Bash (the Gnu Bourne-Again shell).
  8247.    Here are a few lines representative of `pwcat''s output.
  8248.      $ pwcat
  8249.      -| root:3Ov02d5VaUPB6:0:1:Operator:/:/bin/sh
  8250.      -| nobody:*:65534:65534::/:
  8251.      -| daemon:*:1:1::/:
  8252.      -| sys:*:2:2::/:/bin/csh
  8253.      -| bin:*:3:3::/bin:
  8254.      -| arnold:xyzzy:2076:10:Arnold Robbins:/home/arnold:/bin/sh
  8255.      -| miriam:yxaay:112:10:Miriam Robbins:/home/miriam:/bin/sh
  8256.      -| andy:abcca2:113:10:Andy Jacobs:/home/andy:/bin/sh
  8257.      ...
  8258.    With that introduction, here is a group of functions for getting user
  8259. information.  There are several functions here, corresponding to the C
  8260. functions of the same name.
  8261.      # passwd.awk --- access password file information
  8262.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  8263.      # May 1993
  8264.      
  8265.      BEGIN {
  8266.          # tailor this to suit your system
  8267.          _pw_awklib = "/usr/local/libexec/awk/"
  8268.      }
  8269.      
  8270.      function _pw_init(    oldfs, oldrs, olddol0, pwcat)
  8271.      {
  8272.          if (_pw_inited)
  8273.              return
  8274.          oldfs = FS
  8275.          oldrs = RS
  8276.          olddol0 = $0
  8277.          FS = ":"
  8278.          RS = "\n"
  8279.          pwcat = _pw_awklib "pwcat"
  8280.          while ((pwcat | getline) > 0) {
  8281.              _pw_byname[$1] = $0
  8282.              _pw_byuid[$3] = $0
  8283.              _pw_bycount[++_pw_total] = $0
  8284.          }
  8285.          close(pwcat)
  8286.          _pw_count = 0
  8287.          _pw_inited = 1
  8288.          FS = oldfs
  8289.          RS = oldrs
  8290.          $0 = olddol0
  8291.      }
  8292.    The `BEGIN' rule sets a private variable to the directory where
  8293. `pwcat' is stored.  Since it is used to help out an `awk' library
  8294. routine, we have chosen to put it in `/usr/local/libexec/awk'.  You
  8295. might want it to be in a different directory on your system.
  8296.    The function `_pw_init' keeps three copies of the user information
  8297. in three associative arrays.  The arrays are indexed by user name
  8298. (`_pw_byname'), by user-id number (`_pw_byuid'), and by order of
  8299. occurrence (`_pw_bycount').
  8300.    The variable `_pw_inited' is used for efficiency; `_pw_init' only
  8301. needs to be called once.
  8302.    Since this function uses `getline' to read information from `pwcat',
  8303. it first saves the values of `FS', `RS', and `$0'.  Doing so is
  8304. necessary, since these functions could be called from anywhere within a
  8305. user's program, and the user may have his or her own values for `FS'
  8306. and `RS'.
  8307.    The main part of the function uses a loop to read database lines,
  8308. split the line into fields, and then store the line into each array as
  8309. necessary.  When the loop is done, `_pw_init' cleans up by closing the
  8310. pipeline, setting `_pw_inited' to one, and restoring `FS', `RS', and
  8311. `$0'.  The use of `_pw_count' will be explained below.
  8312.      function getpwnam(name)
  8313.      {
  8314.          _pw_init()
  8315.          if (name in _pw_byname)
  8316.              return _pw_byname[name]
  8317.          return ""
  8318.      }
  8319.    The `getpwnam' function takes a user name as a string argument. If
  8320. that user is in the database, it returns the appropriate line.
  8321. Otherwise it returns the null string.
  8322.      function getpwuid(uid)
  8323.      {
  8324.          _pw_init()
  8325.          if (uid in _pw_byuid)
  8326.              return _pw_byuid[uid]
  8327.          return ""
  8328.      }
  8329.    Similarly, the `getpwuid' function takes a user-id number argument.
  8330. If that user number is in the database, it returns the appropriate
  8331. line. Otherwise it returns the null string.
  8332.      function getpwent()
  8333.      {
  8334.          _pw_init()
  8335.          if (_pw_count < _pw_total)
  8336.              return _pw_bycount[++_pw_count]
  8337.          return ""
  8338.      }
  8339.    The `getpwent' function simply steps through the database, one entry
  8340. at a time.  It uses `_pw_count' to track its current position in the
  8341. `_pw_bycount' array.
  8342.      function endpwent()
  8343.      {
  8344.          _pw_count = 0
  8345.      }
  8346.    The `endpwent' function resets `_pw_count' to zero, so that
  8347. subsequent calls to `getpwent' will start over again.
  8348.    A conscious design decision in this suite is that each subroutine
  8349. calls `_pw_init' to initialize the database arrays.  The overhead of
  8350. running a separate process to generate the user database, and the I/O
  8351. to scan it, will only be incurred if the user's main program actually
  8352. calls one of these functions.  If this library file is loaded along
  8353. with a user's program, but none of the routines are ever called, then
  8354. there is no extra run-time overhead.  (The alternative would be to move
  8355. the body of `_pw_init' into a `BEGIN' rule, which would always run
  8356. `pwcat'.  This simplifies the code but runs an extra process that may
  8357. never be needed.)
  8358.    In turn, calling `_pw_init' is not too expensive, since the
  8359. `_pw_inited' variable keeps the program from reading the data more than
  8360. once.  If you are worried about squeezing every last cycle out of your
  8361. `awk' program, the check of `_pw_inited' could be moved out of
  8362. `_pw_init' and duplicated in all the other functions.  In practice,
  8363. this is not necessary, since most `awk' programs are I/O bound, and it
  8364. would clutter up the code.
  8365.    The `id' program in *Note Printing Out User Information: Id Program,
  8366. uses these functions.
  8367. File: gawk.info,  Node: Group Functions,  Next: Library Names,  Prev: Passwd Functions,  Up: Library Functions
  8368. Reading the Group Database
  8369. ==========================
  8370.    Much of the discussion presented in *Note Reading the User Database:
  8371. Passwd Functions, applies to the group database as well.  Although
  8372. there has traditionally been a well known file, `/etc/group', in a well
  8373. known format, the POSIX standard only provides a set of C library
  8374. routines (`<grp.h>' and `getgrent') for accessing the information.
  8375. Even though this file may exist, it likely does not have complete
  8376. information.  Therefore, as with the user database, it is necessary to
  8377. have a small C program that generates the group database as its output.
  8378.    Here is `grcat', a C program that "cats" the group database.
  8379.      /*
  8380.       * grcat.c
  8381.       *
  8382.       * Generate a printable version of the group database
  8383.       *
  8384.       * Arnold Robbins, arnold@gnu.ai.mit.edu
  8385.       * May 1993
  8386.       * Public Domain
  8387.       */
  8388.      
  8389.      #include <stdio.h>
  8390.      #include <grp.h>
  8391.      
  8392.      int
  8393.      main(argc, argv)
  8394.      int argc;
  8395.      char **argv;
  8396.      {
  8397.          struct group *g;
  8398.          int i;
  8399.      
  8400.          while ((g = getgrent()) != NULL) {
  8401.              printf("%s:%s:%d:", g->gr_name, g->gr_passwd,
  8402.                                                  g->gr_gid);
  8403.              for (i = 0; g->gr_mem[i] != NULL; i++) {
  8404.                  printf("%s", g->gr_mem[i]);
  8405.                  if (g->gr_mem[i+1] != NULL)
  8406.                      putchar(',');
  8407.              }
  8408.              putchar('\n');
  8409.          }
  8410.          endgrent();
  8411.          exit(0);
  8412.      }
  8413.    Each line in the group database represent one group.  The fields are
  8414. separated with colons, and represent the following information.
  8415. Group Name
  8416.      The name of the group.
  8417. Group Password
  8418.      The encrypted group password. In practice, this field is never
  8419.      used. It is usually empty, or set to `*'.
  8420. Group ID Number
  8421.      The numeric group-id number. This number should be unique within
  8422.      the file.
  8423. Group Member List
  8424.      A comma-separated list of user names.  These users are members of
  8425.      the group.  Most Unix systems allow users to be members of several
  8426.      groups simultaneously.  If your system does, then reading
  8427.      `/dev/user' will return those group-id numbers in `$5' through
  8428.      `$NF'.  (Note that `/dev/user' is a `gawk' extension; *note
  8429.      Special File Names in `gawk': Special Files..)
  8430.    Here is what running `grcat' might produce:
  8431.      $ grcat
  8432.      -| wheel:*:0:arnold
  8433.      -| nogroup:*:65534:
  8434.      -| daemon:*:1:
  8435.      -| kmem:*:2:
  8436.      -| staff:*:10:arnold,miriam,andy
  8437.      -| other:*:20:
  8438.      ...
  8439.    Here are the functions for obtaining information from the group
  8440. database.  There are several, modeled after the C library functions of
  8441. the same names.
  8442.      # group.awk --- functions for dealing with the group file
  8443.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  8444.      # May 1993
  8445.      
  8446.      BEGIN    \
  8447.      {
  8448.          # Change to suit your system
  8449.          _gr_awklib = "/usr/local/libexec/awk/"
  8450.      }
  8451.      
  8452.      function _gr_init(    oldfs, oldrs, olddol0, grcat, n, a, i)
  8453.      {
  8454.          if (_gr_inited)
  8455.              return
  8456.      
  8457.          oldfs = FS
  8458.          oldrs = RS
  8459.          olddol0 = $0
  8460.          FS = ":"
  8461.          RS = "\n"
  8462.      
  8463.          grcat = _gr_awklib "grcat"
  8464.          while ((grcat | getline) > 0) {
  8465.              if ($1 in _gr_byname)
  8466.                  _gr_byname[$1] = _gr_byname[$1] "," $4
  8467.              else
  8468.                  _gr_byname[$1] = $0
  8469.              if ($3 in _gr_bygid)
  8470.                  _gr_bygid[$3] = _gr_bygid[$3] "," $4
  8471.              else
  8472.                  _gr_bygid[$3] = $0
  8473.      
  8474.              n = split($4, a, "[ \t]*,[ \t]*")
  8475.              for (i = 1; i <= n; i++)
  8476.                  if (a[i] in _gr_groupsbyuser)
  8477.                      _gr_groupsbyuser[a[i]] = \
  8478.                          _gr_groupsbyuser[a[i]] " " $1
  8479.                  else
  8480.                      _gr_groupsbyuser[a[i]] = $1
  8481.      
  8482.              _gr_bycount[++_gr_count] = $0
  8483.          }
  8484.          close(grcat)
  8485.          _gr_count = 0
  8486.          _gr_inited++
  8487.          FS = oldfs
  8488.          RS = oldrs
  8489.          $0 = olddol0
  8490.      }
  8491.    The `BEGIN' rule sets a private variable to the directory where
  8492. `grcat' is stored.  Since it is used to help out an `awk' library
  8493. routine, we have chosen to put it in `/usr/local/libexec/awk'.  You
  8494. might want it to be in a different directory on your system.
  8495.    These routines follow the same general outline as the user database
  8496. routines (*note Reading the User Database: Passwd Functions.).  The
  8497. `_gr_inited' variable is used to ensure that the database is scanned no
  8498. more than once.  The `_gr_init' function first saves `FS', `RS', and
  8499. `$0', and then sets `FS' and `RS' to the correct values for scanning
  8500. the group information.
  8501.    The group information is stored is several associative arrays.  The
  8502. arrays are indexed by group name (`_gr_byname'), by group-id number
  8503. (`_gr_bygid'), and by position in the database (`_gr_bycount').  There
  8504. is an additional array indexed by user name (`_gr_groupsbyuser'), that
  8505. is a space separated list of groups that each user belongs to.
  8506.    Unlike the user database, it is possible to have multiple records in
  8507. the database for the same group.  This is common when a group has a
  8508. large number of members.  Such a pair of entries might look like:
  8509.      tvpeople:*:101:johny,jay,arsenio
  8510.      tvpeople:*:101:david,conan,tom,joan
  8511.    For this reason, `_gr_init' looks to see if a group name or group-id
  8512. number has already been seen.  If it has, then the user names are
  8513. simply concatenated onto the previous list of users.  (There is
  8514. actually a subtle problem with the code presented above.  Suppose that
  8515. the first time there were no names. This code adds the names with a
  8516. leading comma. It also doesn't check that there is a `$4'.)
  8517.    Finally, `_gr_init' closes the pipeline to `grcat', restores `FS',
  8518. `RS', and `$0', initializes `_gr_count' to zero (it is used later), and
  8519. makes `_gr_inited' non-zero.
  8520.      function getgrnam(group)
  8521.      {
  8522.          _gr_init()
  8523.          if (group in _gr_byname)
  8524.              return _gr_byname[group]
  8525.          return ""
  8526.      }
  8527.    The `getgrnam' function takes a group name as its argument, and if
  8528. that group exists, it is returned. Otherwise, `getgrnam' returns the
  8529. null string.
  8530.      function getgrgid(gid)
  8531.      {
  8532.          _gr_init()
  8533.          if (gid in _gr_bygid)
  8534.              return _gr_bygid[gid]
  8535.          return ""
  8536.      }
  8537.    The `getgrgid' function is similar, it takes a numeric group-id, and
  8538. looks up the information associated with that group-id.
  8539.      function getgruser(user)
  8540.      {
  8541.          _gr_init()
  8542.          if (user in _gr_groupsbyuser)
  8543.              return _gr_groupsbyuser[user]
  8544.          return ""
  8545.      }
  8546.    The `getgruser' function does not have a C counterpart. It takes a
  8547. user name, and returns the list of groups that have the user as a
  8548. member.
  8549.      function getgrent()
  8550.      {
  8551.          _gr_init()
  8552.          if (++gr_count in _gr_bycount)
  8553.              return _gr_bycount[_gr_count]
  8554.          return ""
  8555.      }
  8556.    The `getgrent' function steps through the database one entry at a
  8557. time.  It uses `_gr_count' to track its position in the list.
  8558.      function endgrent()
  8559.      {
  8560.          _gr_count = 0
  8561.      }
  8562.    `endgrent' resets `_gr_count' to zero so that `getgrent' can start
  8563. over again.
  8564.    As with the user database routines, each function calls `_gr_init' to
  8565. initialize the arrays.  Doing so only incurs the extra overhead of
  8566. running `grcat' if these functions are used (as opposed to moving the
  8567. body of `_gr_init' into a `BEGIN' rule).
  8568.    Most of the work is in scanning the database and building the various
  8569. associative arrays.  The functions that the user calls are themselves
  8570. very simple, relying on `awk''s associative arrays to do work.
  8571.    The `id' program in *Note Printing Out User Information: Id Program,
  8572. uses these functions.
  8573. File: gawk.info,  Node: Library Names,  Prev: Group Functions,  Up: Library Functions
  8574. Naming Library Function Global Variables
  8575. ========================================
  8576.    Due to the way the `awk' language evolved, variables are either
  8577. "global" (usable by the entire program), or "local" (usable just by a
  8578. specific function).  There is no intermediate state analogous to
  8579. `static' variables in C.
  8580.    Library functions often need to have global variables that they can
  8581. use to preserve state information between calls to the function. For
  8582. example, `getopt''s variable `_opti' (*note Processing Command Line
  8583. Options: Getopt Function.), and the `_tm_months' array used by `mktime'
  8584. (*note Turning Dates Into Timestamps: Mktime Function.).  Such
  8585. variables are called "private", since the only functions that need to
  8586. use them are the ones in the library.
  8587.    When writing a library function, you should try to choose names for
  8588. your private variables so that they will not conflict with any
  8589. variables used by either another library function or a user's main
  8590. program.  For example, a name like `i' or `j' is not a good choice,
  8591. since user programs often use variable names like these for their own
  8592. purposes.
  8593.    The example programs shown in this chapter all start the names of
  8594. their private variables with an underscore (`_').  Users generally
  8595. don't use leading underscores in their variable names, so this
  8596. convention immediately decreases the chances that the variable name
  8597. will be accidentally shared with the user's program.
  8598.    In addition, several of the library functions use a prefix that helps
  8599. indicate what function or set of functions uses the variables. For
  8600. example, `_tm_months' in `mktime' (*note Turning Dates Into Timestamps:
  8601. Mktime Function.), and `_pw_byname' in the user data base routines
  8602. (*note Reading the User Database: Passwd Functions.).  This convention
  8603. is recommended, since it even further decreases the chance of
  8604. inadvertent conflict among variable names.  Note that this convention
  8605. can be used equally well both for variable names and for private
  8606. function names too.
  8607.    While I could have re-written all the library routines to use this
  8608. convention, I did not do so, in order to show how my own `awk'
  8609. programming style has evolved, and to provide some basis for this
  8610. discussion.
  8611.    As a final note on variable naming, if a function makes global
  8612. variables available for use by a main program, it is a good convention
  8613. to start that variable's name with a capital letter.  For example,
  8614. `getopt''s `Opterr' and `Optind' variables (*note Processing Command
  8615. Line Options: Getopt Function.).  The leading capital letter indicates
  8616. that it is global, while the fact that the variable name is not all
  8617. capital letters indicates that the variable is not one of `awk''s
  8618. built-in variables, like `FS'.
  8619.    It is also important that *all* variables in library functions that
  8620. do not need to save state are in fact declared local.  If this is not
  8621. done, the variable could accidentally be used in the user's program,
  8622. leading to bugs that are very difficult to track down.
  8623.      function lib_func(x, y,    l1, l2)
  8624.      {
  8625.          ...
  8626.          USE VARIABLE some_var  # some_var could be local
  8627.          ...                   # but is not by oversight
  8628.      }
  8629.    A different convention, common in the Tcl community, is to use a
  8630. single associative array to hold the values needed by the library
  8631. function(s), or "package."  This significantly decreases the number of
  8632. actual global names in use.  For example, the functions described in
  8633. *Note Reading the User Database: Passwd Functions, might have used
  8634. `PW_data["inited"]', `PW_data["total"]', `PW_data["count"]' and
  8635. `PW_data["awklib"]', instead of `_pw_inited', `_pw_awklib', `_pw_total',
  8636. and `_pw_count'.
  8637.    The conventions presented in this section are exactly that,
  8638. conventions. You are not required to write your programs this way, we
  8639. merely recommend that you do so.
  8640. File: gawk.info,  Node: Sample Programs,  Next: Language History,  Prev: Library Functions,  Up: Top
  8641. Practical `awk' Programs
  8642. ************************
  8643.    This chapter presents a potpourri of `awk' programs for your reading
  8644. enjoyment.
  8645.    Many of these programs use the library functions presented in *Note
  8646. A Library of `awk' Functions: Library Functions.
  8647. * Menu:
  8648. * Clones::                    Clones of common utilities.
  8649. * Miscellaneous Programs::    Some interesting `awk' programs.
  8650. File: gawk.info,  Node: Clones,  Next: Miscellaneous Programs,  Prev: Sample Programs,  Up: Sample Programs
  8651. Re-inventing Wheels for Fun and Profit
  8652. ======================================
  8653.    This section presents a number of POSIX utilities that are
  8654. implemented in `awk'.  Re-inventing these programs in `awk' is often
  8655. enjoyable, since the algorithms can be very clearly expressed, and
  8656. usually the code is very concise and simple.  This is true because
  8657. `awk' does so much for you.
  8658.    It should be noted that these programs are not necessarily intended
  8659. to replace the installed versions on your system.  Instead, their
  8660. purpose is to illustrate `awk' language programming for "real world"
  8661. tasks.
  8662.    The programs are presented in alphabetical order.
  8663. * Menu:
  8664. * Cut Program::             The `cut' utility.
  8665. * Egrep Program::           The `egrep' utility.
  8666. * Id Program::              The `id' utility.
  8667. * Split Program::           The `split' utility.
  8668. * Tee Program::             The `tee' utility.
  8669. * Uniq Program::            The `uniq' utility.
  8670. * Wc Program::              The `wc' utility.
  8671. File: gawk.info,  Node: Cut Program,  Next: Egrep Program,  Prev: Clones,  Up: Clones
  8672. Cutting Out Fields and Columns
  8673. ------------------------------
  8674.    The `cut' utility selects, or "cuts," either characters or fields
  8675. from its standard input and sends them to its standard output.  `cut'
  8676. can cut out either a list of characters, or a list of fields.  By
  8677. default, fields are separated by tabs, but you may supply a command
  8678. line option to change the field "delimiter", i.e. the field separator
  8679. character. `cut''s definition of fields is less general than `awk''s.
  8680.    A common use of `cut' might be to pull out just the login name of
  8681. logged-on users from the output of `who'.  For example, the following
  8682. pipeline generates a sorted, unique list of the logged on users:
  8683.      who | cut -c1-8 | sort | uniq
  8684.    The options for `cut' are:
  8685. `-c LIST'
  8686.      Use LIST as the list of characters to cut out.  Items within the
  8687.      list may be separated by commas, and ranges of characters can be
  8688.      separated with dashes.  The list `1-8,15,22-35' specifies
  8689.      characters one through eight, 15, and 22 through 35.
  8690. `-f LIST'
  8691.      Use LIST as the list of fields to cut out.
  8692. `-d DELIM'
  8693.      Use DELIM as the field separator character instead of the tab
  8694.      character.
  8695.      Suppress printing of lines that do not contain the field delimiter.
  8696.    The `awk' implementation of `cut' uses the `getopt' library function
  8697. (*note Processing Command Line Options: Getopt Function.), and the
  8698. `join' library function (*note Merging an Array Into a String: Join
  8699. Function.).
  8700.    The program begins with a comment describing the options and a
  8701. `usage' function which prints out a usage message and exits.  `usage'
  8702. is called if invalid arguments are supplied.
  8703.      # cut.awk --- implement cut in awk
  8704.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  8705.      # May 1993
  8706.      
  8707.      # Options:
  8708.      #    -f list        Cut fields
  8709.      #    -d c           Field delimiter character
  8710.      #    -c list        Cut characters
  8711.      #
  8712.      #    -s        Suppress lines without the delimiter character
  8713.      
  8714.      function usage(    e1, e2)
  8715.      {
  8716.          e1 = "usage: cut [-f list] [-d c] [-s] [files...]"
  8717.          e2 = "usage: cut [-c list] [files...]"
  8718.          print e1 > "/dev/stderr"
  8719.          print e2 > "/dev/stderr"
  8720.          exit 1
  8721.      }
  8722. The variables `e1' and `e2' are used so that the function fits nicely
  8723. on the screen.
  8724.    Next comes a `BEGIN' rule that parses the command line options.  It
  8725. sets `FS' to a single tab character, since that is `cut''s default
  8726. field separator.  The output field separator is also set to be the same
  8727. as the input field separator.  Then `getopt' is used to step through
  8728. the command line options.  One or the other of the variables
  8729. `by_fields' or `by_chars' is set to true, to indicate that processing
  8730. should be done by fields or by characters respectively.  When cutting
  8731. by characters, the output field separator is set to the null string.
  8732.      BEGIN    \
  8733.      {
  8734.          FS = "\t"    # default
  8735.          OFS = FS
  8736.          while ((c = getopt(ARGC, ARGV, "sf:c:d:")) != -1) {
  8737.              if (c == "f") {
  8738.                  by_fields = 1
  8739.                  fieldlist = Optarg
  8740.              } else if (c == "c") {
  8741.                  by_chars = 1
  8742.                  fieldlist = Optarg
  8743.                  OFS = ""
  8744.              } else if (c == "d") {
  8745.                  if (length(Optarg) > 1) {
  8746.                      printf("Using first character of %s" \
  8747.                      " for delimiter\n", Optarg) > "/dev/stderr"
  8748.                      Optarg = substr(Optarg, 1, 1)
  8749.                  }
  8750.                  FS = Optarg
  8751.                  OFS = FS
  8752.                  if (FS == " ")    # defeat awk semantics
  8753.                      FS = "[ ]"
  8754.              } else if (c == "s")
  8755.                  suppress++
  8756.              else
  8757.                  usage()
  8758.          }
  8759.      
  8760.          for (i = 1; i < Optind; i++)
  8761.              ARGV[i] = ""
  8762.    Special care is taken when the field delimiter is a space. Using
  8763. `" "' (a single space) for the value of `FS' is incorrect--`awk' would
  8764. separate fields with runs of spaces, tabs and/or newlines, and we want
  8765. them to be separated with individual spaces.  Also, note that after
  8766. `getopt' is through, we have to clear out all the elements of `ARGV'
  8767. from one to `Optind', so that `awk' will not try to process the command
  8768. line options as file names.
  8769.    After dealing with the command line options, the program verifies
  8770. that the options make sense.  Only one or the other of `-c' and `-f'
  8771. should be used, and both require a field list.  Then either
  8772. `set_fieldlist' or `set_charlist' is called to pull apart the list of
  8773. fields or characters.
  8774.          if (by_fields && by_chars)
  8775.              usage()
  8776.      
  8777.          if (by_fields == 0 && by_chars == 0)
  8778.              by_fields = 1    # default
  8779.      
  8780.          if (fieldlist == "") {
  8781.              print "cut: needs list for -c or -f" > "/dev/stderr"
  8782.              exit 1
  8783.          }
  8784.      
  8785.          if (by_fields)
  8786.              set_fieldlist()
  8787.          else
  8788.              set_charlist()
  8789.      }
  8790.    Here is `set_fieldlist'.  It first splits the field list apart at
  8791. the commas, into an array.  Then, for each element of the array, it
  8792. looks to see if it is actually a range, and if so splits it apart. The
  8793. range is verified to make sure the first number is smaller than the
  8794. second.  Each number in the list is added to the `flist' array, which
  8795. simply lists the fields that will be printed.  Normal field splitting
  8796. is used.  The program lets `awk' handle the job of doing the field
  8797. splitting.
  8798.      function set_fieldlist(        n, m, i, j, k, f, g)
  8799.      {
  8800.          n = split(fieldlist, f, ",")
  8801.          j = 1    # index in flist
  8802.          for (i = 1; i <= n; i++) {
  8803.              if (index(f[i], "-") != 0) { # a range
  8804.                  m = split(f[i], g, "-")
  8805.                  if (m != 2 || g[1] >= g[2]) {
  8806.                      printf("bad field list: %s\n",
  8807.                                        f[i]) > "/dev/stderr"
  8808.                      exit 1
  8809.                  }
  8810.                  for (k = g[1]; k <= g[2]; k++)
  8811.                      flist[j++] = k
  8812.              } else
  8813.                  flist[j++] = f[i]
  8814.          }
  8815.          nfields = j - 1
  8816.      }
  8817.    The `set_charlist' function is more complicated than `set_fieldlist'.
  8818. The idea here is to use `gawk''s `FIELDWIDTHS' variable (*note Reading
  8819. Fixed-width Data: Constant Size.), which describes constant width
  8820. input.  When using a character list, that is exactly what we have.
  8821.    Setting up `FIELDWIDTHS' is more complicated than simply listing the
  8822. fields that need to be printed.  We have to keep track of the fields to
  8823. be printed, and also the intervening characters that have to be skipped.
  8824. For example, suppose you wanted characters one through eight, 15, and
  8825. 22 through 35.  You would use `-c 1-8,15,22-35'.  The necessary value
  8826. for `FIELDWIDTHS' would be `"8 6 1 6 14"'.  This gives us five fields,
  8827. and what should be printed are `$1', `$3', and `$5'.  The intermediate
  8828. fields are "filler," stuff in between the desired data.
  8829.    `flist' lists the fields to be printed, and `t' tracks the complete
  8830. field list, including filler fields.
  8831.      function set_charlist(    field, i, j, f, g, t,
  8832.                                filler, last, len)
  8833.      {
  8834.          field = 1   # count total fields
  8835.          n = split(fieldlist, f, ",")
  8836.          j = 1       # index in flist
  8837.          for (i = 1; i <= n; i++) {
  8838.              if (index(f[i], "-") != 0) { # range
  8839.                  m = split(f[i], g, "-")
  8840.                  if (m != 2 || g[1] >= g[2]) {
  8841.                      printf("bad character list: %s\n",
  8842.                                     f[i]) > "/dev/stderr"
  8843.                      exit 1
  8844.                  }
  8845.                  len = g[2] - g[1] + 1
  8846.                  if (g[1] > 1)  # compute length of filler
  8847.                      filler = g[1] - last - 1
  8848.                  else
  8849.                      filler = 0
  8850.                  if (filler)
  8851.                      t[field++] = filler
  8852.                  t[field++] = len  # length of field
  8853.                  last = g[2]
  8854.                  flist[j++] = field - 1
  8855.              } else {
  8856.                  if (f[i] > 1)
  8857.                      filler = f[i] - last - 1
  8858.                  else
  8859.                      filler = 0
  8860.                  if (filler)
  8861.                      t[field++] = filler
  8862.                  t[field++] = 1
  8863.                  last = f[i]
  8864.                  flist[j++] = field - 1
  8865.              }
  8866.          }
  8867.          FIELDWIDTHS = join(t, 1, field - 1)
  8868.          nfields = j - 1
  8869.      }
  8870.    Here is the rule that actually processes the data.  If the `-s'
  8871. option was given, then `suppress' will be true.  The first `if'
  8872. statement makes sure that the input record does have the field
  8873. separator.  If `cut' is processing fields, `suppress' is true, and the
  8874. field separator character is not in the record, then the record is
  8875. skipped.
  8876.    If the record is valid, then at this point, `gawk' has split the data
  8877. into fields, either using the character in `FS' or using fixed-length
  8878. fields and `FIELDWIDTHS'.  The loop goes through the list of fields
  8879. that should be printed.  If the corresponding field has data in it, it
  8880. is printed.  If the next field also has data, then the separator
  8881. character is written out in between the fields.
  8882.      {
  8883.          if (by_fields && suppress && $0 !~ FS)
  8884.              next
  8885.      
  8886.          for (i = 1; i <= nfields; i++) {
  8887.              if ($flist[i] != "") {
  8888.                  printf "%s", $flist[i]
  8889.                  if (i < nfields && $flist[i+1] != "")
  8890.                      printf "%s", OFS
  8891.              }
  8892.          }
  8893.          print ""
  8894.      }
  8895.    This version of `cut' relies on `gawk''s `FIELDWIDTHS' variable to
  8896. do the character-based cutting.  While it would be possible in other
  8897. `awk' implementations to use `substr' (*note Built-in Functions for
  8898. String Manipulation: String Functions.), it would also be extremely
  8899. painful to do so.  The `FIELDWIDTHS' variable supplies an elegant
  8900. solution to the problem of picking the input line apart by characters.
  8901. File: gawk.info,  Node: Egrep Program,  Next: Id Program,  Prev: Cut Program,  Up: Clones
  8902. Searching for Regular Expressions in Files
  8903. ------------------------------------------
  8904.    The `egrep' utility searches files for patterns.  It uses regular
  8905. expressions that are almost identical to those available in `awk'
  8906. (*note Regular Expression Constants: Regexp Constants.).  It is used
  8907. this way:
  8908.      egrep [ OPTIONS ] 'PATTERN' FILES ...
  8909.    The PATTERN is a regexp.  In typical usage, the regexp is quoted to
  8910. prevent the shell from expanding any of the special characters as file
  8911. name wildcards.  Normally, `egrep' prints the lines that matched.  If
  8912. multiple file names are provided on the command line, each output line
  8913. is preceded by the name of the file and a colon.
  8914.    The options are:
  8915.      Print out a count of the lines that matched the pattern, instead
  8916.      of the lines themselves.
  8917.      Be silent.  No output is produced, and the exit value indicates
  8918.      whether or not the pattern was matched.
  8919.      Invert the sense of the test. `egrep' prints the lines that do
  8920.      *not* match the pattern, and exits successfully if the pattern was
  8921.      not matched.
  8922.      Ignore case distinctions in both the pattern and the input data.
  8923.      Only print the names of the files that matched, not the lines that
  8924.      matched.
  8925. `-e PATTERN'
  8926.      Use PATTERN as the regexp to match.  The purpose of the `-e'
  8927.      option is to allow patterns that start with a `-'.
  8928.    This version uses the `getopt' library function (*note Processing
  8929. Command Line Options: Getopt Function.), and the file transition
  8930. library program (*note Noting Data File Boundaries: Filetrans
  8931. Function.).
  8932.    The program begins with a descriptive comment, and then a `BEGIN'
  8933. rule that processes the command line arguments with `getopt'.  The `-i'
  8934. (ignore case) option is particularly easy with `gawk'; we just use the
  8935. `IGNORECASE' built in variable (*note Built-in Variables::.).
  8936.      # egrep.awk --- simulate egrep in awk
  8937.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  8938.      # May 1993
  8939.      
  8940.      # Options:
  8941.      #    -c    count of lines
  8942.      #    -s    silent - use exit value
  8943.      #    -v    invert test, success if no match
  8944.      #    -i    ignore case
  8945.      #    -l    print filenames only
  8946.      #    -e    argument is pattern
  8947.      
  8948.      BEGIN {
  8949.          while ((c = getopt(ARGC, ARGV, "ce:svil")) != -1) {
  8950.              if (c == "c")
  8951.                  count_only++
  8952.              else if (c == "s")
  8953.                  no_print++
  8954.              else if (c == "v")
  8955.                  invert++
  8956.              else if (c == "i")
  8957.                  IGNORECASE = 1
  8958.              else if (c == "l")
  8959.                  filenames_only++
  8960.              else if (c == "e")
  8961.                  pattern = Optarg
  8962.              else
  8963.                  usage()
  8964.          }
  8965.    Next comes the code that handles the `egrep' specific behavior. If no
  8966. pattern was supplied with `-e', the first non-option on the command
  8967. line is used.  The `awk' command line arguments up to `ARGV[Optind]'
  8968. are cleared, so that `awk' won't try to process them as files.  If no
  8969. files were specified, the standard input is used, and if multiple files
  8970. were specified, we make sure to note this so that the file names can
  8971. precede the matched lines in the output.
  8972.    The last two lines are commented out, since they are not needed in
  8973. `gawk'.  They should be uncommented if you have to use another version
  8974. of `awk'.
  8975.          if (pattern == "")
  8976.              pattern = ARGV[Optind++]
  8977.      
  8978.          for (i = 1; i < Optind; i++)
  8979.              ARGV[i] = ""
  8980.          if (Optind >= ARGC) {
  8981.              ARGV[1] = "-"
  8982.              ARGC = 2
  8983.          } else if (ARGC - Optind > 1)
  8984.              do_filenames++
  8985.      
  8986.      #    if (IGNORECASE)
  8987.      #        pattern = tolower(pattern)
  8988.      }
  8989.    The next set of lines should be uncommented if you are not using
  8990. `gawk'.  This rule translates all the characters in the input line into
  8991. lower-case if the `-i' option was specified.  The rule is commented out
  8992. since it is not necessary with `gawk'.
  8993.      #{
  8994.      #    if (IGNORECASE)
  8995.      #        $0 = tolower($0)
  8996.      #}
  8997.    The `beginfile' function is called by the rule in `ftrans.awk' when
  8998. each new file is processed.  In this case, it is very simple; all it
  8999. does is initialize a variable `fcount' to zero. `fcount' tracks how
  9000. many lines in the current file matched the pattern.
  9001.      function beginfile(junk)
  9002.      {
  9003.          fcount = 0
  9004.      }
  9005.    The `endfile' function is called after each file has been processed.
  9006. It is used only when the user wants a count of the number of lines that
  9007. matched.  `no_print' will be true only if the exit status is desired.
  9008. `count_only' will be true if line counts are desired.  `egrep' will
  9009. therefore only print line counts if printing and counting are enabled.
  9010. The output format must be adjusted depending upon the number of files
  9011. to be processed.  Finally, `fcount' is added to `total', so that we
  9012. know how many lines altogether matched the pattern.
  9013.      function endfile(file)
  9014.      {
  9015.          if (! no_print && count_only)
  9016.              if (do_filenames)
  9017.                  print file ":" fcount
  9018.              else
  9019.                  print fcount
  9020.      
  9021.          total += fcount
  9022.      }
  9023.    This rule does most of the work of matching lines. The variable
  9024. `matches' will be true if the line matched the pattern. If the user
  9025. wants lines that did not match, the sense of the `matches' is inverted
  9026. using the `!' operator. `fcount' is incremented with the value of
  9027. `matches', which will be either one or zero, depending upon a
  9028. successful or unsuccessful match.  If the line did not match, the
  9029. `next' statement just moves on to the next record.
  9030.    There are several optimizations for performance in the following few
  9031. lines of code. If the user only wants exit status (`no_print' is true),
  9032. and we don't have to count lines, then it is enough to know that one
  9033. line in this file matched, and we can skip on to the next file with
  9034. `nextfile'.  Along similar lines, if we are only printing file names,
  9035. and we don't need to count lines, we can print the file name, and then
  9036. skip to the next file with `nextfile'.
  9037.    Finally, each line is printed, with a leading filename and colon if
  9038. necessary.
  9039.      {
  9040.          matches = ($0 ~ pattern)
  9041.          if (invert)
  9042.              matches = ! matches
  9043.      
  9044.          fcount += matches    # 1 or 0
  9045.      
  9046.          if (! matches)
  9047.              next
  9048.      
  9049.          if (no_print && ! count_only)
  9050.              nextfile
  9051.      
  9052.          if (filenames_only && ! count_only) {
  9053.              print FILENAME
  9054.              nextfile
  9055.          }
  9056.      
  9057.          if (do_filenames && ! count_only)
  9058.              print FILENAME ":" $0
  9059.          else if (! count_only)
  9060.              print
  9061.      }
  9062.    The `END' rule takes care of producing the correct exit status. If
  9063. there were no matches, the exit status is one, otherwise it is zero.
  9064.      END    \
  9065.      {
  9066.          if (total == 0)
  9067.              exit 1
  9068.          exit 0
  9069.      }
  9070.    The `usage' function prints a usage message in case of invalid
  9071. options and then exits.
  9072.      function usage(    e)
  9073.      {
  9074.          e = "Usage: egrep [-csvil] [-e pat] [files ...]"
  9075.          print e > "/dev/stderr"
  9076.          exit 1
  9077.      }
  9078.    The variable `e' is used so that the function fits nicely on the
  9079. printed page.
  9080.    Just a note on programming style. You may have noticed that the `END'
  9081. rule uses backslash continuation, with the open brace on a line by
  9082. itself.  This is so that it more closely resembles the way functions
  9083. are written.  Many of the examples use this style. You can decide for
  9084. yourself if you like writing your `BEGIN' and `END' rules this way, or
  9085. File: gawk.info,  Node: Id Program,  Next: Split Program,  Prev: Egrep Program,  Up: Clones
  9086. Printing Out User Information
  9087. -----------------------------
  9088.    The `id' utility lists a user's real and effective user-id numbers,
  9089. real and effective group-id numbers, and the user's group set, if any.
  9090. `id' will only print the effective user-id and group-id if they are
  9091. different from the real ones.  If possible, `id' will also supply the
  9092. corresponding user and group names.  The output might look like this:
  9093.      $ id
  9094.      -| uid=2076(arnold) gid=10(staff) groups=10(staff),4(tty)
  9095.    This information is exactly what is provided by `gawk''s `/dev/user'
  9096. special file (*note Special File Names in `gawk': Special Files.).
  9097. However, the `id' utility provides a more palatable output than just a
  9098. string of numbers.
  9099.    Here is a simple version of `id' written in `awk'.  It uses the user
  9100. database library functions (*note Reading the User Database: Passwd
  9101. Functions.), and the group database library functions (*note Reading
  9102. the Group Database: Group Functions.).
  9103.    The program is fairly straightforward.  All the work is done in the
  9104. `BEGIN' rule.  The user and group id numbers are obtained from
  9105. `/dev/user'.  If there is no support for `/dev/user', the program gives
  9106.    The code is repetitive.  The entry in the user database for the real
  9107. user-id number is split into parts at the `:'. The name is the first
  9108. field.  Similar code is used for the effective user-id number, and the
  9109. group numbers.
  9110.      # id.awk --- implement id in awk
  9111.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9112.      # May 1993
  9113.      
  9114.      # output is:
  9115.      # uid=12(foo) euid=34(bar) gid=3(baz) \
  9116.      #             egid=5(blat) groups=9(nine),2(two),1(one)
  9117.      
  9118.      BEGIN    \
  9119.      {
  9120.          if ((getline < "/dev/user") < 0) {
  9121.              err = "id: no /dev/user support - cannot run"
  9122.              print err > "/dev/stderr"
  9123.              exit 1
  9124.          }
  9125.          close("/dev/user")
  9126.      
  9127.          uid = $1
  9128.          euid = $2
  9129.          gid = $3
  9130.          egid = $4
  9131.      
  9132.          printf("uid=%d", uid)
  9133.          pw = getpwuid(uid)
  9134.          if (pw != "") {
  9135.              split(pw, a, ":")
  9136.              printf("(%s)", a[1])
  9137.          }
  9138.      
  9139.          if (euid != uid) {
  9140.              printf(" euid=%d", euid)
  9141.              pw = getpwuid(euid)
  9142.              if (pw != "") {
  9143.                  split(pw, a, ":")
  9144.                  printf("(%s)", a[1])
  9145.              }
  9146.          }
  9147.      
  9148.          printf(" gid=%d", gid)
  9149.          pw = getgrgid(gid)
  9150.          if (pw != "") {
  9151.              split(pw, a, ":")
  9152.              printf("(%s)", a[1])
  9153.          }
  9154.      
  9155.          if (egid != gid) {
  9156.              printf(" egid=%d", egid)
  9157.              pw = getgrgid(egid)
  9158.              if (pw != "") {
  9159.                  split(pw, a, ":")
  9160.                  printf("(%s)", a[1])
  9161.              }
  9162.          }
  9163.      
  9164.          if (NF > 4) {
  9165.              printf(" groups=");
  9166.              for (i = 5; i <= NF; i++) {
  9167.                  printf("%d", $i)
  9168.                  pw = getgrgid($i)
  9169.                  if (pw != "") {
  9170.                      split(pw, a, ":")
  9171.                      printf("(%s)", a[1])
  9172.                  }
  9173.                  if (i < NF)
  9174.                      printf(",")
  9175.              }
  9176.          }
  9177.          print ""
  9178.      }
  9179. File: gawk.info,  Node: Split Program,  Next: Tee Program,  Prev: Id Program,  Up: Clones
  9180. Splitting a Large File Into Pieces
  9181. ----------------------------------
  9182.    The `split' program splits large text files into smaller pieces. By
  9183. default, the output files are named `xaa', `xab', and so on. Each file
  9184. has 1000 lines in it, with the likely exception of the last file. To
  9185. change the number of lines in each file, you supply a number on the
  9186. command line preceded with a minus, e.g., `-500' for files with 500
  9187. lines in them instead of 1000.  To change the name of the output files
  9188. to something like `myfileaa', `myfileab', and so on, you supply an
  9189. additional argument that specifies the filename.
  9190.    Here is a version of `split' in `awk'. It uses the `ord' and `chr'
  9191. functions presented in *Note Translating Between Characters and
  9192. Numbers: Ordinal Functions.
  9193.    The program first sets its defaults, and then tests to make sure
  9194. there are not too many arguments.  It then looks at each argument in
  9195. turn.  The first argument could be a minus followed by a number. If it
  9196. is, this happens to look like a negative number, so it is made
  9197. positive, and that is the count of lines.  The data file name is
  9198. skipped over, and the final argument is used as the prefix for the
  9199. output file names.
  9200.      # split.awk --- do split in awk
  9201.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9202.      # May 1993
  9203.      
  9204.      # usage: split [-num] [file] [outname]
  9205.      
  9206.      BEGIN {
  9207.          outfile = "x"    # default
  9208.          count = 1000
  9209.          if (ARGC > 4)
  9210.              usage()
  9211.      
  9212.          i = 1
  9213.          if (ARGV[i] ~ /^-[0-9]+$/) {
  9214.              count = -ARGV[i]
  9215.              ARGV[i] = ""
  9216.              i++
  9217.          }
  9218.          # test argv in case reading from stdin instead of file
  9219.          if (i in ARGV)
  9220.              i++    # skip data file name
  9221.          if (i in ARGV) {
  9222.              outfile = ARGV[i]
  9223.              ARGV[i] = ""
  9224.          }
  9225.      
  9226.          s1 = s2 = "a"
  9227.          out = (outfile s1 s2)
  9228.      }
  9229.    The next rule does most of the work. `tcount' (temporary count)
  9230. tracks how many lines have been printed to the output file so far. If
  9231. it is greater than `count', it is time to close the current file and
  9232. start a new one.  `s1' and `s2' track the current suffixes for the file
  9233. name. If they are both `z', the file is just too big.  Otherwise, `s1'
  9234. moves to the next letter in the alphabet and `s2' starts over again at
  9235.      {
  9236.          if (++tcount > count) {
  9237.              close(out)
  9238.              if (s2 == "z") {
  9239.                  if (s1 == "z") {
  9240.                      printf("split: %s is too large to split\n", \
  9241.                             FILENAME) > "/dev/stderr"
  9242.                      exit 1
  9243.                  }
  9244.                  s1 = chr(ord(s1) + 1)
  9245.                  s2 = "a"
  9246.              } else
  9247.                  s2 = chr(ord(s2) + 1)
  9248.              out = (outfile s1 s2)
  9249.              tcount = 1
  9250.          }
  9251.          print > out
  9252.      }
  9253.    The `usage' function simply prints an error message and exits.
  9254.      function usage(   e)
  9255.      {
  9256.          e = "usage: split [-num] [file] [outname]"
  9257.          print e > "/dev/stderr"
  9258.          exit 1
  9259.      }
  9260. The variable `e' is used so that the function fits nicely on the screen.
  9261.    This program is a bit sloppy; it relies on `awk' to close the last
  9262. file for it automatically, instead of doing it in an `END' rule.
  9263. File: gawk.info,  Node: Tee Program,  Next: Uniq Program,  Prev: Split Program,  Up: Clones
  9264. Duplicating Output Into Multiple Files
  9265. --------------------------------------
  9266.    The `tee' program is known as a "pipe fitting."  `tee' copies its
  9267. standard input to its standard output, and also duplicates it to the
  9268. files named on the command line.  Its usage is:
  9269.      tee [-a] file ...
  9270.    The `-a' option tells `tee' to append to the named files, instead of
  9271. truncating them and starting over.
  9272.    The `BEGIN' rule first makes a copy of all the command line
  9273. arguments, into an array named `copy'.  `ARGV[0]' is not copied, since
  9274. it is not needed.  `tee' cannot use `ARGV' directly, since `awk' will
  9275. attempt to process each file named in `ARGV' as input data.
  9276.    If the first argument is `-a', then the flag variable `append' is
  9277. set to true, and both `ARGV[1]' and `copy[1]' are deleted. If `ARGC' is
  9278. less than two, then no file names were supplied, and `tee' prints a
  9279. usage message and exits.  Finally, `awk' is forced to read the standard
  9280. input by setting `ARGV[1]' to `"-"', and `ARGC' to two.
  9281.      # tee.awk --- tee in awk
  9282.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9283.      # May 1993
  9284.      # Revised December 1995
  9285.      
  9286.      BEGIN    \
  9287.      {
  9288.          for (i = 1; i < ARGC; i++)
  9289.              copy[i] = ARGV[i]
  9290.      
  9291.          if (ARGV[1] == "-a") {
  9292.              append = 1
  9293.              delete ARGV[1]
  9294.              delete copy[1]
  9295.              ARGC--
  9296.          }
  9297.          if (ARGC < 2) {
  9298.              print "usage: tee [-a] file ..." > "/dev/stderr"
  9299.              exit 1
  9300.          }
  9301.          ARGV[1] = "-"
  9302.          ARGC = 2
  9303.      }
  9304.    The single rule does all the work.  Since there is no pattern, it is
  9305. executed for each line of input.  The body of the rule simply prints the
  9306. line into each file on the command line, and then to the standard
  9307. output.
  9308.      {
  9309.          # moving the if outside the loop makes it run faster
  9310.          if (append)
  9311.              for (i in copy)
  9312.                  print >> copy[i]
  9313.          else
  9314.              for (i in copy)
  9315.                  print > copy[i]
  9316.          print
  9317.      }
  9318.    It would have been possible to code the loop this way:
  9319.      for (i in copy)
  9320.          if (append)
  9321.              print >> copy[i]
  9322.          else
  9323.              print > copy[i]
  9324. This is more concise, but it is also less efficient.  The `if' is
  9325. tested for each record and for each output file.  By duplicating the
  9326. loop body, the `if' is only tested once for each input record.  If
  9327. there are N input records and M input files, the first method only
  9328. executes N `if' statements, while the second would execute N`*'M `if'
  9329. statements.
  9330.    Finally, the `END' rule cleans up, by closing all the output files.
  9331.      END    \
  9332.      {
  9333.          for (i in copy)
  9334.              close(copy[i])
  9335.      }
  9336. File: gawk.info,  Node: Uniq Program,  Next: Wc Program,  Prev: Tee Program,  Up: Clones
  9337. Printing Non-duplicated Lines of Text
  9338. -------------------------------------
  9339.    The `uniq' utility reads sorted lines of data on its standard input,
  9340. and (by default) removes duplicate lines.  In other words, only unique
  9341. lines are printed, hence the name.  `uniq' has a number of options. The
  9342. usage is:
  9343.      uniq [-udc [-N]] [+N] [ INPUT FILE [ OUTPUT FILE ]]
  9344.    The option meanings are:
  9345.      Only print repeated lines.
  9346.      Only print non-repeated lines.
  9347.      Count lines. This option overrides `-d' and `-u'.  Both repeated
  9348.      and non-repeated lines are counted.
  9349.      Skip N fields before comparing lines.  The definition of fields is
  9350.      similar to `awk''s default: non-whitespace characters separated by
  9351.      runs of spaces and/or tabs.
  9352.      Skip N characters before comparing lines.  Any fields specified
  9353.      with `-N' are skipped first.
  9354. `INPUT FILE'
  9355.      Data is read from the input file named on the command line,
  9356.      instead of from the standard input.
  9357. `OUTPUT FILE'
  9358.      The generated output is sent to the named output file, instead of
  9359.      to the standard output.
  9360.    Normally `uniq' behaves as if both the `-d' and `-u' options had
  9361. been provided.
  9362.    Here is an `awk' implementation of `uniq'. It uses the `getopt'
  9363. library function (*note Processing Command Line Options: Getopt
  9364. Function.), and the `join' library function (*note Merging an Array
  9365. Into a String: Join Function.).
  9366.    The program begins with a `usage' function and then a brief outline
  9367. of the options and their meanings in a comment.
  9368.    The `BEGIN' rule deals with the command line arguments and options.
  9369. It uses a trick to get `getopt' to handle options of the form `-25',
  9370. treating such an option as the option letter `2' with an argument of
  9371. `5'. If indeed two or more digits were supplied (`Optarg' looks like a
  9372. number), `Optarg' is concatenated with the option digit, and then
  9373. result is added to zero to make it into a number.  If there is only one
  9374. digit in the option, then `Optarg' is not needed, and `Optind' must be
  9375. decremented so that `getopt' will process it next time.  This code is
  9376. admittedly a bit tricky.
  9377.    If no options were supplied, then the default is taken, to print both
  9378. repeated and non-repeated lines.  The output file, if provided, is
  9379. assigned to `outputfile'.  Earlier, `outputfile' was initialized to the
  9380. standard output, `/dev/stdout'.
  9381.      # uniq.awk --- do uniq in awk
  9382.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9383.      # May 1993
  9384.      
  9385.      function usage(    e)
  9386.      {
  9387.          e = "Usage: uniq [-udc [-n]] [+n] [ in [ out ]]"
  9388.          print e > "/dev/stderr"
  9389.          exit 1
  9390.      }
  9391.      
  9392.      # -c    count lines. overrides -d and -u
  9393.      # -d    only repeated lines
  9394.      # -u    only non-repeated lines
  9395.      # -n    skip n fields
  9396.      # +n    skip n characters, skip fields first
  9397.      
  9398.      BEGIN    \
  9399.      {
  9400.          count = 1
  9401.          outputfile = "/dev/stdout"
  9402.          opts = "udc0:1:2:3:4:5:6:7:8:9:"
  9403.          while ((c = getopt(ARGC, ARGV, opts)) != -1) {
  9404.              if (c == "u")
  9405.                  non_repeated_only++
  9406.              else if (c == "d")
  9407.                  repeated_only++
  9408.              else if (c == "c")
  9409.                  do_count++
  9410.              else if (index("0123456789", c) != 0) {
  9411.                  # getopt requires args to options
  9412.                  # this messes us up for things like -5
  9413.                  if (Optarg ~ /^[0-9]+$/)
  9414.                      fcount = (c Optarg) + 0
  9415.                  else {
  9416.                      fcount = c + 0
  9417.                      Optind--
  9418.                  }
  9419.              } else
  9420.                  usage()
  9421.          }
  9422.      
  9423.          if (ARGV[Optind] ~ /^\+[0-9]+$/) {
  9424.              charcount = substr(ARGV[Optind], 2) + 0
  9425.              Optind++
  9426.          }
  9427.      
  9428.          for (i = 1; i < Optind; i++)
  9429.              ARGV[i] = ""
  9430.      
  9431.          if (repeated_only == 0 && non_repeated_only == 0)
  9432.              repeated_only = non_repeated_only = 1
  9433.      
  9434.          if (ARGC - Optind == 2) {
  9435.              outputfile = ARGV[ARGC - 1]
  9436.              ARGV[ARGC - 1] = ""
  9437.          }
  9438.      }
  9439.    The following function, `are_equal', compares the current line,
  9440. `$0', to the previous line, `last'.  It handles skipping fields and
  9441. characters.
  9442.    If no field count and no character count were specified, `are_equal'
  9443. simply returns one or zero depending upon the result of a simple string
  9444. comparison of `last' and `$0'.  Otherwise, things get more complicated.
  9445.    If fields have to be skipped, each line is broken into an array using
  9446. `split' (*note Built-in Functions for String Manipulation: String
  9447. Functions.), and then the desired fields are joined back into a line
  9448. using `join'.  The joined lines are stored in `clast' and `cline'.  If
  9449. no fields are skipped, `clast' and `cline' are set to `last' and `$0'
  9450. respectively.
  9451.    Finally, if characters are skipped, `substr' is used to strip off the
  9452. leading `charcount' characters in `clast' and `cline'.  The two strings
  9453. are then compared, and `are_equal' returns the result.
  9454.      function are_equal(    n, m, clast, cline, alast, aline)
  9455.      {
  9456.          if (fcount == 0 && charcount == 0)
  9457.              return (last == $0)
  9458.      
  9459.          if (fcount > 0) {
  9460.              n = split(last, alast)
  9461.              m = split($0, aline)
  9462.              clast = join(alast, fcount+1, n)
  9463.              cline = join(aline, fcount+1, m)
  9464.          } else {
  9465.              clast = last
  9466.              cline = $0
  9467.          }
  9468.          if (charcount) {
  9469.              clast = substr(clast, charcount + 1)
  9470.              cline = substr(cline, charcount + 1)
  9471.          }
  9472.      
  9473.          return (clast == cline)
  9474.      }
  9475.    The following two rules are the body of the program.  The first one
  9476. is executed only for the very first line of data.  It sets `last' equal
  9477. to `$0', so that subsequent lines of text have something to be compared
  9478.    The second rule does the work. The variable `equal' will be one or
  9479. zero depending upon the results of `are_equal''s comparison. If `uniq'
  9480. is counting repeated lines, then the `count' variable is incremented if
  9481. the lines are equal. Otherwise the line is printed and `count' is
  9482. reset, since the two lines are not equal.
  9483.    If `uniq' is not counting, `count' is incremented if the lines are
  9484. equal. Otherwise, if `uniq' is counting repeated lines, and more than
  9485. one line has been seen, or if `uniq' is counting non-repeated lines,
  9486. and only one line has been seen, then the line is printed, and `count'
  9487. is reset.
  9488.    Finally, similar logic is used in the `END' rule to print the final
  9489. line of input data.
  9490.      NR == 1 {
  9491.          last = $0
  9492.          next
  9493.      }
  9494.      
  9495.      {
  9496.          equal = are_equal()
  9497.      
  9498.          if (do_count) {    # overrides -d and -u
  9499.              if (equal)
  9500.                  count++
  9501.              else {
  9502.                  printf("%4d %s\n", count, last) > outputfile
  9503.                  last = $0
  9504.                  count = 1    # reset
  9505.              }
  9506.              next
  9507.          }
  9508.      
  9509.          if (equal)
  9510.              count++
  9511.          else {
  9512.              if ((repeated_only && count > 1) ||
  9513.                  (non_repeated_only && count == 1))
  9514.                      print last > outputfile
  9515.              last = $0
  9516.              count = 1
  9517.          }
  9518.      }
  9519.      
  9520.      END {
  9521.          if (do_count)
  9522.              printf("%4d %s\n", count, last) > outputfile
  9523.          else if ((repeated_only && count > 1) ||
  9524.                  (non_repeated_only && count == 1))
  9525.              print last > outputfile
  9526.      }
  9527. File: gawk.info,  Node: Wc Program,  Prev: Uniq Program,  Up: Clones
  9528. Counting Things
  9529. ---------------
  9530.    The `wc' (word count) utility counts lines, words, and characters in
  9531. one or more input files. Its usage is:
  9532.      wc [-lwc] [ FILES ... ]
  9533.    If no files are specified on the command line, `wc' reads its
  9534. standard input. If there are multiple files, it will also print total
  9535. counts for all the files.  The options and their meanings are:
  9536.      Only count lines.
  9537.      Only count words.  A "word" is a contiguous sequence of
  9538.      non-whitespace characters, separated by spaces and/or tabs.
  9539.      Happily, this is the normal way `awk' separates fields in its
  9540.      input data.
  9541.      Only count characters.
  9542.    Implementing `wc' in `awk' is particularly elegant, since `awk' does
  9543. a lot of the work for us; it splits lines into words (i.e.  fields) and
  9544. counts them, it counts lines (i.e. records) for us, and it can easily
  9545. tell us how long a line is.
  9546.    This version uses the `getopt' library function (*note Processing
  9547. Command Line Options: Getopt Function.), and the file transition
  9548. functions (*note Noting Data File Boundaries: Filetrans Function.).
  9549.    This version has one major difference from traditional versions of
  9550. `wc'.  Our version always prints the counts in the order lines, words,
  9551. and characters.  Traditional versions note the order of the `-l', `-w',
  9552. and `-c' options on the command line, and print the counts in that
  9553. order.
  9554.    The `BEGIN' rule does the argument processing.  The variable
  9555. `print_total' will be true if more than one file was named on the
  9556. command line.
  9557.      # wc.awk --- count lines, words, characters
  9558.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9559.      # May 1993
  9560.      
  9561.      # Options:
  9562.      #    -l    only count lines
  9563.      #    -w    only count words
  9564.      #    -c    only count characters
  9565.      #
  9566.      # Default is to count lines, words, characters
  9567.      
  9568.      BEGIN {
  9569.          # let getopt print a message about
  9570.          # invalid options. we ignore them
  9571.          while ((c = getopt(ARGC, ARGV, "lwc")) != -1) {
  9572.              if (c == "l")
  9573.                  do_lines = 1
  9574.              else if (c == "w")
  9575.                  do_words = 1
  9576.              else if (c == "c")
  9577.                  do_chars = 1
  9578.          }
  9579.          for (i = 1; i < Optind; i++)
  9580.              ARGV[i] = ""
  9581.      
  9582.          # if no options, do all
  9583.          if (! do_lines && ! do_words && ! do_chars)
  9584.              do_lines = do_words = do_chars = 1
  9585.      
  9586.          print_total = (ARGC - i > 2)
  9587.      }
  9588.    The `beginfile' function is simple; it just resets the counts of
  9589. lines, words, and characters to zero, and saves the current file name in
  9590. `fname'.
  9591.    The `endfile' function adds the current file's numbers to the running
  9592. totals of lines, words, and characters.  It then prints out those
  9593. numbers for the file that was just read. It relies on `beginfile' to
  9594. reset the numbers for the following data file.
  9595.      function beginfile(file)
  9596.      {
  9597.          chars = lines = words = 0
  9598.          fname = FILENAME
  9599.      }
  9600.      
  9601.      function endfile(file)
  9602.      {
  9603.          tchars += chars
  9604.          tlines += lines
  9605.          twords += words
  9606.          if (do_lines)
  9607.              printf "\t%d", lines
  9608.          if (do_words)
  9609.              printf "\t%d", words
  9610.          if (do_chars)
  9611.              printf "\t%d", chars
  9612.          printf "\t%s\n", fname
  9613.      }
  9614.    There is one rule that is executed for each line. It adds the length
  9615. of the record to `chars'.  It has to add one, since the newline
  9616. character separating records (the value of `RS') is not part of the
  9617. record itself.  `lines' is incremented for each line read, and `words'
  9618. is incremented by the value of `NF', the number of "words" on this
  9619. line.(1)
  9620.    Finally, the `END' rule simply prints the totals for all the files.
  9621.      # do per line
  9622.      {
  9623.          chars += length($0) + 1    # get newline
  9624.          lines++
  9625.          words += NF
  9626.      }
  9627.      
  9628.      END {
  9629.          if (print_total) {
  9630.              if (do_lines)
  9631.                  printf "\t%d", tlines
  9632.              if (do_words)
  9633.                  printf "\t%d", twords
  9634.              if (do_chars)
  9635.                  printf "\t%d", tchars
  9636.              print "\ttotal"
  9637.          }
  9638.      }
  9639.    ---------- Footnotes ----------
  9640.    (1)  Examine the code in *Note Noting Data File Boundaries:
  9641. Filetrans Function.  Why must `wc' use a separate `lines' variable,
  9642. instead of using the value of `FNR' in `endfile'?
  9643. File: gawk.info,  Node: Miscellaneous Programs,  Prev: Clones,  Up: Sample Programs
  9644. A Grab Bag of `awk' Programs
  9645. ============================
  9646.    This section is a large "grab bag" of miscellaneous programs.  We
  9647. hope you find them both interesting and enjoyable.
  9648. * Menu:
  9649. * Dupword Program::         Finding duplicated words in a document.
  9650. * Alarm Program::           An alarm clock.
  9651. * Translate Program::       A program similar to the `tr' utility.
  9652. * Labels Program::          Printing mailing labels.
  9653. * Word Sorting::            A program to produce a word usage count.
  9654. * History Sorting::         Eliminating duplicate entries from a history
  9655.                             file.
  9656. * Extract Program::         Pulling out programs from Texinfo source
  9657.                             files.
  9658. * Simple Sed::              A Simple Stream Editor.
  9659. * Igawk Program::           A wrapper for `awk' that includes files.
  9660. File: gawk.info,  Node: Dupword Program,  Next: Alarm Program,  Prev: Miscellaneous Programs,  Up: Miscellaneous Programs
  9661. Finding Duplicated Words in a Document
  9662. --------------------------------------
  9663.    A common error when writing large amounts of prose is to accidentally
  9664. duplicate words.  Often you will see this in text as something like "the
  9665. the program does the following ...."  When the text is on-line, often
  9666. the duplicated words occur at the end of one line and the beginning of
  9667. another, making them very difficult to spot.
  9668.    This program, `dupword.awk', scans through a file one line at a time,
  9669. and looks for adjacent occurrences of the same word.  It also saves the
  9670. last word on a line (in the variable `prev') for comparison with the
  9671. first word on the next line.
  9672.    The first two statements make sure that the line is all lower-case,
  9673. so that, for example, "The" and "the" compare equal to each other.  The
  9674. second statement removes all non-alphanumeric and non-whitespace
  9675. characters from the line, so that punctuation does not affect the
  9676. comparison either.  This sometimes leads to reports of duplicated words
  9677. that really are different, but this is unusual.
  9678.      # dupword --- find duplicate words in text
  9679.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9680.      # December 1991
  9681.      
  9682.      {
  9683.          $0 = tolower($0)
  9684.          gsub(/[^A-Za-z0-9 \t]/, "");
  9685.          if ($1 == prev)
  9686.              printf("%s:%d: duplicate %s\n",
  9687.                  FILENAME, FNR, $1)
  9688.          for (i = 2; i <= NF; i++)
  9689.              if ($i == $(i-1))
  9690.                  printf("%s:%d: duplicate %s\n",
  9691.                      FILENAME, FNR, $i)
  9692.          prev = $NF
  9693.      }
  9694. File: gawk.info,  Node: Alarm Program,  Next: Translate Program,  Prev: Dupword Program,  Up: Miscellaneous Programs
  9695. An Alarm Clock Program
  9696. ----------------------
  9697.    The following program is a simple "alarm clock" program.  You give
  9698. it a time of day, and an optional message.  At the given time, it
  9699. prints the message on the standard output. In addition, you can give it
  9700. the number of times to repeat the message, and also a delay between
  9701. repetitions.
  9702.    This program uses the `gettimeofday' function from *Note Managing
  9703. the Time of Day: Gettimeofday Function.
  9704.    All the work is done in the `BEGIN' rule.  The first part is argument
  9705. checking and setting of defaults; the delay, the count, and the message
  9706. to print.  If the user supplied a message, but it does not contain the
  9707. ASCII BEL character (known as the "alert" character, `\a'), then it is
  9708. added to the message.  (On many systems, printing the ASCII BEL
  9709. generates some sort of audible alert. Thus, when the alarm goes off,
  9710. the system calls attention to itself, in case the user is not looking
  9711. at their computer or terminal.)
  9712.      # alarm --- set an alarm
  9713.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9714.      # May 1993
  9715.      
  9716.      # usage: alarm time [ "message" [ count [ delay ] ] ]
  9717.      
  9718.      BEGIN    \
  9719.      {
  9720.          # Initial argument sanity checking
  9721.          usage1 = "usage: alarm time ['message' [count [delay]]]"
  9722.          usage2 = sprintf("\t(%s) time ::= hh:mm", ARGV[1])
  9723.      
  9724.          if (ARGC < 2) {
  9725.              print usage > "/dev/stderr"
  9726.              exit 1
  9727.          } else if (ARGC == 5) {
  9728.              delay = ARGV[4] + 0
  9729.              count = ARGV[3] + 0
  9730.              message = ARGV[2]
  9731.          } else if (ARGC == 4) {
  9732.              count = ARGV[3] + 0
  9733.              message = ARGV[2]
  9734.          } else if (ARGC == 3) {
  9735.              message = ARGV[2]
  9736.          } else if (ARGV[1] !~ /[0-9]?[0-9]:[0-9][0-9]/) {
  9737.              print usage1 > "/dev/stderr"
  9738.              print usage2 > "/dev/stderr"
  9739.              exit 1
  9740.          }
  9741.      
  9742.          # set defaults for once we reach the desired time
  9743.          if (delay == 0)
  9744.              delay = 180    # 3 minutes
  9745.          if (count == 0)
  9746.              count = 5
  9747.          if (message == "")
  9748.              message = sprintf("\aIt is now %s!\a", ARGV[1])
  9749.          else if (index(message, "\a") == 0)
  9750.              message = "\a" message "\a"
  9751.    The next section of code turns the alarm time into hours and minutes,
  9752. and converts it if necessary to a 24-hour clock.  Then it turns that
  9753. time into a count of the seconds since midnight.  Next it turns the
  9754. current time into a count of seconds since midnight.  The difference
  9755. between the two is how long to wait before setting off the alarm.
  9756.          # split up dest time
  9757.          split(ARGV[1], atime, ":")
  9758.          hour = atime[1] + 0    # force numeric
  9759.          minute = atime[2] + 0  # force numeric
  9760.      
  9761.          # get current broken down time
  9762.          gettimeofday(now)
  9763.      
  9764.          # if time given is 12-hour hours and it's after that
  9765.          # hour, e.g., `alarm 5:30' at 9 a.m. means 5:30 p.m.,
  9766.          # then add 12 to real hour
  9767.          if (hour < 12 && now["hour"] > hour)
  9768.              hour += 12
  9769.      
  9770.          # set target time in seconds since midnight
  9771.          target = (hour * 60 * 60) + (minute * 60)
  9772.      
  9773.          # get current time in seconds since midnight
  9774.          current = (now["hour"] * 60 * 60) + \
  9775.                     (now["minute"] * 60) + now["second"]
  9776.      
  9777.          # how long to sleep for
  9778.          naptime = target - current
  9779.          if (naptime <= 0) {
  9780.              print "time is in the past!" > "/dev/stderr"
  9781.              exit 1
  9782.          }
  9783.    Finally, the program uses the `system' function (*note Built-in
  9784. Functions for Input/Output: I/O Functions.) to call the `sleep'
  9785. utility.  The `sleep' utility simply pauses for the given number of
  9786. seconds.  If the exit status is not zero, the program assumes that
  9787. `sleep' was interrupted, and exits. If `sleep' exited with an OK status
  9788. (zero), then the program prints the message in a loop, again using
  9789. `sleep' to delay for however many seconds are necessary.
  9790.          # zzzzzz..... go away if interrupted
  9791.          if (system(sprintf("sleep %d", naptime)) != 0)
  9792.              exit 1
  9793.      
  9794.          # time to notify!
  9795.          command = sprintf("sleep %d", delay)
  9796.          for (i = 1; i <= count; i++) {
  9797.              print message
  9798.              # if sleep command interrupted, go away
  9799.              if (system(command) != 0)
  9800.                  break
  9801.          }
  9802.      
  9803.          exit 0
  9804.      }
  9805. File: gawk.info,  Node: Translate Program,  Next: Labels Program,  Prev: Alarm Program,  Up: Miscellaneous Programs
  9806. Transliterating Characters
  9807. --------------------------
  9808.    The system `tr' utility transliterates characters.  For example, it
  9809. is often used to map upper-case letters into lower-case, for further
  9810. processing.
  9811.      GENERATE DATA | tr '[A-Z]' '[a-z]' | PROCESS DATA ...
  9812.    You give `tr' two lists of characters enclosed in square brackets.
  9813. Usually, the lists are quoted to keep the shell from attempting to do a
  9814. filename expansion.(1)  When processing the input, the first character
  9815. in the first list is replaced with the first character in the second
  9816. list, the second character in the first list is replaced with the
  9817. second character in the second list, and so on.  If there are more
  9818. characters in the "from" list than in the "to" list, the last character
  9819. of the "to" list is used for the remaining characters in the "from"
  9820. list.
  9821.    Some time ago, a user proposed to us that we add a transliteration
  9822. function to `gawk'.  Being opposed to "creeping featurism," I wrote the
  9823. following program to prove that character transliteration could be done
  9824. with a user-level function.  This program is not as complete as the
  9825. system `tr' utility, but it will do most of the job.
  9826.    The `translate' program demonstrates one of the few weaknesses of
  9827. standard `awk': dealing with individual characters is very painful,
  9828. requiring repeated use of the `substr', `index', and `gsub' built-in
  9829. functions (*note Built-in Functions for String Manipulation: String
  9830. Functions.).(2)
  9831.    There are two functions.  The first, `stranslate', takes three
  9832. arguments.
  9833. `from'
  9834.      A list of characters to translate from.
  9835.      A list of characters to translate to.
  9836. `target'
  9837.      The string to do the translation on.
  9838.    Associative arrays make the translation part fairly easy. `t_ar'
  9839. holds the "to" characters, indexed by the "from" characters.  Then a
  9840. simple loop goes through `from', one character at a time.  For each
  9841. character in `from', if the character appears in `target', `gsub' is
  9842. used to change it to the corresponding `to' character.
  9843.    The `translate' function simply calls `stranslate' using `$0' as the
  9844. target.  The main program sets two global variables, `FROM' and `TO',
  9845. from the command line, and then changes `ARGV' so that `awk' will read
  9846. from the standard input.
  9847.    Finally, the processing rule simply calls `translate' for each
  9848. record.
  9849.      # translate --- do tr like stuff
  9850.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9851.      # August 1989
  9852.      
  9853.      # bugs: does not handle things like: tr A-Z a-z, it has
  9854.      # to be spelled out. However, if `to' is shorter than `from',
  9855.      # the last character in `to' is used for the rest of `from'.
  9856.      
  9857.      function stranslate(from, to, target,     lf, lt, t_ar, i, c)
  9858.      {
  9859.          lf = length(from)
  9860.          lt = length(to)
  9861.          for (i = 1; i <= lt; i++)
  9862.              t_ar[substr(from, i, 1)] = substr(to, i, 1)
  9863.          if (lt < lf)
  9864.              for (; i <= lf; i++)
  9865.                  t_ar[substr(from, i, 1)] = substr(to, lt, 1)
  9866.          for (i = 1; i <= lf; i++) {
  9867.              c = substr(from, i, 1)
  9868.              if (index(target, c) > 0)
  9869.                  gsub(c, t_ar[c], target)
  9870.          }
  9871.          return target
  9872.      }
  9873.      
  9874.      function translate(from, to)
  9875.      {
  9876.          return $0 = stranslate(from, to, $0)
  9877.      }
  9878.      
  9879.      # main program
  9880.      BEGIN {
  9881.          if (ARGC < 3) {
  9882.              print "usage: translate from to" > "/dev/stderr"
  9883.              exit
  9884.          }
  9885.          FROM = ARGV[1]
  9886.          TO = ARGV[2]
  9887.          ARGC = 2
  9888.          ARGV[1] = "-"
  9889.      }
  9890.      
  9891.      {
  9892.          translate(FROM, TO)
  9893.          print
  9894.      }
  9895.    While it is possible to do character transliteration in a user-level
  9896. function, it is not necessarily efficient, and we started to consider
  9897. adding a built-in function.  However, shortly after writing this
  9898. program, we learned that the System V Release 4 `awk' had added the
  9899. `toupper' and `tolower' functions.  These functions handle the vast
  9900. majority of the cases where character transliteration is necessary, and
  9901. so we chose to simply add those functions to `gawk' as well, and then
  9902. leave well enough alone.
  9903.    An obvious improvement to this program would be to set up the `t_ar'
  9904. array only once, in a `BEGIN' rule. However, this assumes that the
  9905. "from" and "to" lists will never change throughout the lifetime of the
  9906. program.
  9907.    ---------- Footnotes ----------
  9908.    (1)  On older, non-POSIX systems, `tr' often does not require that
  9909. the lists be enclosed in square brackets and quoted.  This is a feature.
  9910.    (2)  This program was written before `gawk' acquired the ability to
  9911. split each character in a string into separate array elements.  How
  9912. might this ability simplify the program?
  9913. File: gawk.info,  Node: Labels Program,  Next: Word Sorting,  Prev: Translate Program,  Up: Miscellaneous Programs
  9914. Printing Mailing Labels
  9915. -----------------------
  9916.    Here is a "real world"(1) program.  This script reads lists of names
  9917. and addresses, and generates mailing labels.  Each page of labels has
  9918. 20 labels on it, two across and ten down.  The addresses are guaranteed
  9919. to be no more than five lines of data.  Each address is separated from
  9920. the next by a blank line.
  9921.    The basic idea is to read 20 labels worth of data.  Each line of
  9922. each label is stored in the `line' array.  The single rule takes care
  9923. of filling the `line' array and printing the page when 20 labels have
  9924. been read.
  9925.    The `BEGIN' rule simply sets `RS' to the empty string, so that `awk'
  9926. will split records at blank lines (*note How Input is Split into
  9927. Records: Records.).  It sets `MAXLINES' to 100, since `MAXLINE' is the
  9928. maximum number of lines on the page (20 * 5 = 100).
  9929.    Most of the work is done in the `printpage' function.  The label
  9930. lines are stored sequentially in the `line' array.  But they have to be
  9931. printed horizontally; `line[1]' next to `line[6]', `line[2]' next to
  9932. `line[7]', and so on.  Two loops are used to accomplish this.  The
  9933. outer loop, controlled by `i', steps through every 10 lines of data;
  9934. this is each row of labels.  The inner loop, controlled by `j', goes
  9935. through the lines within the row.  As `j' goes from zero to four, `i+j'
  9936. is the `j''th line in the row, and `i+j+5' is the entry next to it.
  9937. The output ends up looking something like this:
  9938.      line 1          line 6
  9939.      line 2          line 7
  9940.      line 3          line 8
  9941.      line 4          line 9
  9942.      line 5          line 10
  9943.    As a final note, at lines 21 and 61, an extra blank line is printed,
  9944. to keep the output lined up on the labels.  This is dependent on the
  9945. particular brand of labels in use when the program was written.  You
  9946. will also note that there are two blank lines at the top and two blank
  9947. lines at the bottom.
  9948.    The `END' rule arranges to flush the final page of labels; there may
  9949. not have been an even multiple of 20 labels in the data.
  9950.      # labels.awk
  9951.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  9952.      # June 1992
  9953.      
  9954.      # Program to print labels.  Each label is 5 lines of data
  9955.      # that may have blank lines.  The label sheets have 2
  9956.      # blank lines at the top and 2 at the bottom.
  9957.      
  9958.      BEGIN    { RS = "" ; MAXLINES = 100 }
  9959.      
  9960.      function printpage(    i, j)
  9961.      {
  9962.          if (Nlines <= 0)
  9963.              return
  9964.      
  9965.          printf "\n\n"        # header
  9966.      
  9967.          for (i = 1; i <= Nlines; i += 10) {
  9968.              if (i == 21 || i == 61)
  9969.                  print ""
  9970.              for (j = 0; j < 5; j++) {
  9971.                  if (i + j > MAXLINES)
  9972.                      break
  9973.                  printf "   %-41s %s\n", line[i+j], line[i+j+5]
  9974.              }
  9975.              print ""
  9976.          }
  9977.      
  9978.          printf "\n\n"        # footer
  9979.      
  9980.          for (i in line)
  9981.              line[i] = ""
  9982.      }
  9983.      
  9984.      # main rule
  9985.      {
  9986.          if (Count >= 20) {
  9987.              printpage()
  9988.              Count = 0
  9989.              Nlines = 0
  9990.          }
  9991.          n = split($0, a, "\n")
  9992.          for (i = 1; i <= n; i++)
  9993.              line[++Nlines] = a[i]
  9994.          for (; i <= 5; i++)
  9995.              line[++Nlines] = ""
  9996.          Count++
  9997.      }
  9998.      
  9999.      END    \
  10000.      {
  10001.          printpage()
  10002.      }
  10003.    ---------- Footnotes ----------
  10004.    (1)  "Real world" is defined as "a program actually used to get
  10005. something done."
  10006. File: gawk.info,  Node: Word Sorting,  Next: History Sorting,  Prev: Labels Program,  Up: Miscellaneous Programs
  10007. Generating Word Usage Counts
  10008. ----------------------------
  10009.    The following `awk' program prints the number of occurrences of each
  10010. word in its input.  It illustrates the associative nature of `awk'
  10011. arrays by using strings as subscripts.  It also demonstrates the `for X
  10012. in ARRAY' construction.  Finally, it shows how `awk' can be used in
  10013. conjunction with other utility programs to do a useful task of some
  10014. complexity with a minimum of effort.  Some explanations follow the
  10015. program listing.
  10016.      awk '
  10017.      # Print list of word frequencies
  10018.      {
  10019.          for (i = 1; i <= NF; i++)
  10020.              freq[$i]++
  10021.      }
  10022.      
  10023.      END {
  10024.          for (word in freq)
  10025.              printf "%s\t%d\n", word, freq[word]
  10026.      }'
  10027.    The first thing to notice about this program is that it has two
  10028. rules.  The first rule, because it has an empty pattern, is executed on
  10029. every line of the input.  It uses `awk''s field-accessing mechanism
  10030. (*note Examining Fields: Fields.) to pick out the individual words from
  10031. the line, and the built-in variable `NF' (*note Built-in Variables::.)
  10032. to know how many fields are available.
  10033.    For each input word, an element of the array `freq' is incremented to
  10034. reflect that the word has been seen an additional time.
  10035.    The second rule, because it has the pattern `END', is not executed
  10036. until the input has been exhausted.  It prints out the contents of the
  10037. `freq' table that has been built up inside the first action.
  10038.    This program has several problems that would prevent it from being
  10039. useful by itself on real text files:
  10040.    * Words are detected using the `awk' convention that fields are
  10041.      separated by whitespace and that other characters in the input
  10042.      (except newlines) don't have any special meaning to `awk'.  This
  10043.      means that punctuation characters count as part of words.
  10044.    * The `awk' language considers upper- and lower-case characters to be
  10045.      distinct.  Therefore, `bartender' and `Bartender' are not treated
  10046.      as the same word.  This is undesirable since, in normal text, words
  10047.      are capitalized if they begin sentences, and a frequency analyzer
  10048.      should not be sensitive to capitalization.
  10049.    * The output does not come out in any useful order.  You're more
  10050.      likely to be interested in which words occur most frequently, or
  10051.      having an alphabetized table of how frequently each word occurs.
  10052.    The way to solve these problems is to use some of the more advanced
  10053. features of the `awk' language.  First, we use `tolower' to remove case
  10054. distinctions.  Next, we use `gsub' to remove punctuation characters.
  10055. Finally, we use the system `sort' utility to process the output of the
  10056. `awk' script.  Here is the new version of the program:
  10057.      # Print list of word frequencies
  10058.      {
  10059.          $0 = tolower($0)    # remove case distinctions
  10060.          gsub(/[^a-z0-9_ \t]/, "", $0)  # remove punctuation
  10061.          for (i = 1; i <= NF; i++)
  10062.              freq[$i]++
  10063.      }
  10064.      
  10065.      END {
  10066.          for (word in freq)
  10067.              printf "%s\t%d\n", word, freq[word]
  10068.      }
  10069.    Assuming we have saved this program in a file named `wordfreq.awk',
  10070. and that the data is in `file1', the following pipeline
  10071.      awk -f wordfreq.awk file1 | sort +1 -nr
  10072. produces a table of the words appearing in `file1' in order of
  10073. decreasing frequency.
  10074.    The `awk' program suitably massages the data and produces a word
  10075. frequency table, which is not ordered.
  10076.    The `awk' script's output is then sorted by the `sort' utility and
  10077. printed on the terminal.  The options given to `sort' in this example
  10078. specify to sort using the second field of each input line (skipping one
  10079. field), that the sort keys should be treated as numeric quantities
  10080. (otherwise `15' would come before `5'), and that the sorting should be
  10081. done in descending (reverse) order.
  10082.    We could have even done the `sort' from within the program, by
  10083. changing the `END' action to:
  10084.      END {
  10085.          sort = "sort +1 -nr"
  10086.          for (word in freq)
  10087.              printf "%s\t%d\n", word, freq[word] | sort
  10088.          close(sort)
  10089.      }
  10090.    You would have to use this way of sorting on systems that do not
  10091. have true pipes.
  10092.    See the general operating system documentation for more information
  10093. on how to use the `sort' program.
  10094. File: gawk.info,  Node: History Sorting,  Next: Extract Program,  Prev: Word Sorting,  Up: Miscellaneous Programs
  10095. Removing Duplicates from Unsorted Text
  10096. --------------------------------------
  10097.    The `uniq' program (*note Printing Non-duplicated Lines of Text:
  10098. Uniq Program.), removes duplicate lines from *sorted* data.
  10099.    Suppose, however, you need to remove duplicate lines from a data
  10100. file, but that you wish to preserve the order the lines are in?  A good
  10101. example of this might be a shell history file.  The history file keeps
  10102. a copy of all the commands you have entered, and it is not unusual to
  10103. repeat a command several times in a row.  Occasionally you might wish
  10104. to compact the history by removing duplicate entries.  Yet it is
  10105. desirable to maintain the order of the original commands.
  10106.    This simple program does the job.  It uses two arrays.  The `data'
  10107. array is indexed by the text of each line.  For each line, `data[$0]'
  10108. is incremented.
  10109.    If a particular line has not been seen before, then `data[$0]' will
  10110. be zero.  In that case, the text of the line is stored in
  10111. `lines[count]'.  Each element of `lines' is a unique command, and the
  10112. indices of `lines' indicate the order in which those lines were
  10113. encountered.  The `END' rule simply prints out the lines, in order.
  10114.      # histsort.awk --- compact a shell history file
  10115.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  10116.      # May 1993
  10117.      
  10118.      # Thanks to Byron Rakitzis for the general idea
  10119.      {
  10120.          if (data[$0]++ == 0)
  10121.              lines[++count] = $0
  10122.      }
  10123.      
  10124.      END {
  10125.          for (i = 1; i <= count; i++)
  10126.              print lines[i]
  10127.      }
  10128.    This program also provides a foundation for generating other useful
  10129. information.  For example, using the following `print' satement in the
  10130. `END' rule would indicate how often a particular command was used.
  10131.      print data[lines[i]], lines[i]
  10132.    This works because `data[$0]' was incremented each time a line was
  10133. seen.
  10134. File: gawk.info,  Node: Extract Program,  Next: Simple Sed,  Prev: History Sorting,  Up: Miscellaneous Programs
  10135. Extracting Programs from Texinfo Source Files
  10136. ---------------------------------------------
  10137.    The nodes *Note A Library of `awk' Functions: Library Functions, and
  10138. *Note Practical `awk' Programs: Sample Programs, are the top level
  10139. nodes for a large number of `awk' programs.  If you wish to experiment
  10140. with these programs, it is tedious to have to type them in by hand.
  10141. Here we present a program that can extract parts of a Texinfo input
  10142. file into separate files.
  10143.    This Info file is written in Texinfo, the GNU project's document
  10144. formatting language.  A single Texinfo source file can be used to
  10145. produce both printed and on-line documentation.  The Texinfo language
  10146. is described fully, starting with *Note Introduction: (texi)Top.
  10147.    For our purposes, it is enough to know three things about Texinfo
  10148. input files.
  10149.    * The "at" symbol, `@', is special in Texinfo, much like `\' in C or
  10150.      `awk'.  Literal `@' symbols are represented in Texinfo source
  10151.      files as `@@'.
  10152.    * Comments start with either `@c' or `@comment'.  The file
  10153.      extraction program will work by using special comments that start
  10154.      at the beginning of a line.
  10155.    * Example text that should not be split across a page boundary is
  10156.      bracketed between lines containing `@group' and `@end group'
  10157.      commands.
  10158.    The following program, `extract.awk', reads through a Texinfo source
  10159. file, and does two things, based on the special comments.  Upon seeing
  10160. `@c system ...', it runs a command, by extracting the command text from
  10161. the control line and passing it on to the `system' function (*note
  10162. Built-in Functions for Input/Output: I/O Functions.).  Upon seeing `@c
  10163. file FILENAME', each subsequent line is sent to the file FILENAME,
  10164. until `@c endfile' is encountered.  The rules in `extract.awk' will
  10165. match either `@c' or `@comment' by letting the `omment' part be
  10166. optional.  Lines containing `@group' and `@end group' are simply
  10167. removed.  `extract.awk' uses the `join' library function (*note Merging
  10168. an Array Into a String: Join Function.).
  10169.    The example programs in the on-line Texinfo source for `Effective
  10170. AWK Programming' (`gawk.texi') have all been bracketed inside `file',
  10171. and `endfile' lines.  The `gawk' distribution uses a copy of
  10172. `extract.awk' to extract the sample programs and install many of them
  10173. in a standard directory, where `gawk' can find them.
  10174.    `extract.awk' begins by setting `IGNORECASE' to one, so that mixed
  10175. upper-case and lower-case letters in the directives won't matter.
  10176.    The first rule handles calling `system', checking that a command was
  10177. given (`NF' is at least three), and also checking that the command
  10178. exited with a zero exit status, signifying OK.
  10179.      # extract.awk --- extract files and run programs
  10180.      #                 from texinfo files
  10181.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  10182.      # May 1993
  10183.      
  10184.      BEGIN    { IGNORECASE = 1 }
  10185.      
  10186.      /^@c(omment)?[ \t]+system/    \
  10187.      {
  10188.          if (NF < 3) {
  10189.              e = (FILENAME ":" FNR)
  10190.              e = (e  ": badly formed `system' line")
  10191.              print e > "/dev/stderr"
  10192.              next
  10193.          }
  10194.          $1 = ""
  10195.          $2 = ""
  10196.          stat = system($0)
  10197.          if (stat != 0) {
  10198.              e = (FILENAME ":" FNR)
  10199.              e = (e ": warning: system returned " stat)
  10200.              print e > "/dev/stderr"
  10201.          }
  10202.      }
  10203. The variable `e' is used so that the function fits nicely on the screen.
  10204.    The second rule handles moving data into files.  It verifies that a
  10205. file name was given in the directive.  If the file named is not the
  10206. current file, then the current file is closed.  This means that an `@c
  10207. endfile' was not given for that file.  (We should probably print a
  10208. diagnostic in this case, although at the moment we do not.)
  10209.    The `for' loop does the work.  It reads lines using `getline' (*note
  10210. Explicit Input with `getline': Getline.).  For an unexpected end of
  10211. file, it calls the `unexpected_eof' function.  If the line is an
  10212. "endfile" line, then it breaks out of the loop.  If the line is an
  10213. `@group' or `@end group' line, then it ignores it, and goes on to the
  10214. next line.
  10215.    Most of the work is in the following few lines.  If the line has no
  10216. `@' symbols, it can be printed directly.  Otherwise, each leading `@'
  10217. must be stripped off.
  10218.    To remove the `@' symbols, the line is split into separate elements
  10219. of the array `a', using the `split' function (*note Built-in Functions
  10220. for String Manipulation: String Functions.).  Each element of `a' that
  10221. is empty indicates two successive `@' symbols in the original line.
  10222. For each two empty elements (`@@' in the original file), we have to add
  10223. back in a single `@' symbol.
  10224.    When the processing of the array is finished, `join' is called with
  10225. the value of `SUBSEP', to rejoin the pieces back into a single line.
  10226. That line is then printed to the output file.
  10227.      /^@c(omment)?[ \t]+file/    \
  10228.      {
  10229.          if (NF != 3) {
  10230.              e = (FILENAME ":" FNR ": badly formed `file' line")
  10231.              print e > "/dev/stderr"
  10232.              next
  10233.          }
  10234.          if ($3 != curfile) {
  10235.              if (curfile != "")
  10236.                  close(curfile)
  10237.              curfile = $3
  10238.          }
  10239.      
  10240.          for (;;) {
  10241.              if ((getline line) <= 0)
  10242.                  unexpected_eof()
  10243.              if (line ~ /^@c(omment)?[ \t]+endfile/)
  10244.                  break
  10245.              else if (line ~ /^@(end[ \t]+)?group/)
  10246.                  continue
  10247.              if (index(line, "@") == 0) {
  10248.                  print line > curfile
  10249.                  continue
  10250.              }
  10251.              n = split(line, a, "@")
  10252.              # if a[1] == "", means leading @,
  10253.              # don't add one back in.
  10254.              for (i = 2; i <= n; i++) {
  10255.                  if (a[i] == "") { # was an @@
  10256.                      a[i] = "@"
  10257.                      if (a[i+1] == "")
  10258.                          i++
  10259.                  }
  10260.              }
  10261.              print join(a, 1, n, SUBSEP) > curfile
  10262.          }
  10263.      }
  10264.    An important thing to note is the use of the `>' redirection.
  10265. Output done with `>' only opens the file once; it stays open and
  10266. subsequent output is appended to the file (*note Redirecting Output of
  10267. `print' and `printf': Redirection.).  This allows us to easily mix
  10268. program text and explanatory prose for the same sample source file (as
  10269. has been done here!) without any hassle.  The file is only closed when
  10270. a new data file name is encountered, or at the end of the input file.
  10271.    Finally, the function `unexpected_eof' prints an appropriate error
  10272. message and then exits.
  10273.    The `END' rule handles the final cleanup, closing the open file.
  10274.      function unexpected_eof()
  10275.      {
  10276.          printf("%s:%d: unexpected EOF or error\n", \
  10277.              FILENAME, FNR) > "/dev/stderr"
  10278.          exit 1
  10279.      }
  10280.      
  10281.      END {
  10282.          if (curfile)
  10283.              close(curfile)
  10284.      }
  10285. File: gawk.info,  Node: Simple Sed,  Next: Igawk Program,  Prev: Extract Program,  Up: Miscellaneous Programs
  10286. A Simple Stream Editor
  10287. ----------------------
  10288.    The `sed' utility is a "stream editor," a program that reads a
  10289. stream of data, makes changes to it, and passes the modified data on.
  10290. It is often used to make global changes to a large file, or to a stream
  10291. of data generated by a pipeline of commands.
  10292.    While `sed' is a complicated program in its own right, its most
  10293. common use is to perform global substitutions in the middle of a
  10294. pipeline:
  10295.      command1 < orig.data | sed 's/old/new/g' | command2 > result
  10296.    Here, the `s/old/new/g' tells `sed' to look for the regexp `old' on
  10297. each input line, and replace it with the text `new', globally (i.e. all
  10298. the occurrences on a line).  This is similar to `awk''s `gsub' function
  10299. (*note Built-in Functions for String Manipulation: String Functions.).
  10300.    The following program, `awksed.awk', accepts at least two command
  10301. line arguments; the pattern to look for and the text to replace it
  10302. with. Any additional arguments are treated as data file names to
  10303. process. If none are provided, the standard input is used.
  10304.      # awksed.awk --- do s/foo/bar/g using just print
  10305.      #    Thanks to Michael Brennan for the idea
  10306.      
  10307.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  10308.      # August 1995
  10309.      
  10310.      function usage()
  10311.      {
  10312.          print "usage: awksed pat repl [files...]" > "/dev/stderr"
  10313.          exit 1
  10314.      }
  10315.      
  10316.      BEGIN {
  10317.          # validate arguments
  10318.          if (ARGC < 3)
  10319.              usage()
  10320.      
  10321.          RS = ARGV[1]
  10322.          ORS = ARGV[2]
  10323.      
  10324.          # don't use arguments as files
  10325.          ARGV[1] = ARGV[2] = ""
  10326.      }
  10327.      
  10328.      # look ma, no hands!
  10329.      {
  10330.          if (RT == "")
  10331.              printf "%s", $0
  10332.          else
  10333.              print
  10334.      }
  10335.    The program relies on `gawk''s ability to have `RS' be a regexp and
  10336. on the setting of `RT' to the actual text that terminated the record
  10337. (*note How Input is Split into Records: Records.).
  10338.    The idea is to have `RS' be the pattern to look for. `gawk' will
  10339. automatically set `$0' to the text between matches of the pattern.
  10340. This is text that we wish to keep, unmodified.  Then, by setting `ORS'
  10341. to the replacement text, a simple `print' statement will output the
  10342. text we wish to keep, followed by the replacement text.
  10343.    There is one wrinkle to this scheme, which is what to do if the last
  10344. record doesn't end with text that matches `RS'?  Using a `print'
  10345. statement unconditionally prints the replacement text, which is not
  10346. correct.
  10347.    However, if the file did not end in text that matches `RS', `RT'
  10348. will be set to the null string.  In this case, we can print `$0' using
  10349. `printf' (*note Using `printf' Statements for Fancier Printing:
  10350. Printf.).
  10351.    The `BEGIN' rule handles the setup, checking for the right number of
  10352. arguments, and calling `usage' if there is a problem. Then it sets `RS'
  10353. and `ORS' from the command line arguments, and sets `ARGV[1]' and
  10354. `ARGV[2]' to the null string, so that they will not be treated as file
  10355. names (*note Using `ARGC' and `ARGV': ARGC and ARGV.).
  10356.    The `usage' function prints an error message and exits.
  10357.    Finally, the single rule handles the printing scheme outlined above,
  10358. using `print' or `printf' as appropriate, depending upon the value of
  10359. `RT'.
  10360. File: gawk.info,  Node: Igawk Program,  Prev: Simple Sed,  Up: Miscellaneous Programs
  10361. An Easy Way to Use Library Functions
  10362. ------------------------------------
  10363.    Using library functions in `awk' can be very beneficial. It
  10364. encourages code re-use and the writing of general functions. Programs
  10365. are smaller, and therefore clearer.  However, using library functions
  10366. is only easy when writing `awk' programs; it is painful when running
  10367. them, requiring multiple `-f' options.  If `gawk' is unavailable, then
  10368. so too is the `AWKPATH' environment variable and the ability to put
  10369. `awk' functions into a library directory (*note Command Line Options:
  10370. Options.).
  10371.    It would be nice to be able to write programs like so:
  10372.      # library functions
  10373.      @include getopt.awk
  10374.      @include join.awk
  10375.      ...
  10376.      
  10377.      # main program
  10378.      BEGIN {
  10379.          while ((c = getopt(ARGC, ARGV, "a:b:cde")) != -1)
  10380.              ...
  10381.          ...
  10382.      }
  10383.    The following program, `igawk.sh', provides this service.  It
  10384. simulates `gawk''s searching of the `AWKPATH' variable, and also allows
  10385. "nested" includes; i.e. a file that has been included with `@include'
  10386. can contain further `@include' statements.  `igawk' will make an effort
  10387. to only include files once, so that nested includes don't accidentally
  10388. include a library function twice.
  10389.    `igawk' should behave externally just like `gawk'.  This means it
  10390. should accept all of `gawk''s command line arguments, including the
  10391. ability to have multiple source files specified via `-f', and the
  10392. ability to mix command line and library source files.
  10393.    The program is written using the POSIX Shell (`sh') command language.
  10394. The way the program works is as follows:
  10395.   1. Loop through the arguments, saving anything that doesn't represent
  10396.      `awk' source code for later, when the expanded program is run.
  10397.   2. For any arguments that do represent `awk' text, put the arguments
  10398.      into a temporary file that will be expanded.  There are two cases.
  10399.        a. Literal text, provided with `--source' or `--source='.  This
  10400.           text is just echoed directly.  The `echo' program will
  10401.           automatically supply a trailing newline.
  10402.        b. File names provided with `-f'.  We use a neat trick, and echo
  10403.           `@include FILENAME' into the temporary file.  Since the file
  10404.           inclusion program will work the way `gawk' does, this will
  10405.           get the text of the file included into the program at the
  10406.           correct point.
  10407.   3. Run an `awk' program (naturally) over the temporary file to expand
  10408.      `@include' statements.  The expanded program is placed in a second
  10409.      temporary file.
  10410.   4. Run the expanded program with `gawk' and any other original
  10411.      command line arguments that the user supplied (such as the data
  10412.      file names).
  10413.    The initial part of the program turns on shell tracing if the first
  10414. argument was `debug'.  Otherwise, a shell `trap' statement arranges to
  10415. clean up any temporary files on program exit or upon an interrupt.
  10416.    The next part loops through all the command line arguments.  There
  10417. are several cases of interest.
  10418.      This ends the arguments to `igawk'.  Anything else should be
  10419.      passed on to the user's `awk' program without being evaluated.
  10420.      This indicates that the next option is specific to `gawk'.  To make
  10421.      argument processing easier, the `-W' is appended to the front of
  10422.      the remaining arguments and the loop continues.  (This is an `sh'
  10423.      programming trick.  Don't worry about it if you are not familiar
  10424.      with `sh'.)
  10425.      These are saved and passed on to `gawk'.
  10426. `--file'
  10427. `--file='
  10428. `-Wfile='
  10429.      The file name is saved to the temporary file `/tmp/ig.s.$$' with an
  10430.      `@include' statement.  The `sed' utility is used to remove the
  10431.      leading option part of the argument (e.g., `--file=').
  10432. `--source'
  10433. `--source='
  10434. `-Wsource='
  10435.      The source text is echoed into `/tmp/ig.s.$$'.
  10436. `--version'
  10437. `--version'
  10438. `-Wversion'
  10439.      `igawk' prints its version number, and runs `gawk --version' to
  10440.      get the `gawk' version information, and then exits.
  10441.    If none of `-f', `--file', `-Wfile', `--source', or `-Wsource', were
  10442. supplied, then the first non-option argument should be the `awk'
  10443. program.  If there are no command line arguments left, `igawk' prints
  10444. an error message and exits.  Otherwise, the first argument is echoed
  10445. into `/tmp/ig.s.$$'.
  10446.    In any case, after the arguments have been processed, `/tmp/ig.s.$$'
  10447. contains the complete text of the original `awk' program.
  10448.    The `$$' in `sh' represents the current process ID number.  It is
  10449. often used in shell programs to generate unique temporary file names.
  10450. This allows multiple users to run `igawk' without worrying that the
  10451. temporary file names will clash.
  10452.    Here's the program:
  10453.      #! /bin/sh
  10454.      
  10455.      # igawk --- like gawk but do @include processing
  10456.      # Arnold Robbins, arnold@gnu.ai.mit.edu, Public Domain
  10457.      # July 1993
  10458.      
  10459.      if [ "$1" = debug ]
  10460.      then
  10461.          set -x
  10462.          shift
  10463.      else
  10464.          # cleanup on exit, hangup, interrupt, quit, termination
  10465.          trap 'rm -f /tmp/ig.[se].$$' 0 1 2 3 15
  10466.      fi
  10467.      
  10468.      while [ $# -ne 0 ] # loop over arguments
  10469.      do
  10470.          case $1 in
  10471.          --)     shift; break;;
  10472.      
  10473.          -W)     shift
  10474.                  set -- -W"$@"
  10475.                  continue;;
  10476.      
  10477.          -[vF])  opts="$opts $1 '$2'"
  10478.                  shift;;
  10479.      
  10480.          -[vF]*) opts="$opts '$1'" ;;
  10481.      
  10482.          -f)     echo @include "$2" >> /tmp/ig.s.$$
  10483.                  shift;;
  10484.      
  10485.          -f*)    f=`echo "$1" | sed 's/-f//'`
  10486.                  echo @include "$f" >> /tmp/ig.s.$$ ;;
  10487.      
  10488.          -?file=*)    # -Wfile or --file
  10489.                  f=`echo "$1" | sed 's/-.file=//'`
  10490.                  echo @include "$f" >> /tmp/ig.s.$$ ;;
  10491.      
  10492.          -?file)    # get arg, $2
  10493.                  echo @include "$2" >> /tmp/ig.s.$$
  10494.                  shift;;
  10495.      
  10496.          -?source=*)    # -Wsource or --source
  10497.                  t=`echo "$1" | sed 's/-.source=//'`
  10498.                  echo "$t" >> /tmp/ig.s.$$ ;;
  10499.      
  10500.          -?source)  # get arg, $2
  10501.                  echo "$2" >> /tmp/ig.s.$$
  10502.                  shift;;
  10503.      
  10504.          -?version)
  10505.                  echo igawk: version 1.0 1>&2
  10506.                  gawk --version
  10507.                  exit 0 ;;
  10508.      
  10509.          -[W-]*)    opts="$opts '$1'" ;;
  10510.      
  10511.          *)      break;;
  10512.          esac
  10513.          shift
  10514.      done
  10515.      
  10516.      if [ ! -s /tmp/ig.s.$$ ]
  10517.      then
  10518.          if [ -z "$1" ]
  10519.          then
  10520.               echo igawk: no program! 1>&2
  10521.               exit 1
  10522.          else
  10523.              echo "$1" > /tmp/ig.s.$$
  10524.              shift
  10525.          fi
  10526.      fi
  10527.      
  10528.      # at this point, /tmp/ig.s.$$ has the program
  10529.    The `awk' program to process `@include' directives reads through the
  10530. program, one line at a time using `getline' (*note Explicit Input with
  10531. `getline': Getline.).  The input file names and `@include' statements
  10532. are managed using a stack.  As each `@include' is encountered, the
  10533. current file name is "pushed" onto the stack, and the file named in the
  10534. `@include' directive becomes the current file name.  As each file is
  10535. finished, the stack is "popped," and the previous input file becomes
  10536. the current input file again.  The process is started by making the
  10537. original file the first one on the stack.
  10538.    The `pathto' function does the work of finding the full path to a
  10539. file.  It simulates `gawk''s behavior when searching the `AWKPATH'
  10540. environment variable (*note The `AWKPATH' Environment Variable: AWKPATH
  10541. Variable.).  If a file name has a `/' in it, no path search is done.
  10542. Otherwise, the file name is concatenated with the name of each
  10543. directory in the path, and an attempt is made to open the generated file
  10544. name.  The only way in `awk' to test if a file can be read is to go
  10545. ahead and try to read it with `getline'; that is what `pathto' does.(1)
  10546. If the file can be read, it is closed, and the file name is returned.
  10547.      gawk -- '
  10548.      # process @include directives
  10549.      
  10550.      function pathto(file,    i, t, junk)
  10551.      {
  10552.          if (index(file, "/") != 0)
  10553.              return file
  10554.      
  10555.          for (i = 1; i <= ndirs; i++) {
  10556.              t = (pathlist[i] "/" file)
  10557.              if ((getline junk < t) > 0) {
  10558.                  # found it
  10559.                  close(t)
  10560.                  return t
  10561.              }
  10562.          }
  10563.          return ""
  10564.      }
  10565.    The main program is contained inside one `BEGIN' rule.  The first
  10566. thing it does is set up the `pathlist' array that `pathto' uses.  After
  10567. splitting the path on `:', null elements are replaced with `"."', which
  10568. represents the current directory.
  10569.      BEGIN {
  10570.          path = ENVIRON["AWKPATH"]
  10571.          ndirs = split(path, pathlist, ":")
  10572.          for (i = 1; i <= ndirs; i++) {
  10573.              if (pathlist[i] == "")
  10574.                  pathlist[i] = "."
  10575.          }
  10576.    The stack is initialized with `ARGV[1]', which will be
  10577. `/tmp/ig.s.$$'.  The main loop comes next.  Input lines are read in
  10578. succession. Lines that do not start with `@include' are printed
  10579. verbatim.
  10580.    If the line does start with `@include', the file name is in `$2'.
  10581. `pathto' is called to generate the full path.  If it could not, then we
  10582. print an error message and continue.
  10583.    The next thing to check is if the file has been included already.
  10584. The `processed' array is indexed by the full file name of each included
  10585. file, and it tracks this information for us.  If the file has been
  10586. seen, a warning message is printed. Otherwise, the new file name is
  10587. pushed onto the stack and processing continues.
  10588.    Finally, when `getline' encounters the end of the input file, the
  10589. file is closed and the stack is popped.  When `stackptr' is less than
  10590. zero, the program is done.
  10591.          stackptr = 0
  10592.          input[stackptr] = ARGV[1] # ARGV[1] is first file
  10593.      
  10594.          for (; stackptr >= 0; stackptr--) {
  10595.              while ((getline < input[stackptr]) > 0) {
  10596.                  if (tolower($1) != "@include") {
  10597.                      print
  10598.                      continue
  10599.                  }
  10600.                  fpath = pathto($2)
  10601.                  if (fpath == "") {
  10602.                      printf("igawk:%s:%d: cannot find %s\n", \
  10603.                          input[stackptr], FNR, $2) > "/dev/stderr"
  10604.                      continue
  10605.                  }
  10606.                  if (! (fpath in processed)) {
  10607.                      processed[fpath] = input[stackptr]
  10608.                      input[++stackptr] = fpath
  10609.                  } else
  10610.                      print $2, "included in", input[stackptr], \
  10611.                          "already included in", \
  10612.                          processed[fpath] > "/dev/stderr"
  10613.              }
  10614.              close(input[stackptr])
  10615.          }
  10616.      }' /tmp/ig.s.$$ > /tmp/ig.e.$$
  10617.    The last step is to call `gawk' with the expanded program and the
  10618. original options and command line arguments that the user supplied.
  10619. `gawk''s exit status is passed back on to `igawk''s calling program.
  10620.      eval gawk -f /tmp/ig.e.$$ $opts -- "$@"
  10621.      
  10622.      exit $?
  10623.    This version of `igawk' represents my third attempt at this program.
  10624. There are three key simplifications that made the program work better.
  10625.   1. Using `@include' even for the files named with `-f' makes building
  10626.      the initial collected `awk' program much simpler; all the
  10627.      `@include' processing can be done once.
  10628.   2. The `pathto' function doesn't try to save the line read with
  10629.      `getline' when testing for the file's accessibility.  Trying to
  10630.      save this line for use with the main program complicates things
  10631.      considerably.
  10632.   3. Using a `getline' loop in the `BEGIN' rule does it all in one
  10633.      place.  It is not necessary to call out to a separate loop for
  10634.      processing nested `@include' statements.
  10635.    Also, this program illustrates that it is often worthwhile to combine
  10636. `sh' and `awk' programming together.  You can usually accomplish quite
  10637. a lot, without having to resort to low-level programming in C or C++,
  10638. and it is frequently easier to do certain kinds of string and argument
  10639. manipulation using the shell than it is in `awk'.
  10640.    Finally, `igawk' shows that it is not always necessary to add new
  10641. features to a program; they can often be layered on top.  With `igawk',
  10642. there is no real reason to build `@include' processing into `gawk'
  10643. itself.
  10644.    As an additional example of this, consider the idea of having two
  10645. files in a directory in the search path.
  10646. `default.awk'
  10647.      This file would contain a set of default library functions, such
  10648.      as `getopt' and `assert'.
  10649. `site.awk'
  10650.      This file would contain library functions that are specific to a
  10651.      site or installation, i.e. locally developed functions.  Having a
  10652.      separate file allows `default.awk' to change with new `gawk'
  10653.      releases, without requiring the system administrator to update it
  10654.      each time by adding the local functions.
  10655.    One user suggested that `gawk' be modified to automatically read
  10656. these files upon startup.  Instead, it would be very simple to modify
  10657. `igawk' to do this. Since `igawk' can process nested `@include'
  10658. directives, `default.awk' could simply contain `@include' statements
  10659. for the desired library functions.
  10660.    ---------- Footnotes ----------
  10661.    (1)  On some very old versions of `awk', the test `getline junk < t'
  10662. can loop forever if the file exists but is empty.  Caveat Emptor.
  10663. File: gawk.info,  Node: Language History,  Next: Gawk Summary,  Prev: Sample Programs,  Up: Top
  10664. The Evolution of the `awk' Language
  10665. ***********************************
  10666.    This Info file describes the GNU implementation of `awk', which
  10667. follows the POSIX specification.  Many `awk' users are only familiar
  10668. with the original `awk' implementation in Version 7 Unix.  (This
  10669. implementation was the basis for `awk' in Berkeley Unix, through
  10670. 4.3-Reno.  The 4.4 release of Berkeley Unix uses `gawk' 2.15.2 for its
  10671. version of `awk'.) This chapter briefly describes the evolution of the
  10672. `awk' language, with cross references to other parts of the Info file
  10673. where you can find more information.
  10674. * Menu:
  10675. * V7/SVR3.1::                   The major changes between V7 and System V
  10676.                                 Release 3.1.
  10677. * SVR4::                        Minor changes between System V Releases 3.1
  10678.                                 and 4.
  10679. * POSIX::                       New features from the POSIX standard.
  10680. * BTL::                         New features from the Bell Laboratories
  10681.                                 version of `awk'.
  10682. * POSIX/GNU::                   The extensions in `gawk' not in POSIX
  10683.                                 `awk'.
  10684. File: gawk.info,  Node: V7/SVR3.1,  Next: SVR4,  Prev: Language History,  Up: Language History
  10685. Major Changes between V7 and SVR3.1
  10686. ===================================
  10687.    The `awk' language evolved considerably between the release of
  10688. Version 7 Unix (1978) and the new version first made generally
  10689. available in System V Release 3.1 (1987).  This section summarizes the
  10690. changes, with cross-references to further details.
  10691.    * The requirement for `;' to separate rules on a line (*note `awk'
  10692.      Statements Versus Lines: Statements/Lines.).
  10693.    * User-defined functions, and the `return' statement (*note
  10694.      User-defined Functions: User-defined.).
  10695.    * The `delete' statement (*note The `delete' Statement: Delete.).
  10696.    * The `do'-`while' statement (*note The `do'-`while' Statement: Do
  10697.      Statement.).
  10698.    * The built-in functions `atan2', `cos', `sin', `rand' and `srand'
  10699.      (*note Numeric Built-in Functions: Numeric Functions.).
  10700.    * The built-in functions `gsub', `sub', and `match' (*note Built-in
  10701.      Functions for String Manipulation: String Functions.).
  10702.    * The built-in functions `close', and `system' (*note Built-in
  10703.      Functions for Input/Output: I/O Functions.).
  10704.    * The `ARGC', `ARGV', `FNR', `RLENGTH', `RSTART', and `SUBSEP'
  10705.      built-in variables (*note Built-in Variables::.).
  10706.    * The conditional expression using the ternary operator `?:' (*note
  10707.      Conditional Expressions: Conditional Exp.).
  10708.    * The exponentiation operator `^' (*note Arithmetic Operators:
  10709.      Arithmetic Ops.) and its assignment operator form `^=' (*note
  10710.      Assignment Expressions: Assignment Ops.).
  10711.    * C-compatible operator precedence, which breaks some old `awk'
  10712.      programs (*note Operator Precedence (How Operators Nest):
  10713.      Precedence.).
  10714.    * Regexps as the value of `FS' (*note Specifying How Fields are
  10715.      Separated: Field Separators.), and as the third argument to the
  10716.      `split' function (*note Built-in Functions for String
  10717.      Manipulation: String Functions.).
  10718.    * Dynamic regexps as operands of the `~' and `!~' operators (*note
  10719.      How to Use Regular Expressions: Regexp Usage.).
  10720.    * The escape sequences `\b', `\f', and `\r' (*note Escape
  10721.      Sequences::.).  (Some vendors have updated their old versions of
  10722.      `awk' to recognize `\r', `\b', and `\f', but this is not something
  10723.      you can rely on.)
  10724.    * Redirection of input for the `getline' function (*note Explicit
  10725.      Input with `getline': Getline.).
  10726.    * Multiple `BEGIN' and `END' rules (*note The `BEGIN' and `END'
  10727.      Special Patterns: BEGIN/END.).
  10728.    * Multi-dimensional arrays (*note Multi-dimensional Arrays:
  10729.      Multi-dimensional.).
  10730. File: gawk.info,  Node: SVR4,  Next: POSIX,  Prev: V7/SVR3.1,  Up: Language History
  10731. Changes between SVR3.1 and SVR4
  10732. ===============================
  10733.    The System V Release 4 version of Unix `awk' added these features
  10734. (some of which originated in `gawk'):
  10735.    * The `ENVIRON' variable (*note Built-in Variables::.).
  10736.    * Multiple `-f' options on the command line (*note Command Line
  10737.      Options: Options.).
  10738.    * The `-v' option for assigning variables before program execution
  10739.      begins (*note Command Line Options: Options.).
  10740.    * The `--' option for terminating command line options.
  10741.    * The `\a', `\v', and `\x' escape sequences (*note Escape
  10742.      Sequences::.).
  10743.    * A defined return value for the `srand' built-in function (*note
  10744.      Numeric Built-in Functions: Numeric Functions.).
  10745.    * The `toupper' and `tolower' built-in string functions for case
  10746.      translation (*note Built-in Functions for String Manipulation:
  10747.      String Functions.).
  10748.    * A cleaner specification for the `%c' format-control letter in the
  10749.      `printf' function (*note Format-Control Letters: Control Letters.).
  10750.    * The ability to dynamically pass the field width and precision
  10751.      (`"%*.*d"') in the argument list of the `printf' function (*note
  10752.      Format-Control Letters: Control Letters.).
  10753.    * The use of regexp constants such as `/foo/' as expressions, where
  10754.      they are equivalent to using the matching operator, as in `$0 ~
  10755.      /foo/' (*note Using Regular Expression Constants: Using Constant
  10756.      Regexps.).
  10757. File: gawk.info,  Node: POSIX,  Next: BTL,  Prev: SVR4,  Up: Language History
  10758. Changes between SVR4 and POSIX `awk'
  10759. ====================================
  10760.    The POSIX Command Language and Utilities standard for `awk'
  10761. introduced the following changes into the language:
  10762.    * The use of `-W' for implementation-specific options.
  10763.    * The use of `CONVFMT' for controlling the conversion of numbers to
  10764.      strings (*note Conversion of Strings and Numbers: Conversion.).
  10765.    * The concept of a numeric string, and tighter comparison rules to go
  10766.      with it (*note Variable Typing and Comparison Expressions: Typing
  10767.      and Comparison.).
  10768.    * More complete documentation of many of the previously undocumented
  10769.      features of the language.
  10770.    The following common extensions are not permitted by the POSIX
  10771. standard:
  10772.    * `\x' escape sequences are not recognized (*note Escape
  10773.      Sequences::.).
  10774.    * Newlines do not act as whitespace to separate fields when `FS' is
  10775.      equal to a single space.
  10776.    * The synonym `func' for the keyword `function' is not recognized
  10777.      (*note Function Definition Syntax: Definition Syntax.).
  10778.    * The operators `**' and `**=' cannot be used in place of `^' and
  10779.      `^=' (*note Arithmetic Operators: Arithmetic Ops., and also *note
  10780.      Assignment Expressions: Assignment Ops.).
  10781.    * Specifying `-Ft' on the command line does not set the value of
  10782.      `FS' to be a single tab character (*note Specifying How Fields are
  10783.      Separated: Field Separators.).
  10784.    * The `fflush' built-in function is not supported (*note Built-in
  10785.      Functions for Input/Output: I/O Functions.).
  10786. File: gawk.info,  Node: BTL,  Next: POSIX/GNU,  Prev: POSIX,  Up: Language History
  10787. Extensions in the Bell Laboratories `awk'
  10788. =========================================
  10789.    Brian Kernighan, one of the original designers of Unix `awk', has
  10790. made his version available via anonymous `ftp' (*note Other Freely
  10791. Available `awk' Implementations: Other Versions.).  This section
  10792. describes extensions in his version of `awk' that are not in POSIX
  10793. `awk'.
  10794.    * The `-mf NNN' and `-mr NNN' command line options to set the
  10795.      maximum number of fields, and the maximum record size, respectively
  10796.      (*note Command Line Options: Options.).
  10797.    * The `fflush' built-in function for flushing buffered output (*note
  10798.      Built-in Functions for Input/Output: I/O Functions.).
  10799. File: gawk.info,  Node: POSIX/GNU,  Prev: BTL,  Up: Language History
  10800. Extensions in `gawk' Not in POSIX `awk'
  10801. =======================================
  10802.    The GNU implementation, `gawk', adds a number of features.  This
  10803. sections lists them in the order they were added to `gawk'.  They can
  10804. all be disabled with either the `--traditional' or `--posix' options
  10805. (*note Command Line Options: Options.).
  10806.    Version 2.10 of `gawk' introduced these features:
  10807.    * The `AWKPATH' environment variable for specifying a path search for
  10808.      the `-f' command line option (*note Command Line Options:
  10809.      Options.).
  10810.    * The `IGNORECASE' variable and its effects (*note Case-sensitivity
  10811.      in Matching: Case-sensitivity.).
  10812.    * The `/dev/stdin', `/dev/stdout', `/dev/stderr', and `/dev/fd/N'
  10813.      file name interpretation (*note Special File Names in `gawk':
  10814.      Special Files.).
  10815.    Version 2.13 of `gawk' introduced these features:
  10816.    * The `FIELDWIDTHS' variable and its effects (*note Reading
  10817.      Fixed-width Data: Constant Size.).
  10818.    * The `systime' and `strftime' built-in functions for obtaining and
  10819.      printing time stamps (*note Functions for Dealing with Time
  10820.      Stamps: Time Functions.).
  10821.    * The `-W lint' option to provide source code and run time error and
  10822.      portability checking (*note Command Line Options: Options.).
  10823.    * The `-W compat' option to turn off these extensions (*note Command
  10824.      Line Options: Options.).
  10825.    * The `-W posix' option for full POSIX compliance (*note Command
  10826.      Line Options: Options.).
  10827.    Version 2.14 of `gawk' introduced these features:
  10828.    * The `next file' statement for skipping to the next data file
  10829.      (*note The `nextfile' Statement: Nextfile Statement.).
  10830.    Version 2.15 of `gawk' introduced these features:
  10831.    * The `ARGIND' variable, that tracks the movement of `FILENAME'
  10832.      through `ARGV'  (*note Built-in Variables::.).
  10833.    * The `ERRNO' variable, that contains the system error message when
  10834.      `getline' returns -1, or when `close' fails (*note Built-in
  10835.      Variables::.).
  10836.    * The ability to use GNU-style long named options that start with
  10837.      `--' (*note Command Line Options: Options.).
  10838.    * The `--source' option for mixing command line and library file
  10839.      source code (*note Command Line Options: Options.).
  10840.    * The `/dev/pid', `/dev/ppid', `/dev/pgrpid', and `/dev/user' file
  10841.      name interpretation (*note Special File Names in `gawk': Special
  10842.      Files.).
  10843.    Version 3.0 of `gawk' introduced these features:
  10844.    * The `next file' statement became `nextfile' (*note The `nextfile'
  10845.      Statement: Nextfile Statement.).
  10846.    * The `--lint-old' option to warn about constructs that are not
  10847.      available in the original Version 7 Unix version of `awk' (*note
  10848.      Major Changes between V7 and SVR3.1: V7/SVR3.1.).
  10849.    * The `--traditional' option was added as a better name for
  10850.      `--compat' (*note Command Line Options: Options.).
  10851.    * The ability for `FS' to be a null string, and for the third
  10852.      argument to `split' to be the null string (*note Making Each
  10853.      Character a Separate Field: Single Character Fields.).
  10854.    * The ability for `RS' to be a regexp (*note How Input is Split into
  10855.      Records: Records.).
  10856.    * The `RT' variable (*note How Input is Split into Records:
  10857.      Records.).
  10858.    * The `gensub' function for more powerful text manipulation (*note
  10859.      Built-in Functions for String Manipulation: String Functions.).
  10860.    * The `strftime' function acquired a default time format, allowing
  10861.      it to be called with no arguments (*note Functions for Dealing
  10862.      with Time Stamps: Time Functions.).
  10863.    * Full support for both POSIX and GNU regexps (*note Regular
  10864.      Expressions: Regexp.).
  10865.    * The `--re-interval' option to provide interval expressions in
  10866.      regexps (*note Regular Expression Operators: Regexp Operators.).
  10867.    * `IGNORECASE' changed, now applying to string comparison as well as
  10868.      regexp operations (*note Case-sensitivity in Matching:
  10869.      Case-sensitivity.).
  10870.    * The `-m' option and the `fflush' function from the Bell Labs
  10871.      research version of `awk' (*note Command Line Options: Options.;
  10872.      also *note Built-in Functions for Input/Output: I/O Functions.).
  10873.    * The use of GNU Autoconf to control the configuration process
  10874.      (*note Compiling `gawk' for Unix: Quick Installation.).
  10875.    * Amiga support (*note Installing `gawk' on an Amiga: Amiga
  10876.      Installation.).
  10877. File: gawk.info,  Node: Gawk Summary,  Next: Installation,  Prev: Language History,  Up: Top
  10878. `gawk' Summary
  10879. **************
  10880.    This appendix provides a brief summary of the `gawk' command line
  10881. and the `awk' language.  It is designed to serve as "quick reference."
  10882. It is therefore terse, but complete.
  10883. * Menu:
  10884. * Command Line Summary::        Recapitulation of the command line.
  10885. * Language Summary::            A terse review of the language.
  10886. * Variables/Fields::            Variables, fields, and arrays.
  10887. * Rules Summary::               Patterns and Actions, and their component
  10888.                                 parts.
  10889. * Actions Summary::             Quick overview of actions.
  10890. * Functions Summary::           Defining and calling functions.
  10891. * Historical Features::         Some undocumented but supported "features".
  10892. File: gawk.info,  Node: Command Line Summary,  Next: Language Summary,  Prev: Gawk Summary,  Up: Gawk Summary
  10893. Command Line Options Summary
  10894. ============================
  10895.    The command line consists of options to `gawk' itself, the `awk'
  10896. program text (if not supplied via the `-f' option), and values to be
  10897. made available in the `ARGC' and `ARGV' predefined `awk' variables:
  10898.      gawk [POSIX OR GNU STYLE OPTIONS] -f SOURCE-FILE [`--'] FILE ...
  10899.      gawk [POSIX OR GNU STYLE OPTIONS] [`--'] 'PROGRAM' FILE ...
  10900.    The options that `gawk' accepts are:
  10901. `-F FS'
  10902. `--field-separator FS'
  10903.      Use FS for the input field separator (the value of the `FS'
  10904.      predefined variable).
  10905. `-f PROGRAM-FILE'
  10906. `--file PROGRAM-FILE'
  10907.      Read the `awk' program source from the file PROGRAM-FILE, instead
  10908.      of from the first command line argument.
  10909. `-mf NNN'
  10910. `-mr NNN'
  10911.      The `f' flag sets the maximum number of fields, and the `r' flag
  10912.      sets the maximum record size.  These options are ignored by
  10913.      `gawk', since `gawk' has no predefined limits; they are only for
  10914.      compatibility with the Bell Labs research version of Unix `awk'.
  10915. `-v VAR=VAL'
  10916. `--assign VAR=VAL'
  10917.      Assign the variable VAR the value VAL before program execution
  10918.      begins.
  10919. `-W traditional'
  10920. `-W compat'
  10921. `--traditional'
  10922. `--compat'
  10923.      Use compatibility mode, in which `gawk' extensions are turned off.
  10924. `-W copyleft'
  10925. `-W copyright'
  10926. `--copyleft'
  10927. `--copyright'
  10928.      Print the short version of the General Public License on the
  10929.      standard output, and exit.  This option may disappear in a future
  10930.      version of `gawk'.
  10931. `-W help'
  10932. `-W usage'
  10933. `--help'
  10934. `--usage'
  10935.      Print a relatively short summary of the available options on the
  10936.      standard output, and exit.
  10937. `-W lint'
  10938. `--lint'
  10939.      Give warnings about dubious or non-portable `awk' constructs.
  10940. `-W lint-old'
  10941. `--lint-old'
  10942.      Warn about constructs that are not available in the original
  10943.      Version 7 Unix version of `awk'.
  10944. `-W posix'
  10945. `--posix'
  10946.      Use POSIX compatibility mode, in which `gawk' extensions are
  10947.      turned off and additional restrictions apply.
  10948. `-W re-interval'
  10949. `--re-interval'
  10950.      Allow interval expressions (*note Regular Expression Operators:
  10951.      Regexp Operators.), in regexps.
  10952. `-W source=PROGRAM-TEXT'
  10953. `--source PROGRAM-TEXT'
  10954.      Use PROGRAM-TEXT as `awk' program source code.  This option allows
  10955.      mixing command line source code with source code from files, and is
  10956.      particularly useful for mixing command line programs with library
  10957.      functions.
  10958. `-W version'
  10959. `--version'
  10960.      Print version information for this particular copy of `gawk' on
  10961.      the error output.
  10962.      Signal the end of options.  This is useful to allow further
  10963.      arguments to the `awk' program itself to start with a `-'.  This
  10964.      is mainly for consistency with POSIX argument parsing conventions.
  10965.    Any other options are flagged as invalid, but are otherwise ignored.
  10966. *Note Command Line Options: Options, for more details.
  10967. File: gawk.info,  Node: Language Summary,  Next: Variables/Fields,  Prev: Command Line Summary,  Up: Gawk Summary
  10968. Language Summary
  10969. ================
  10970.    An `awk' program consists of a sequence of zero or more
  10971. pattern-action statements and optional function definitions.  One or
  10972. the other of the pattern and action may be omitted.
  10973.      PATTERN    { ACTION STATEMENTS }
  10974.      PATTERN
  10975.                { ACTION STATEMENTS }
  10976.      
  10977.      function NAME(PARAMETER LIST)     { ACTION STATEMENTS }
  10978.    `gawk' first reads the program source from the PROGRAM-FILE(s), if
  10979. specified, or from the first non-option argument on the command line.
  10980. The `-f' option may be used multiple times on the command line.  `gawk'
  10981. reads the program text from all the PROGRAM-FILE files, effectively
  10982. concatenating them in the order they are specified.  This is useful for
  10983. building libraries of `awk' functions, without having to include them
  10984. in each new `awk' program that uses them.  To use a library function in
  10985. a file from a program typed in on the command line, specify `--source
  10986. 'PROGRAM'', and type your program in between the single quotes.  *Note
  10987. Command Line Options: Options.
  10988.    The environment variable `AWKPATH' specifies a search path to use
  10989. when finding source files named with the `-f' option.  The default
  10990. path, which is `.:/usr/local/share/awk'(1) is used if `AWKPATH' is not
  10991. set.  If a file name given to the `-f' option contains a `/' character,
  10992. no path search is performed.  *Note The `AWKPATH' Environment Variable:
  10993. AWKPATH Variable.
  10994.    `gawk' compiles the program into an internal form, and then proceeds
  10995. to read each file named in the `ARGV' array.  The initial values of
  10996. `ARGV' come from the command line arguments.  If there are no files
  10997. named on the command line, `gawk' reads the standard input.
  10998.    If a "file" named on the command line has the form `VAR=VAL', it is
  10999. treated as a variable assignment: the variable VAR is assigned the
  11000. value VAL.  If any of the files have a value that is the null string,
  11001. that element in the list is skipped.
  11002.    For each record in the input, `gawk' tests to see if it matches any
  11003. PATTERN in the `awk' program.  For each pattern that the record
  11004. matches, the associated ACTION is executed.
  11005.    ---------- Footnotes ----------
  11006.    (1)  The path may use a directory other than `/usr/local/share/awk',
  11007. depending upon how `gawk' was built and installed.
  11008. File: gawk.info,  Node: Variables/Fields,  Next: Rules Summary,  Prev: Language Summary,  Up: Gawk Summary
  11009. Variables and Fields
  11010. ====================
  11011.    `awk' variables are not declared; they come into existence when they
  11012. are first used.  Their values are either floating-point numbers or
  11013. strings.  `awk' also has one-dimensional arrays; multiple-dimensional
  11014. arrays may be simulated.  There are several predefined variables that
  11015. `awk' sets as a program runs; these are summarized below.
  11016. * Menu:
  11017. * Fields Summary::              Input field splitting.
  11018. * Built-in Summary::            `awk''s built-in variables.
  11019. * Arrays Summary::              Using arrays.
  11020. * Data Type Summary::           Values in `awk' are numbers or strings.
  11021. File: gawk.info,  Node: Fields Summary,  Next: Built-in Summary,  Prev: Variables/Fields,  Up: Variables/Fields
  11022. Fields
  11023. ------
  11024.    As each input line is read, `gawk' splits the line into FIELDS,
  11025. using the value of the `FS' variable as the field separator.  If `FS'
  11026. is a single character, fields are separated by that character.
  11027. Otherwise, `FS' is expected to be a full regular expression.  In the
  11028. special case that `FS' is a single space, fields are separated by runs
  11029. of spaces, tabs and/or newlines.(1) If `FS' is the null string (`""'),
  11030. then each individual character in the record becomes a separate field.
  11031. Note that the value of `IGNORECASE' (*note Case-sensitivity in
  11032. Matching: Case-sensitivity.) also affects how fields are split when
  11033. `FS' is a regular expression.
  11034.    Each field in the input line may be referenced by its position, `$1',
  11035. `$2', and so on.  `$0' is the whole line.  The value of a field may be
  11036. assigned to as well.  Field numbers need not be constants:
  11037.      n = 5
  11038.      print $n
  11039. prints the fifth field in the input line.  The variable `NF' is set to
  11040. the total number of fields in the input line.
  11041.    References to non-existent fields (i.e. fields after `$NF') return
  11042. the null string.  However, assigning to a non-existent field (e.g.,
  11043. `$(NF+2) = 5') increases the value of `NF', creates any intervening
  11044. fields with the null string as their value, and causes the value of
  11045. `$0' to be recomputed, with the fields being separated by the value of
  11046. `OFS'.  Decrementing `NF' causes the values of fields past the new
  11047. value to be lost, and the value of `$0' to be recomputed, with the
  11048. fields being separated by the value of `OFS'.  *Note Reading Input
  11049. Files: Reading Files.
  11050.    ---------- Footnotes ----------
  11051.    (1)  In POSIX `awk', newline does not separate fields.
  11052. File: gawk.info,  Node: Built-in Summary,  Next: Arrays Summary,  Prev: Fields Summary,  Up: Variables/Fields
  11053. Built-in Variables
  11054. ------------------
  11055.    `gawk''s built-in variables are:
  11056. `ARGC'
  11057.      The number of elements in `ARGV'. See below for what is actually
  11058.      included in `ARGV'.
  11059. `ARGIND'
  11060.      The index in `ARGV' of the current file being processed.  When
  11061.      `gawk' is processing the input data files, it is always true that
  11062.      `FILENAME == ARGV[ARGIND]'.
  11063. `ARGV'
  11064.      The array of command line arguments.  The array is indexed from
  11065.      zero to `ARGC' - 1.  Dynamically changing `ARGC' and the contents
  11066.      of `ARGV' can control the files used for data.  A null-valued
  11067.      element in `ARGV' is ignored. `ARGV' does not include the options
  11068.      to `awk' or the text of the `awk' program itself.
  11069. `CONVFMT'
  11070.      The conversion format to use when converting numbers to strings.
  11071. `FIELDWIDTHS'
  11072.      A space separated list of numbers describing the fixed-width input
  11073.      data.
  11074. `ENVIRON'
  11075.      An array of environment variable values.  The array is indexed by
  11076.      variable name, each element being the value of that variable.
  11077.      Thus, the environment variable `HOME' is `ENVIRON["HOME"]'.  One
  11078.      possible value might be `/home/arnold'.
  11079.      Changing this array does not affect the environment seen by
  11080.      programs which `gawk' spawns via redirection or the `system'
  11081.      function.  (This may change in a future version of `gawk'.)
  11082.      Some operating systems do not have environment variables.  The
  11083.      `ENVIRON' array is empty when running on these systems.
  11084. `ERRNO'
  11085.      The system error message when an error occurs using `getline' or
  11086.      `close'.
  11087. `FILENAME'
  11088.      The name of the current input file.  If no files are specified on
  11089.      the command line, the value of `FILENAME' is the null string.
  11090. `FNR'
  11091.      The input record number in the current input file.
  11092.      The input field separator, a space by default.
  11093. `IGNORECASE'
  11094.      The case-sensitivity flag for string comparisons and regular
  11095.      expression operations.  If `IGNORECASE' has a non-zero value, then
  11096.      pattern matching in rules, record separating with `RS', field
  11097.      splitting with `FS', regular expression matching with `~' and
  11098.      `!~', and the `gensub', `gsub', `index', `match', `split' and
  11099.      `sub' built-in functions all ignore case when doing regular
  11100.      expression operations, and all string comparisons are done
  11101.      ignoring case.  The value of `IGNORECASE' does *not* affect array
  11102.      subscripting.
  11103.      The number of fields in the current input record.
  11104.      The total number of input records seen so far.
  11105. `OFMT'
  11106.      The output format for numbers for the `print' statement, `"%.6g"'
  11107.      by default.
  11108. `OFS'
  11109.      The output field separator, a space by default.
  11110. `ORS'
  11111.      The output record separator, by default a newline.
  11112.      The input record separator, by default a newline.  If `RS' is set
  11113.      to the null string, then records are separated by blank lines.
  11114.      When `RS' is set to the null string, then the newline character
  11115.      always acts as a field separator, in addition to whatever value
  11116.      `FS' may have.  If `RS' is set to a multi-character string, it
  11117.      denotes a regexp; input text matching the regexp separates records.
  11118.      The input text that matched the text denoted by `RS', the record
  11119.      separator.
  11120. `RSTART'
  11121.      The index of the first character last matched by `match'; zero if
  11122.      no match.
  11123. `RLENGTH'
  11124.      The length of the string last matched by `match'; -1 if no match.
  11125. `SUBSEP'
  11126.      The string used to separate multiple subscripts in array elements,
  11127.      by default `"\034"'.
  11128.    *Note Built-in Variables::, for more information.
  11129. File: gawk.info,  Node: Arrays Summary,  Next: Data Type Summary,  Prev: Built-in Summary,  Up: Variables/Fields
  11130. Arrays
  11131. ------
  11132.    Arrays are subscripted with an expression between square brackets
  11133. (`[' and `]').  Array subscripts are *always* strings; numbers are
  11134. converted to strings as necessary, following the standard conversion
  11135. rules (*note Conversion of Strings and Numbers: Conversion.).
  11136.    If you use multiple expressions separated by commas inside the square
  11137. brackets, then the array subscript is a string consisting of the
  11138. concatenation of the individual subscript values, converted to strings,
  11139. separated by the subscript separator (the value of `SUBSEP').
  11140.    The special operator `in' may be used in a conditional context to
  11141. see if an array has an index consisting of a particular value.
  11142.      if (val in array)
  11143.              print array[val]
  11144.    If the array has multiple subscripts, use `(i, j, ...) in ARRAY' to
  11145. test for existence of an element.
  11146.    The `in' construct may also be used in a `for' loop to iterate over
  11147. all the elements of an array.  *Note Scanning All Elements of an Array:
  11148. Scanning an Array.
  11149.    You can remove an element from an array using the `delete' statement.
  11150.    You can clear an entire array using `delete ARRAY'.
  11151.    *Note Arrays in `awk': Arrays.
  11152. File: gawk.info,  Node: Data Type Summary,  Prev: Arrays Summary,  Up: Variables/Fields
  11153. Data Types
  11154. ----------
  11155.    The value of an `awk' expression is always either a number or a
  11156. string.
  11157.    Some contexts (such as arithmetic operators) require numeric values.
  11158. They convert strings to numbers by interpreting the text of the string
  11159. as a number.  If the string does not look like a number, it converts to
  11160. zero.
  11161.    Other contexts (such as concatenation) require string values.  They
  11162. convert numbers to strings by effectively printing them with `sprintf'.
  11163. *Note Conversion of Strings and Numbers: Conversion, for the details.
  11164.    To force conversion of a string value to a number, simply add zero
  11165. to it.  If the value you start with is already a number, this does not
  11166. change it.
  11167.    To force conversion of a numeric value to a string, concatenate it
  11168. with the null string.
  11169.    Comparisons are done numerically if both operands are numeric, or if
  11170. one is numeric and the other is a numeric string.  Otherwise one or
  11171. both operands are converted to strings and a string comparison is
  11172. performed.  Fields, `getline' input, `FILENAME', `ARGV' elements,
  11173. `ENVIRON' elements and the elements of an array created by `split' are
  11174. the only items that can be numeric strings. String constants, such as
  11175. `"3.1415927"' are not numeric strings, they are string constants.  The
  11176. full rules for comparisons are described in *Note Variable Typing and
  11177. Comparison Expressions: Typing and Comparison.
  11178.    Uninitialized variables have the string value `""' (the null, or
  11179. empty, string).  In contexts where a number is required, this is
  11180. equivalent to zero.
  11181.    *Note Variables::, for more information on variable naming and
  11182. initialization; *note Conversion of Strings and Numbers: Conversion.,
  11183. for more information on how variable values are interpreted.
  11184. File: gawk.info,  Node: Rules Summary,  Next: Actions Summary,  Prev: Variables/Fields,  Up: Gawk Summary
  11185. Patterns
  11186. ========
  11187. * Menu:
  11188. * Pattern Summary::             Quick overview of patterns.
  11189. * Regexp Summary::              Quick overview of regular expressions.
  11190.    An `awk' program is mostly composed of rules, each consisting of a
  11191. pattern followed by an action.  The action is enclosed in `{' and `}'.
  11192. Either the pattern may be missing, or the action may be missing, but
  11193. not both.  If the pattern is missing, the action is executed for every
  11194. input record.  A missing action is equivalent to `{ print }', which
  11195. prints the entire line.
  11196.    Comments begin with the `#' character, and continue until the end of
  11197. the line.  Blank lines may be used to separate statements.  Statements
  11198. normally end with a newline; however, this is not the case for lines
  11199. ending in a `,', `{', `?', `:', `&&', or `||'.  Lines ending in `do' or
  11200. `else' also have their statements automatically continued on the
  11201. following line.  In other cases, a line can be continued by ending it
  11202. with a `\', in which case the newline is ignored.
  11203.    Multiple statements may be put on one line by separating each one
  11204. with a `;'.  This applies to both the statements within the action part
  11205. of a rule (the usual case), and to the rule statements.
  11206.    *Note Comments in `awk' Programs: Comments, for information on
  11207. `awk''s commenting convention; *note `awk' Statements Versus Lines:
  11208. Statements/Lines., for a description of the line continuation mechanism
  11209. in `awk'.
  11210. File: gawk.info,  Node: Pattern Summary,  Next: Regexp Summary,  Prev: Rules Summary,  Up: Rules Summary
  11211. Pattern Summary
  11212. ---------------
  11213.    `awk' patterns may be one of the following:
  11214.      /REGULAR EXPRESSION/
  11215.      RELATIONAL EXPRESSION
  11216.      PATTERN && PATTERN
  11217.      PATTERN || PATTERN
  11218.      PATTERN ? PATTERN : PATTERN
  11219.      (PATTERN)
  11220.      ! PATTERN
  11221.      PATTERN1, PATTERN2
  11222.      BEGIN
  11223.      END
  11224.    `BEGIN' and `END' are two special kinds of patterns that are not
  11225. tested against the input.  The action parts of all `BEGIN' rules are
  11226. concatenated as if all the statements had been written in a single
  11227. `BEGIN' rule.  They are executed before any of the input is read.
  11228. Similarly, all the `END' rules are concatenated, and executed when all
  11229. the input is exhausted (or when an `exit' statement is executed).
  11230. `BEGIN' and `END' patterns cannot be combined with other patterns in
  11231. pattern expressions.  `BEGIN' and `END' rules cannot have missing
  11232. action parts.
  11233.    For `/REGULAR-EXPRESSION/' patterns, the associated statement is
  11234. executed for each input record that matches the regular expression.
  11235. Regular expressions are summarized below.
  11236.    A RELATIONAL EXPRESSION may use any of the operators defined below in
  11237. the section on actions.  These generally test whether certain fields
  11238. match certain regular expressions.
  11239.    The `&&', `||', and `!' operators are logical "and," logical "or,"
  11240. and logical "not," respectively, as in C.  They do short-circuit
  11241. evaluation, also as in C, and are used for combining more primitive
  11242. pattern expressions.  As in most languages, parentheses may be used to
  11243. change the order of evaluation.
  11244.    The `?:' operator is like the same operator in C.  If the first
  11245. pattern matches, then the second pattern is matched against the input
  11246. record; otherwise, the third is matched.  Only one of the second and
  11247. third patterns is matched.
  11248.    The `PATTERN1, PATTERN2' form of a pattern is called a range
  11249. pattern.  It matches all input lines starting with a line that matches
  11250. PATTERN1, and continuing until a line that matches PATTERN2, inclusive.
  11251. A range pattern cannot be used as an operand of any of the pattern
  11252. operators.
  11253.    *Note Pattern Elements: Pattern Overview.
  11254. File: gawk.info,  Node: Regexp Summary,  Prev: Pattern Summary,  Up: Rules Summary
  11255. Regular Expressions
  11256. -------------------
  11257.    Regular expressions are based on POSIX EREs (extended regular
  11258. expressions).  The escape sequences allowed in string constants are
  11259. also valid in regular expressions (*note Escape Sequences::.).  Regexps
  11260. are composed of characters as follows:
  11261.      matches the character C (assuming C is none of the characters
  11262.      listed below).
  11263.      matches the literal character C.
  11264.      matches any character, *including* newline.  In strict POSIX mode,
  11265.      `.' does not match the NUL character, which is a character with
  11266.      all bits equal to zero.
  11267.      matches the beginning of a string.
  11268.      matches the end of a string.
  11269. `[ABC...]'
  11270.      matches any of the characters ABC... (character list).
  11271. `[[:CLASS:]]'
  11272.      matches any character in the character class CLASS. Allowable
  11273.      classes are `alnum', `alpha', `blank', `cntrl', `digit', `graph',
  11274.      `lower', `print', `punct', `space', `upper', and `xdigit'.
  11275. `[[.SYMBOL.]]'
  11276.      matches the multi-character collating symbol SYMBOL.  `gawk' does
  11277.      not currently support collating symbols.
  11278. `[[=CLASSNAME=]]'
  11279.      matches any of the equivalent characters in the current locale
  11280.      named by the equivalence class CLASSNAME.  `gawk' does not
  11281.      currently support equivalence classes.
  11282. `[^ABC...]'
  11283.      matches any character except ABC... (negated character list).
  11284. `R1|R2'
  11285.      matches either R1 or R2 (alternation).
  11286. `R1R2'
  11287.      matches R1, and then R2 (concatenation).
  11288.      matches one or more R's.
  11289.      matches zero or more R's.
  11290.      matches zero or one R's.
  11291. `(R)'
  11292.      matches R (grouping).
  11293. `R{N}'
  11294. `R{N,}'
  11295. `R{N,M}'
  11296.      matches at least N, N to any number, or N to M occurrences of R
  11297.      (interval expressions).
  11298.      matches the empty string at either the beginning or the end of a
  11299.      word.
  11300.      matches the empty string within a word.
  11301.      matches the empty string at the beginning of a word.
  11302.      matches the empty string at the end of a word.
  11303.      matches any word-constituent character (alphanumeric characters and
  11304.      the underscore).
  11305.      matches any character that is not word-constituent.
  11306.      matches the empty string at the beginning of a buffer (same as a
  11307.      string in `gawk').
  11308.      matches the empty string at the end of a buffer.
  11309.    The various command line options control how `gawk' interprets
  11310. characters in regexps.
  11311. No options
  11312.      In the default case, `gawk' provide all the facilities of POSIX
  11313.      regexps and the GNU regexp operators described above.  However,
  11314.      interval expressions are not supported.
  11315. `--posix'
  11316.      Only POSIX regexps are supported, the GNU operators are not special
  11317.      (e.g., `\w' matches a literal `w').  Interval expressions are
  11318.      allowed.
  11319. `--traditional'
  11320.      Traditional Unix `awk' regexps are matched. The GNU operators are
  11321.      not special, interval expressions are not available, and neither
  11322.      are the POSIX character classes (`[[:alnum:]]' and so on).
  11323.      Characters described by octal and hexadecimal escape sequences are
  11324.      treated literally, even if they represent regexp metacharacters.
  11325. `--re-interval'
  11326.      Allow interval expressions in regexps, even if `--traditional' has
  11327.      been provided.
  11328.    *Note Regular Expressions: Regexp.
  11329. File: gawk.info,  Node: Actions Summary,  Next: Functions Summary,  Prev: Rules Summary,  Up: Gawk Summary
  11330. Actions
  11331. =======
  11332.    Action statements are enclosed in braces, `{' and `}'.  A missing
  11333. action statement is equivalent to `{ print }'.
  11334.    Action statements consist of the usual assignment, conditional, and
  11335. looping statements found in most languages.  The operators, control
  11336. statements, and Input/Output statements available are similar to those
  11337. in C.
  11338.    Comments begin with the `#' character, and continue until the end of
  11339. the line.  Blank lines may be used to separate statements.  Statements
  11340. normally end with a newline; however, this is not the case for lines
  11341. ending in a `,', `{', `?', `:', `&&', or `||'.  Lines ending in `do' or
  11342. `else' also have their statements automatically continued on the
  11343. following line.  In other cases, a line can be continued by ending it
  11344. with a `\', in which case the newline is ignored.
  11345.    Multiple statements may be put on one line by separating each one
  11346. with a `;'.  This applies to both the statements within the action part
  11347. of a rule (the usual case), and to the rule statements.
  11348.    *Note Comments in `awk' Programs: Comments, for information on
  11349. `awk''s commenting convention; *note `awk' Statements Versus Lines:
  11350. Statements/Lines., for a description of the line continuation mechanism
  11351. in `awk'.
  11352. * Menu:
  11353. * Operator Summary::            `awk' operators.
  11354. * Control Flow Summary::        The control statements.
  11355. * I/O Summary::                 The I/O statements.
  11356. * Printf Summary::              A summary of `printf'.
  11357. * Special File Summary::        Special file names interpreted internally.
  11358. * Built-in Functions Summary::  Built-in numeric and string functions.
  11359. * Time Functions Summary::      Built-in time functions.
  11360. * String Constants Summary::    Escape sequences in strings.
  11361. File: gawk.info,  Node: Operator Summary,  Next: Control Flow Summary,  Prev: Actions Summary,  Up: Actions Summary
  11362. Operators
  11363. ---------
  11364.    The operators in `awk', in order of decreasing precedence, are:
  11365. `(...)'
  11366.      Grouping.
  11367.      Field reference.
  11368. `++ --'
  11369.      Increment and decrement, both prefix and postfix.
  11370.      Exponentiation (`**' may also be used, and `**=' for the assignment
  11371.      operator, but they are not specified in the POSIX standard).
  11372. `+ - !'
  11373.      Unary plus, unary minus, and logical negation.
  11374. `* / %'
  11375.      Multiplication, division, and modulus.
  11376. `+ -'
  11377.      Addition and subtraction.
  11378. `SPACE'
  11379.      String concatenation.
  11380. `< <= > >= != =='
  11381.      The usual relational operators.
  11382. `~ !~'
  11383.      Regular expression match, negated match.
  11384.      Array membership.
  11385.      Logical "and".
  11386.      Logical "or".
  11387.      A conditional expression.  This has the form `EXPR1 ?  EXPR2 :
  11388.      EXPR3'.  If EXPR1 is true, the value of the expression is EXPR2;
  11389.      otherwise it is EXPR3.  Only one of EXPR2 and EXPR3 is evaluated.
  11390. `= += -= *= /= %= ^='
  11391.      Assignment.  Both absolute assignment (`VAR=VALUE') and operator
  11392.      assignment (the other forms) are supported.
  11393.    *Note Expressions::.
  11394. File: gawk.info,  Node: Control Flow Summary,  Next: I/O Summary,  Prev: Operator Summary,  Up: Actions Summary
  11395. Control Statements
  11396. ------------------
  11397.    The control statements are as follows:
  11398.      if (CONDITION) STATEMENT [ else STATEMENT ]
  11399.      while (CONDITION) STATEMENT
  11400.      do STATEMENT while (CONDITION)
  11401.      for (EXPR1; EXPR2; EXPR3) STATEMENT
  11402.      for (VAR in ARRAY) STATEMENT
  11403.      break
  11404.      continue
  11405.      delete ARRAY[INDEX]
  11406.      delete ARRAY
  11407.      exit [ EXPRESSION ]
  11408.      { STATEMENTS }
  11409.    *Note Control Statements in Actions: Statements.
  11410. File: gawk.info,  Node: I/O Summary,  Next: Printf Summary,  Prev: Control Flow Summary,  Up: Actions Summary
  11411. I/O Statements
  11412. --------------
  11413.    The Input/Output statements are as follows:
  11414. `getline'
  11415.      Set `$0' from next input record; set `NF', `NR', `FNR'.  *Note
  11416.      Explicit Input with `getline': Getline.
  11417. `getline <FILE'
  11418.      Set `$0' from next record of FILE; set `NF'.
  11419. `getline VAR'
  11420.      Set VAR from next input record; set `NR', `FNR'.
  11421. `getline VAR <FILE'
  11422.      Set VAR from next record of FILE.
  11423. `COMMAND | getline'
  11424.      Run COMMAND, piping its output into `getline'; sets `$0', `NF',
  11425.      `NR'.
  11426. `COMMAND | getline `var''
  11427.      Run COMMAND, piping its output into `getline'; sets VAR.
  11428. `next'
  11429.      Stop processing the current input record.  The next input record
  11430.      is read and processing starts over with the first pattern in the
  11431.      `awk' program.  If the end of the input data is reached, the `END'
  11432.      rule(s), if any, are executed.  *Note The `next' Statement: Next
  11433.      Statement.
  11434. `nextfile'
  11435.      Stop processing the current input file.  The next input record
  11436.      read comes from the next input file.  `FILENAME' is updated, `FNR'
  11437.      is set to one, `ARGIND' is incremented, and processing starts over
  11438.      with the first pattern in the `awk' program.  If the end of the
  11439.      input data is reached, the `END' rule(s), if any, are executed.
  11440.      Earlier versions of `gawk' used `next file'; this usage is still
  11441.      supported, but is considered to be deprecated.  *Note The
  11442.      `nextfile' Statement: Nextfile Statement.
  11443. `print'
  11444.      Prints the current record.  *Note Printing Output: Printing.
  11445. `print EXPR-LIST'
  11446.      Prints expressions.
  11447. `print EXPR-LIST > FILE'
  11448.      Prints expressions to FILE. If FILE does not exist, it is created.
  11449.      If it does exist, its contents are deleted the first time the
  11450.      `print' is executed.
  11451. `print EXPR-LIST >> FILE'
  11452.      Prints expressions to FILE.  The previous contents of FILE are
  11453.      retained, and the output of `print' is appended to the file.
  11454. `print EXPR-LIST | COMMAND'
  11455.      Prints expressions, sending the output down a pipe to COMMAND.
  11456.      The pipeline to the command stays open until the `close' function
  11457.      is called.
  11458. `printf FMT, EXPR-LIST'
  11459.      Format and print.
  11460. `printf FMT, EXPR-LIST > file'
  11461.      Format and print to FILE. If FILE does not exist, it is created.
  11462.      If it does exist, its contents are deleted the first time the
  11463.      `printf' is executed.
  11464. `printf FMT, EXPR-LIST >> FILE'
  11465.      Format and print to FILE.  The previous contents of FILE are
  11466.      retained, and the output of `printf' is appended to the file.
  11467. `printf FMT, EXPR-LIST | COMMAND'
  11468.      Format and print, sending the output down a pipe to COMMAND.  The
  11469.      pipeline to the command stays open until the `close' function is
  11470.      called.
  11471.    `getline' returns zero on end of file, and -1 on an error.  In the
  11472. event of an error, `getline' will set `ERRNO' to the value of a
  11473. system-dependent string that describes the error.
  11474. File: gawk.info,  Node: Printf Summary,  Next: Special File Summary,  Prev: I/O Summary,  Up: Actions Summary
  11475. `printf' Summary
  11476. ----------------
  11477.    Conversion specification have the form
  11478. `%'[FLAG][WIDTH][`.'PREC]FORMAT.  Items in brackets are optional.
  11479.    The `awk' `printf' statement and `sprintf' function accept the
  11480. following conversion specification formats:
  11481.      An ASCII character.  If the argument used for `%c' is numeric, it
  11482.      is treated as a character and printed.  Otherwise, the argument is
  11483.      assumed to be a string, and the only first character of that
  11484.      string is printed.
  11485.      A decimal number (the integer part).
  11486.      A floating point number of the form `[-]d.dddddde[+-]dd'.  The
  11487.      `%E' format uses `E' instead of `e'.
  11488.      A floating point number of the form [`-']`ddd.dddddd'.
  11489.      Use either the `%e' or `%f' formats, whichever produces a shorter
  11490.      string, with non-significant zeros suppressed.  `%G' will use `%E'
  11491.      instead of `%e'.
  11492.      An unsigned octal number (again, an integer).
  11493.      A character string.
  11494.      An unsigned hexadecimal number (an integer).  The `%X' format uses
  11495.      `A' through `F' instead of `a' through `f' for decimal 10 through
  11496.      15.
  11497.      A single `%' character; no argument is converted.
  11498.    There are optional, additional parameters that may lie between the
  11499. `%' and the control letter:
  11500.      The expression should be left-justified within its field.
  11501. `SPACE'
  11502.      For numeric conversions, prefix positive values with a space, and
  11503.      negative values with a minus sign.
  11504.      The plus sign, used before the width modifier (see below), says to
  11505.      always supply a sign for numeric conversions, even if the data to
  11506.      be formatted is positive. The `+' overrides the space modifier.
  11507.      Use an "alternate form" for certain control letters.  For `o',
  11508.      supply a leading zero.  For `x', and `X', supply a leading `0x' or
  11509.      `0X' for a non-zero result.  For `e', `E', and `f', the result
  11510.      will always contain a decimal point.  For `g', and `G', trailing
  11511.      zeros are not removed from the result.
  11512.      A leading `0' (zero) acts as a flag, that indicates output should
  11513.      be padded with zeros instead of spaces.  This applies even to
  11514.      non-numeric output formats.  This flag only has an effect when the
  11515.      field width is wider than the value to be printed.
  11516. `WIDTH'
  11517.      The field should be padded to this width. The field is normally
  11518.      padded with spaces.  If the `0' flag has been used, it is padded
  11519.      with zeros.
  11520. `.PREC'
  11521.      A number that specifies the precision to use when printing.  For
  11522.      the `e', `E', and `f' formats, this specifies the number of digits
  11523.      you want printed to the right of the decimal point.  For the `g',
  11524.      and `G' formats, it specifies the maximum number of significant
  11525.      digits.  For the `d', `o', `i', `u', `x', and `X' formats, it
  11526.      specifies the minimum number of digits to print.  For the `s'
  11527.      format, it specifies the maximum number of characters from the
  11528.      string that should be printed.
  11529.    Either or both of the WIDTH and PREC values may be specified as `*'.
  11530. In that case, the particular value is taken from the argument list.
  11531.    *Note Using `printf' Statements for Fancier Printing: Printf.
  11532. File: gawk.info,  Node: Special File Summary,  Next: Built-in Functions Summary,  Prev: Printf Summary,  Up: Actions Summary
  11533. Special File Names
  11534. ------------------
  11535.    When doing I/O redirection from either `print' or `printf' into a
  11536. file, or via `getline' from a file, `gawk' recognizes certain special
  11537. file names internally.  These file names allow access to open file
  11538. descriptors inherited from `gawk''s parent process (usually the shell).
  11539. The file names are:
  11540. `/dev/stdin'
  11541.      The standard input.
  11542. `/dev/stdout'
  11543.      The standard output.
  11544. `/dev/stderr'
  11545.      The standard error output.
  11546. `/dev/fd/N'
  11547.      The file denoted by the open file descriptor N.
  11548.    In addition, reading the following files provides process related
  11549. information about the running `gawk' program.  All returned records are
  11550. terminated with a newline.
  11551. `/dev/pid'
  11552.      Returns the process ID of the current process.
  11553. `/dev/ppid'
  11554.      Returns the parent process ID of the current process.
  11555. `/dev/pgrpid'
  11556.      Returns the process group ID of the current process.
  11557. `/dev/user'
  11558.      At least four space-separated fields, containing the return values
  11559.      of the `getuid', `geteuid', `getgid', and `getegid' system calls.
  11560.      If there are any additional fields, they are the group IDs
  11561.      returned by `getgroups' system call.  (Multiple groups may not be
  11562.      supported on all systems.)
  11563. These file names may also be used on the command line to name data
  11564. files.  These file names are only recognized internally if you do not
  11565. actually have files with these names on your system.
  11566.    *Note Special File Names in `gawk': Special Files, for a longer
  11567. description that provides the motivation for this feature.
  11568. File: gawk.info,  Node: Built-in Functions Summary,  Next: Time Functions Summary,  Prev: Special File Summary,  Up: Actions Summary
  11569. Built-in Functions
  11570. ------------------
  11571.    `awk' provides a number of built-in functions for performing numeric
  11572. operations, string related operations, and I/O related operations.
  11573.    The built-in arithmetic functions are:
  11574. `atan2(Y, X)'
  11575.      the arctangent of Y/X in radians.
  11576. `cos(EXPR)'
  11577.      the cosine of EXPR, which is in radians.
  11578. `exp(EXPR)'
  11579.      the exponential function (`e ^ EXPR').
  11580. `int(EXPR)'
  11581.      truncates to integer.
  11582. `log(EXPR)'
  11583.      the natural logarithm of `expr'.
  11584. `rand()'
  11585.      a random number between zero and one.
  11586. `sin(EXPR)'
  11587.      the sine of EXPR, which is in radians.
  11588. `sqrt(EXPR)'
  11589.      the square root function.
  11590. `srand([EXPR])'
  11591.      use EXPR as a new seed for the random number generator.  If no EXPR
  11592.      is provided, the time of day is used.  The return value is the
  11593.      previous seed for the random number generator.
  11594.    `awk' has the following built-in string functions:
  11595. `gensub(REGEX, SUBST, HOW [, TARGET])'
  11596.      If HOW is a string beginning with `g' or `G', then replace each
  11597.      match of REGEX in TARGET with SUBST.  Otherwise, replace the
  11598.      HOW'th occurrence. If TARGET is not supplied, use `$0'.  The
  11599.      return value is the changed string; the original TARGET is not
  11600.      modified. Within SUBST, `\N', where N is a digit from one to nine,
  11601.      can be used to indicate the text that matched the N'th
  11602.      parenthesized subexpression.  This function is `gawk'-specific.
  11603. `gsub(REGEX, SUBST [, TARGET])'
  11604.      for each substring matching the regular expression REGEX in the
  11605.      string TARGET, substitute the string SUBST, and return the number
  11606.      of substitutions. If TARGET is not supplied, use `$0'.
  11607. `index(STR, SEARCH)'
  11608.      returns the index of the string SEARCH in the string STR, or zero
  11609.      if SEARCH is not present.
  11610. `length([STR])'
  11611.      returns the length of the string STR.  The length of `$0' is
  11612.      returned if no argument is supplied.
  11613. `match(STR, REGEX)'
  11614.      returns the position in STR where the regular expression REGEX
  11615.      occurs, or zero if REGEX is not present, and sets the values of
  11616.      `RSTART' and `RLENGTH'.
  11617. `split(STR, ARR [, REGEX])'
  11618.      splits the string STR into the array ARR on the regular expression
  11619.      REGEX, and returns the number of elements.  If REGEX is omitted,
  11620.      `FS' is used instead. REGEX can be the null string, causing each
  11621.      character to be placed into its own array element.  The array ARR
  11622.      is cleared first.
  11623. `sprintf(FMT, EXPR-LIST)'
  11624.      prints EXPR-LIST according to FMT, and returns the resulting
  11625.      string.
  11626. `sub(REGEX, SUBST [, TARGET])'
  11627.      just like `gsub', but only the first matching substring is
  11628.      replaced.
  11629. `substr(STR, INDEX [, LEN])'
  11630.      returns the LEN-character substring of STR starting at INDEX.  If
  11631.      LEN is omitted, the rest of STR is used.
  11632. `tolower(STR)'
  11633.      returns a copy of the string STR, with all the upper-case
  11634.      characters in STR translated to their corresponding lower-case
  11635.      counterparts.  Non-alphabetic characters are left unchanged.
  11636. `toupper(STR)'
  11637.      returns a copy of the string STR, with all the lower-case
  11638.      characters in STR translated to their corresponding upper-case
  11639.      counterparts.  Non-alphabetic characters are left unchanged.
  11640.    The I/O related functions are:
  11641. `close(EXPR)'
  11642.      Close the open file or pipe denoted by EXPR.
  11643. `fflush([EXPR])'
  11644.      Flush any buffered output for the output file or pipe denoted by
  11645.      EXPR.  If EXPR is omitted, standard output is flushed.  If EXPR is
  11646.      the null string (`""'), all output buffers are flushed.
  11647. `system(CMD-LINE)'
  11648.      Execute the command CMD-LINE, and return the exit status.  If your
  11649.      operating system does not support `system', calling it will
  11650.      generate a fatal error.
  11651.      `system("")' can be used to force `awk' to flush any pending
  11652.      output.  This is more portable, but less obvious, than calling
  11653.      `fflush'.
  11654. File: gawk.info,  Node: Time Functions Summary,  Next: String Constants Summary,  Prev: Built-in Functions Summary,  Up: Actions Summary
  11655. Time Functions
  11656. --------------
  11657.    The following two functions are available for getting the current
  11658. time of day, and for formatting time stamps.  They are specific to
  11659. `gawk'.
  11660. `systime()'
  11661.      returns the current time of day as the number of seconds since a
  11662.      particular epoch (Midnight, January 1, 1970 UTC, on POSIX systems).
  11663. `strftime([FORMAT[, TIMESTAMP]])'
  11664.      formats TIMESTAMP according to the specification in FORMAT.  The
  11665.      current time of day is used if no TIMESTAMP is supplied.  A
  11666.      default format equivalent to the output of the `date' utility is
  11667.      used if no FORMAT is supplied.  *Note Functions for Dealing with
  11668.      Time Stamps: Time Functions, for the details on the conversion
  11669.      specifiers that `strftime' accepts.
  11670. File: gawk.info,  Node: String Constants Summary,  Prev: Time Functions Summary,  Up: Actions Summary
  11671. String Constants
  11672. ----------------
  11673.    String constants in `awk' are sequences of characters enclosed in
  11674. double quotes (`"').  Within strings, certain "escape sequences" are
  11675. recognized, as in C.  These are:
  11676.      A literal backslash.
  11677.      The "alert" character; usually the ASCII BEL character.
  11678.      Backspace.
  11679.      Formfeed.
  11680.      Newline.
  11681.      Carriage return.
  11682.      Horizontal tab.
  11683.      Vertical tab.
  11684. `\xHEX DIGITS'
  11685.      The character represented by the string of hexadecimal digits
  11686.      following the `\x'.  As in ANSI C, all following hexadecimal
  11687.      digits are considered part of the escape sequence.  E.g., `"\x1B"'
  11688.      is a string containing the ASCII ESC (escape) character.  (The `\x'
  11689.      escape sequence is not in POSIX `awk'.)
  11690. `\DDD'
  11691.      The character represented by the one, two, or three digit sequence
  11692.      of octal digits.  Thus, `"\033"' is also a string containing the
  11693.      ASCII ESC (escape) character.
  11694.      The literal character C, if C is not one of the above.
  11695.    The escape sequences may also be used inside constant regular
  11696. expressions (e.g., the regexp `/[ \t\f\n\r\v]/' matches whitespace
  11697. characters).
  11698.    *Note Escape Sequences::.
  11699. File: gawk.info,  Node: Functions Summary,  Next: Historical Features,  Prev: Actions Summary,  Up: Gawk Summary
  11700. User-defined Functions
  11701. ======================
  11702.    Functions in `awk' are defined as follows:
  11703.      function NAME(PARAMETER LIST) { STATEMENTS }
  11704.    Actual parameters supplied in the function call are used to
  11705. instantiate the formal parameters declared in the function.  Arrays are
  11706. passed by reference, other variables are passed by value.
  11707.    If there are fewer arguments passed than there are names in
  11708. PARAMETER-LIST, the extra names are given the null string as their
  11709. value.  Extra names have the effect of local variables.
  11710.    The open-parenthesis in a function call of a user-defined function
  11711. must immediately follow the function name, without any intervening
  11712. white space.  This is to avoid a syntactic ambiguity with the
  11713. concatenation operator.
  11714.    The word `func' may be used in place of `function' (but not in POSIX
  11715. `awk').
  11716.    Use the `return' statement to return a value from a function.
  11717.    *Note User-defined Functions: User-defined.
  11718. File: gawk.info,  Node: Historical Features,  Prev: Functions Summary,  Up: Gawk Summary
  11719. Historical Features
  11720. ===================
  11721.    There are two features of historical `awk' implementations that
  11722. `gawk' supports.
  11723.    First, it is possible to call the `length' built-in function not only
  11724. with no arguments, but even without parentheses!
  11725.      a = length
  11726. is the same as either of
  11727.      a = length()
  11728.      a = length($0)
  11729. For example:
  11730.      $ echo abcdef | awk '{ print length }'
  11731.      -| 6
  11732. This feature is marked as "deprecated" in the POSIX standard, and
  11733. `gawk' will issue a warning about its use if `--lint' is specified on
  11734. the command line.  (The ability to use `length' this way was actually
  11735. an accident of the original Unix `awk' implementation.  If any built-in
  11736. function used `$0' as its default argument, it was possible to call
  11737. that function without the parentheses.  In particular, it was common
  11738. practice to use the `length' function in this fashion, and this usage
  11739. was documented in the `awk' manual page.)
  11740.    The other historical feature is the use of either the `break'
  11741. statement, or the `continue' statement outside the body of a `while',
  11742. `for', or `do' loop.  Traditional `awk' implementations have treated
  11743. such usage as equivalent to the `next' statement.  More recent versions
  11744. of Unix `awk' do not allow it. `gawk' supports this usage if
  11745. `--traditional' has been specified.
  11746.    *Note Command Line Options: Options, for more information about the
  11747. `--posix' and `--lint' options.
  11748. File: gawk.info,  Node: Installation,  Next: Notes,  Prev: Gawk Summary,  Up: Top
  11749. Installing `gawk'
  11750. *****************
  11751.    This appendix provides instructions for installing `gawk' on the
  11752. various platforms that are supported by the developers.  The primary
  11753. developers support Unix (and one day, GNU), while the other ports were
  11754. contributed.  The file `ACKNOWLEDGMENT' in the `gawk' distribution
  11755. lists the electronic mail addresses of the people who did the
  11756. respective ports, and they are also provided in *Note Reporting
  11757. Problems and Bugs: Bugs.
  11758. * Menu:
  11759. * Gawk Distribution::           What is in the `gawk' distribution.
  11760. * Unix Installation::           Installing `gawk' under various versions
  11761.                                 of Unix.
  11762. * VMS Installation::            Installing `gawk' on VMS.
  11763. * PC Installation::             Installing and Compiling `gawk' on MS-DOS
  11764.                                 and OS/2
  11765. * Atari Installation::          Installing `gawk' on the Atari ST.
  11766. * Amiga Installation::          Installing `gawk' on an Amiga.
  11767. * Bugs::                        Reporting Problems and Bugs.
  11768. * Other Versions::              Other freely available `awk'
  11769.                                 implementations.
  11770. File: gawk.info,  Node: Gawk Distribution,  Next: Unix Installation,  Prev: Installation,  Up: Installation
  11771. The `gawk' Distribution
  11772. =======================
  11773.    This section first describes how to get the `gawk' distribution, how
  11774. to extract it, and then what is in the various files and subdirectories.
  11775. * Menu:
  11776. * Getting::                     How to get the distribution.
  11777. * Extracting::                  How to extract the distribution.
  11778. * Distribution contents::       What is in the distribution.
  11779. File: gawk.info,  Node: Getting,  Next: Extracting,  Prev: Gawk Distribution,  Up: Gawk Distribution
  11780. Getting the `gawk' Distribution
  11781. -------------------------------
  11782.    There are three ways you can get GNU software.
  11783.   1. You can copy it from someone else who already has it.
  11784.   2. You can order `gawk' directly from the Free Software Foundation.
  11785.      Software distributions are available for Unix, MS-DOS, and VMS, on
  11786.      tape and CD-ROM.  The address is:
  11787.           Free Software Foundation
  11788.           59 Temple Place--Suite 330
  11789.           Boston, MA  02111-1307 USA
  11790.           Phone: +1-617-542-5942
  11791.           Fax (including Japan): +1-617-542-2652
  11792.           E-mail: `gnu@prep.ai.mit.edu'
  11793.      Ordering from the FSF directly contributes to the support of the
  11794.      foundation and to the production of more free software.
  11795.   3. You can get `gawk' by using anonymous `ftp' to the Internet host
  11796.      `ftp.gnu.ai.mit.edu', in the directory `/pub/gnu'.
  11797.      Here is a list of alternate `ftp' sites from which you can obtain
  11798.      GNU software.  When a site is listed as "SITE`:'DIRECTORY" the
  11799.      DIRECTORY indicates the directory where GNU software is kept.  You
  11800.      should use a site that is geographically close to you.
  11801.     Asia:
  11802.          `cair-archive.kaist.ac.kr:/pub/gnu'
  11803.          `ftp.cs.titech.ac.jp'
  11804.          `ftp.nectec.or.th:/pub/mirrors/gnu'
  11805.          `utsun.s.u-tokyo.ac.jp:/ftpsync/prep'
  11806.     Australia:
  11807.          `archie.au:/gnu'
  11808.                (`archie.oz' or `archie.oz.au' for ACSnet)
  11809.     Africa:
  11810.          `ftp.sun.ac.za:/pub/gnu'
  11811.     Middle East:
  11812.          `ftp.technion.ac.il:/pub/unsupported/gnu'
  11813.     Europe:
  11814.          `archive.eu.net'
  11815.          `ftp.denet.dk'
  11816.          `ftp.eunet.ch'
  11817.          `ftp.funet.fi:/pub/gnu'
  11818.          `ftp.ieunet.ie:pub/gnu'
  11819.          `ftp.informatik.rwth-aachen.de:/pub/gnu'
  11820.          `ftp.informatik.tu-muenchen.de'
  11821.          `ftp.luth.se:/pub/unix/gnu'
  11822.          `ftp.mcc.ac.uk'
  11823.          `ftp.stacken.kth.se'
  11824.          `ftp.sunet.se:/pub/gnu'
  11825.          `ftp.univ-lyon1.fr:pub/gnu'
  11826.          `ftp.win.tue.nl:/pub/gnu'
  11827.          `irisa.irisa.fr:/pub/gnu'
  11828.          `isy.liu.se'
  11829.          `nic.switch.ch:/mirror/gnu'
  11830.          `src.doc.ic.ac.uk:/gnu'
  11831.          `unix.hensa.ac.uk:/pub/uunet/systems/gnu'
  11832.     South America:
  11833.          `ftp.inf.utfsm.cl:/pub/gnu'
  11834.          `ftp.unicamp.br:/pub/gnu'
  11835.     Western Canada:
  11836.          `ftp.cs.ubc.ca:/mirror2/gnu'
  11837.     USA:
  11838.          `col.hp.com:/mirrors/gnu'
  11839.          `f.ms.uky.edu:/pub3/gnu'
  11840.          `ftp.cc.gatech.edu:/pub/gnu'
  11841.          `ftp.cs.columbia.edu:/archives/gnu/prep'
  11842.          `ftp.digex.net:/pub/gnu'
  11843.          `ftp.hawaii.edu:/mirrors/gnu'
  11844.          `ftp.kpc.com:/pub/mirror/gnu'
  11845.     USA (continued):
  11846.          `ftp.uu.net:/systems/gnu'
  11847.          `gatekeeper.dec.com:/pub/GNU'
  11848.          `jaguar.utah.edu:/gnustuff'
  11849.          `labrea.stanford.edu'
  11850.          `mrcnext.cso.uiuc.edu:/pub/gnu'
  11851.          `vixen.cso.uiuc.edu:/gnu'
  11852.          `wuarchive.wustl.edu:/systems/gnu'
  11853. File: gawk.info,  Node: Extracting,  Next: Distribution contents,  Prev: Getting,  Up: Gawk Distribution
  11854. Extracting the Distribution
  11855. ---------------------------
  11856.    `gawk' is distributed as a `tar' file compressed with the GNU Zip
  11857. program, `gzip'.
  11858.    Once you have the distribution (for example, `gawk-3.0.3.tar.gz'),
  11859. first use `gzip' to expand the file, and then use `tar' to extract it.
  11860. You can use the following pipeline to produce the `gawk' distribution:
  11861.      # Under System V, add 'o' to the tar flags
  11862.      gzip -d -c gawk-3.0.3.tar.gz | tar -xvpf -
  11863. This will create a directory named `gawk-3.0.3' in the current
  11864. directory.
  11865.    The distribution file name is of the form `gawk-V.R.N.tar.gz'.  The
  11866. V represents the major version of `gawk', the R represents the current
  11867. release of version V, and the N represents a "patch level", meaning
  11868. that minor bugs have been fixed in the release.  The current patch
  11869. level is 3, but when retrieving distributions, you should get the
  11870. version with the highest version, release, and patch level.  (Note that
  11871. release levels greater than or equal to 90 denote "beta," or
  11872. non-production software; you may not wish to retrieve such a version
  11873. unless you don't mind experimenting.)
  11874.    If you are not on a Unix system, you will need to make other
  11875. arrangements for getting and extracting the `gawk' distribution.  You
  11876. should consult a local expert.
  11877. File: gawk.info,  Node: Distribution contents,  Prev: Extracting,  Up: Gawk Distribution
  11878. Contents of the `gawk' Distribution
  11879. -----------------------------------
  11880.    The `gawk' distribution has a number of C source files,
  11881. documentation files, subdirectories and files related to the
  11882. configuration process (*note Compiling and Installing `gawk' on Unix:
  11883. Unix Installation.), and several subdirectories related to different,
  11884. non-Unix, operating systems.
  11885. various `.c', `.y', and `.h' files
  11886.      These files are the actual `gawk' source code.
  11887. `README'
  11888. `README_d/README.*'
  11889.      Descriptive files: `README' for `gawk' under Unix, and the rest
  11890.      for the various hardware and software combinations.
  11891. `INSTALL'
  11892.      A file providing an overview of the configuration and installation
  11893.      process.
  11894. `PORTS'
  11895.      A list of systems to which `gawk' has been ported, and which have
  11896.      successfully run the test suite.
  11897. `ACKNOWLEDGMENT'
  11898.      A list of the people who contributed major parts of the code or
  11899.      documentation.
  11900. `ChangeLog'
  11901.      A detailed list of source code changes as bugs are fixed or
  11902.      improvements made.
  11903. `NEWS'
  11904.      A list of changes to `gawk' since the last release or patch.
  11905. `COPYING'
  11906.      The GNU General Public License.
  11907. `FUTURES'
  11908.      A brief list of features and/or changes being contemplated for
  11909.      future releases, with some indication of the time frame for the
  11910.      feature, based on its difficulty.
  11911. `LIMITATIONS'
  11912.      A list of those factors that limit `gawk''s performance.  Most of
  11913.      these depend on the hardware or operating system software, and are
  11914.      not limits in `gawk' itself.
  11915. `POSIX.STD'
  11916.      A description of one area where the POSIX standard for `awk' is
  11917.      incorrect, and how `gawk' handles the problem.
  11918. `PROBLEMS'
  11919.      A file describing known problems with the current release.
  11920. `doc/awkforai.txt'
  11921.      A short article describing why `gawk' is a good language for AI
  11922.      (Artificial Intelligence) programming.
  11923. `doc/README.card'
  11924. `doc/ad.block'
  11925. `doc/awkcard.in'
  11926. `doc/cardfonts'
  11927. `doc/colors'
  11928. `doc/macros'
  11929. `doc/no.colors'
  11930. `doc/setter.outline'
  11931.      The `troff' source for a five-color `awk' reference card.  A
  11932.      modern version of `troff', such as GNU Troff (`groff') is needed
  11933.      to produce the color version. See the file `README.card' for
  11934.      instructions if you have an older `troff'.
  11935. `doc/gawk.1'
  11936.      The `troff' source for a manual page describing `gawk'.  This is
  11937.      distributed for the convenience of Unix users.
  11938. `doc/gawk.texi'
  11939.      The Texinfo source file for this Info file.  It should be
  11940.      processed with TeX to produce a printed document, and with
  11941.      `makeinfo' to produce an Info file.
  11942. `doc/gawk.info'
  11943.      The generated Info file for this Info file.
  11944. `doc/igawk.1'
  11945.      The `troff' source for a manual page describing the `igawk'
  11946.      program presented in *Note An Easy Way to Use Library Functions:
  11947.      Igawk Program.
  11948. `doc/Makefile.in'
  11949.      The input file used during the configuration process to generate
  11950.      the actual `Makefile' for creating the documentation.
  11951. `Makefile.in'
  11952. `acconfig.h'
  11953. `aclocal.m4'
  11954. `configh.in'
  11955. `configure.in'
  11956. `configure'
  11957. `custom.h'
  11958. `missing/*'
  11959.      These files and subdirectory are used when configuring `gawk' for
  11960.      various Unix systems.  They are explained in detail in *Note
  11961.      Compiling and Installing `gawk' on Unix: Unix Installation.
  11962. `awklib/extract.awk'
  11963. `awklib/Makefile.in'
  11964.      The `awklib' directory contains a copy of `extract.awk' (*note
  11965.      Extracting Programs from Texinfo Source Files: Extract Program.),
  11966.      which can be used to extract the sample programs from the Texinfo
  11967.      source file for this Info file, and a `Makefile.in' file, which
  11968.      `configure' uses to generate a `Makefile'.  As part of the process
  11969.      of building `gawk', the library functions from *Note A Library of
  11970.      `awk' Functions: Library Functions, and the `igawk' program from
  11971.      *Note An Easy Way to Use Library Functions: Igawk Program, are
  11972.      extracted into ready to use files.  They are installed as part of
  11973.      the installation process.
  11974. `atari/*'
  11975.      Files needed for building `gawk' on an Atari ST.  *Note Installing
  11976.      `gawk' on the Atari ST: Atari Installation, for details.
  11977. `pc/*'
  11978.      Files needed for building `gawk' under MS-DOS and OS/2.  *Note
  11979.      MS-DOS and OS/2 Installation and Compilation: PC Installation, for
  11980.      details.
  11981. `vms/*'
  11982.      Files needed for building `gawk' under VMS.  *Note How to Compile
  11983.      and Install `gawk' on VMS: VMS Installation, for details.
  11984. `test/*'
  11985.      A test suite for `gawk'.  You can use `make check' from the top
  11986.      level `gawk' directory to run your version of `gawk' against the
  11987.      test suite.  If `gawk' successfully passes `make check' then you
  11988.      can be confident of a successful port.
  11989. File: gawk.info,  Node: Unix Installation,  Next: VMS Installation,  Prev: Gawk Distribution,  Up: Installation
  11990. Compiling and Installing `gawk' on Unix
  11991. =======================================
  11992.    Usually, you can compile and install `gawk' by typing only two
  11993. commands.  However, if you do use an unusual system, you may need to
  11994. configure `gawk' for your system yourself.
  11995. * Menu:
  11996. * Quick Installation::          Compiling `gawk' under Unix.
  11997. * Configuration Philosophy::    How it's all supposed to work.
  11998. File: gawk.info,  Node: Quick Installation,  Next: Configuration Philosophy,  Prev: Unix Installation,  Up: Unix Installation
  11999. Compiling `gawk' for Unix
  12000. -------------------------
  12001.    After you have extracted the `gawk' distribution, `cd' to
  12002. `gawk-3.0.3'.  Like most GNU software, `gawk' is configured
  12003. automatically for your Unix system by running the `configure' program.
  12004. This program is a Bourne shell script that was generated automatically
  12005. using GNU `autoconf'.  (The `autoconf' software is described fully
  12006. starting with *Note Introduction: (autoconf)Top.)
  12007.    To configure `gawk', simply run `configure':
  12008.      sh ./configure
  12009.    This produces a `Makefile' and `config.h' tailored to your system.
  12010. The `config.h' file describes various facts about your system.  You may
  12011. wish to edit the `Makefile' to change the `CFLAGS' variable, which
  12012. controls the command line options that are passed to the C compiler
  12013. (such as optimization levels, or compiling for debugging).
  12014.    Alternatively, you can add your own values for most `make'
  12015. variables, such as `CC' and `CFLAGS', on the command line when running
  12016. `configure':
  12017.      CC=cc CFLAGS=-g sh ./configure
  12018. See the file `INSTALL' in the `gawk' distribution for all the details.
  12019.    After you have run `configure', and possibly edited the `Makefile',
  12020. type:
  12021.      make
  12022. and shortly thereafter, you should have an executable version of `gawk'.
  12023. That's all there is to it!  (If these steps do not work, please send in
  12024. a bug report; *note Reporting Problems and Bugs: Bugs..)
  12025. File: gawk.info,  Node: Configuration Philosophy,  Prev: Quick Installation,  Up: Unix Installation
  12026. The Configuration Process
  12027. -------------------------
  12028.    (This section is of interest only if you know something about using
  12029. the C language and the Unix operating system.)
  12030.    The source code for `gawk' generally attempts to adhere to formal
  12031. standards wherever possible.  This means that `gawk' uses library
  12032. routines that are specified by the ANSI C standard and by the POSIX
  12033. operating system interface standard.  When using an ANSI C compiler,
  12034. function prototypes are used to help improve the compile-time checking.
  12035.    Many Unix systems do not support all of either the ANSI or the POSIX
  12036. standards.  The `missing' subdirectory in the `gawk' distribution
  12037. contains replacement versions of those subroutines that are most likely
  12038. to be missing.
  12039.    The `config.h' file that is created by the `configure' program
  12040. contains definitions that describe features of the particular operating
  12041. system where you are attempting to compile `gawk'.  The three things
  12042. described by this file are what header files are available, so that
  12043. they can be correctly included, what (supposedly) standard functions
  12044. are actually available in your C libraries, and other miscellaneous
  12045. facts about your variant of Unix.  For example, there may not be an
  12046. `st_blksize' element in the `stat' structure.  In this case
  12047. `HAVE_ST_BLKSIZE' would be undefined.
  12048.    It is possible for your C compiler to lie to `configure'. It may do
  12049. so by not exiting with an error when a library function is not
  12050. available.  To get around this, you can edit the file `custom.h'.  Use
  12051. an `#ifdef' that is appropriate for your system, and either `#define'
  12052. any constants that `configure' should have defined but didn't, or
  12053. `#undef' any constants that `configure' defined and should not have.
  12054. `custom.h' is automatically included by `config.h'.
  12055.    It is also possible that the `configure' program generated by
  12056. `autoconf' will not work on your system in some other fashion.  If you
  12057. do have a problem, the file `configure.in' is the input for `autoconf'.
  12058. You may be able to change this file, and generate a new version of
  12059. `configure' that will work on your system.  *Note Reporting Problems
  12060. and Bugs: Bugs, for information on how to report problems in
  12061. configuring `gawk'.  The same mechanism may be used to send in updates
  12062. to `configure.in' and/or `custom.h'.
  12063. File: gawk.info,  Node: VMS Installation,  Next: PC Installation,  Prev: Unix Installation,  Up: Installation
  12064. How to Compile and Install `gawk' on VMS
  12065. ========================================
  12066.    This section describes how to compile and install `gawk' under VMS.
  12067. * Menu:
  12068. * VMS Compilation::             How to compile `gawk' under VMS.
  12069. * VMS Installation Details::    How to install `gawk' under VMS.
  12070. * VMS Running::                 How to run `gawk' under VMS.
  12071. * VMS POSIX::                   Alternate instructions for VMS POSIX.
  12072. File: gawk.info,  Node: VMS Compilation,  Next: VMS Installation Details,  Prev: VMS Installation,  Up: VMS Installation
  12073. Compiling `gawk' on VMS
  12074. -----------------------
  12075.    To compile `gawk' under VMS, there is a `DCL' command procedure that
  12076. will issue all the necessary `CC' and `LINK' commands, and there is
  12077. also a `Makefile' for use with the `MMS' utility.  From the source
  12078. directory, use either
  12079.      $ @[.VMS]VMSBUILD.COM
  12080.      $ MMS/DESCRIPTION=[.VMS]DESCRIP.MMS GAWK
  12081.    Depending upon which C compiler you are using, follow one of the sets
  12082. of instructions in this table:
  12083. VAX C V3.x
  12084.      Use either `vmsbuild.com' or `descrip.mms' as is.  These use
  12085.      `CC/OPTIMIZE=NOLINE', which is essential for Version 3.0.
  12086. VAX C V2.x
  12087.      You must have Version 2.3 or 2.4; older ones won't work.  Edit
  12088.      either `vmsbuild.com' or `descrip.mms' according to the comments
  12089.      in them.  For `vmsbuild.com', this just entails removing two `!'
  12090.      delimiters.  Also edit `config.h' (which is a copy of file
  12091.      `[.config]vms-conf.h') and comment out or delete the two lines
  12092.      `#define __STDC__ 0' and `#define VAXC_BUILTINS' near the end.
  12093. GNU C
  12094.      Edit `vmsbuild.com' or `descrip.mms'; the changes are different
  12095.      from those for VAX C V2.x, but equally straightforward.  No
  12096.      changes to `config.h' should be needed.
  12097. DEC C
  12098.      Edit `vmsbuild.com' or `descrip.mms' according to their comments.
  12099.      No changes to `config.h' should be needed.
  12100.    `gawk' has been tested under VAX/VMS 5.5-1 using VAX C V3.2, GNU C
  12101. 1.40 and 2.3.  It should work without modifications for VMS V4.6 and up.
  12102. File: gawk.info,  Node: VMS Installation Details,  Next: VMS Running,  Prev: VMS Compilation,  Up: VMS Installation
  12103. Installing `gawk' on VMS
  12104. ------------------------
  12105.    To install `gawk', all you need is a "foreign" command, which is a
  12106. `DCL' symbol whose value begins with a dollar sign. For example:
  12107.      $ GAWK :== $disk1:[gnubin]GAWK
  12108. (Substitute the actual location of `gawk.exe' for `$disk1:[gnubin]'.)
  12109. The symbol should be placed in the `login.com' of any user who wishes
  12110. to run `gawk', so that it will be defined every time the user logs on.
  12111. Alternatively, the symbol may be placed in the system-wide
  12112. `sylogin.com' procedure, which will allow all users to run `gawk'.
  12113.    Optionally, the help entry can be loaded into a VMS help library:
  12114.      $ LIBRARY/HELP SYS$HELP:HELPLIB [.VMS]GAWK.HLP
  12115. (You may want to substitute a site-specific help library rather than
  12116. the standard VMS library `HELPLIB'.)  After loading the help text,
  12117.      $ HELP GAWK
  12118. will provide information about both the `gawk' implementation and the
  12119. `awk' programming language.
  12120.    The logical name `AWK_LIBRARY' can designate a default location for
  12121. `awk' program files.  For the `-f' option, if the specified filename
  12122. has no device or directory path information in it, `gawk' will look in
  12123. the current directory first, then in the directory specified by the
  12124. translation of `AWK_LIBRARY' if the file was not found.  If after
  12125. searching in both directories, the file still is not found, then `gawk'
  12126. appends the suffix `.awk' to the filename and the file search will be
  12127. re-tried.  If `AWK_LIBRARY' is not defined, that portion of the file
  12128. search will fail benignly.
  12129. File: gawk.info,  Node: VMS Running,  Next: VMS POSIX,  Prev: VMS Installation Details,  Up: VMS Installation
  12130. Running `gawk' on VMS
  12131. ---------------------
  12132.    Command line parsing and quoting conventions are significantly
  12133. different on VMS, so examples in this Info file or from other sources
  12134. often need minor changes.  They *are* minor though, and all `awk'
  12135. programs should run correctly.
  12136.    Here are a couple of trivial tests:
  12137.      $ gawk -- "BEGIN {print ""Hello, World!""}"
  12138.      $ gawk -"W" version
  12139.      ! could also be -"W version" or "-W version"
  12140. Note that upper-case and mixed-case text must be quoted.
  12141.    The VMS port of `gawk' includes a `DCL'-style interface in addition
  12142. to the original shell-style interface (see the help entry for details).
  12143. One side-effect of dual command line parsing is that if there is only a
  12144. single parameter (as in the quoted string program above), the command
  12145. becomes ambiguous.  To work around this, the normally optional `--'
  12146. flag is required to force Unix style rather than `DCL' parsing.  If any
  12147. other dash-type options (or multiple parameters such as data files to be
  12148. processed) are present, there is no ambiguity and `--' can be omitted.
  12149.    The default search path when looking for `awk' program files
  12150. specified by the `-f' option is `"SYS$DISK:[],AWK_LIBRARY:"'.  The
  12151. logical name `AWKPATH' can be used to override this default.  The format
  12152. of `AWKPATH' is a comma-separated list of directory specifications.
  12153. When defining it, the value should be quoted so that it retains a single
  12154. translation, and not a multi-translation `RMS' searchlist.
  12155. File: gawk.info,  Node: VMS POSIX,  Prev: VMS Running,  Up: VMS Installation
  12156. Building and Using `gawk' on VMS POSIX
  12157. --------------------------------------
  12158.    Ignore the instructions above, although `vms/gawk.hlp' should still
  12159. be made available in a help library.  The source tree should be unpacked
  12160. into a container file subsystem rather than into the ordinary VMS file
  12161. system.  Make sure that the two scripts, `configure' and
  12162. `vms/posix-cc.sh', are executable; use `chmod +x' on them if necessary.
  12163. Then execute the following two commands:
  12164.      psx> CC=vms/posix-cc.sh configure
  12165.      psx> make CC=c89 gawk
  12166. The first command will construct files `config.h' and `Makefile' out of
  12167. templates, using a script to make the C compiler fit `configure''s
  12168. expectations.  The second command will compile and link `gawk' using
  12169. the C compiler directly; ignore any warnings from `make' about being
  12170. unable to redefine `CC'.  `configure' will take a very long time to
  12171. execute, but at least it provides incremental feedback as it runs.
  12172.    This has been tested with VAX/VMS V6.2, VMS POSIX V2.0, and DEC C
  12173. V5.2.
  12174.    Once built, `gawk' will work like any other shell utility.  Unlike
  12175. the normal VMS port of `gawk', no special command line manipulation is
  12176. needed in the VMS POSIX environment.
  12177. File: gawk.info,  Node: PC Installation,  Next: Atari Installation,  Prev: VMS Installation,  Up: Installation
  12178. MS-DOS and OS/2 Installation and Compilation
  12179. ============================================
  12180.    If you have received a binary distribution prepared by the DOS
  12181. maintainers, then `gawk' and the necessary support files will appear
  12182. under the `gnu' directory, with executables in `gnu/bin', libraries in
  12183. `gnu/lib/awk', and manual pages under `gnu/man'.  This is designed for
  12184. easy installation to a `/gnu' directory on your drive, but the files
  12185. can be installed anywhere provided `AWKPATH' is set properly.
  12186. Regardless of the installation directory, the first line of `igawk.cmd'
  12187. and `igawk.bat' (in `gnu/bin') may need to be edited.
  12188.    The binary distribution will contain a separate file describing the
  12189. contents. In particular, it may include more than one version of the
  12190. `gawk' executable. OS/2 binary distributions may have a different
  12191. arrangement, but installation is similar.
  12192.    The OS/2 and MS-DOS versions of `gawk' search for program files as
  12193. described in *Note The `AWKPATH' Environment Variable: AWKPATH Variable.
  12194. However, semicolons (rather than colons) separate elements in the
  12195. `AWKPATH' variable. If `AWKPATH' is not set or is empty, then the
  12196. default search path is `".;c:/lib/awk;c:/gnu/lib/awk"'.
  12197.    An `sh'-like shell (as opposed to `command.com' under MS-DOS or
  12198. `cmd.exe' under OS/2) may be useful for `awk' programming.  Ian
  12199. Stewartson has written an excellent shell for MS-DOS and OS/2, and a
  12200. `ksh' clone and GNU Bash are available for OS/2. The file
  12201. `README_d/README.pc' in the `gawk' distribution contains information on
  12202. these shells. Users of Stewartson's shell on DOS should examine its
  12203. documentation on handling of command-lines. In particular, the setting
  12204. for `gawk' in the shell configuration may need to be changed, and the
  12205. `ignoretype' option may also be of interest.
  12206.    `gawk' can be compiled for MS-DOS and OS/2 using the GNU development
  12207. tools from DJ Delorie (DJGPP, MS-DOS-only) or Eberhard Mattes (EMX,
  12208. MS-DOS and OS/2).  Microsoft C can be used to build 16-bit versions for
  12209. MS-DOS and OS/2.  The file `README_d/README.pc' in the `gawk'
  12210. distribution contains additional notes, and `pc/Makefile' contains
  12211. important notes on compilation options.
  12212.    To build `gawk', copy the files in the `pc' directory (*except* for
  12213. `ChangeLog') to the directory with the rest of the `gawk' sources. The
  12214. `Makefile' contains a configuration section with comments, and may need
  12215. to be edited in order to work with your `make' utility.
  12216.    The `Makefile' contains a number of targets for building various
  12217. MS-DOS and OS/2 versions. A list of targets will be printed if the
  12218. `make' command is given without a target. As an example, to build `gawk'
  12219. using the DJGPP tools, enter `make djgpp'.
  12220.    Using `make' to run the standard tests and to install `gawk'
  12221. requires additional Unix-like tools, including `sh', `sed', and `cp'.
  12222. In order to run the tests, the `test/*.ok' files may need to be
  12223. converted so that they have the usual DOS-style end-of-line markers.
  12224. Most of the tests will work properly with Stewartson's shell along with
  12225. the companion utilities or appropriate GNU utilities.  However, some
  12226. editing of `test/Makefile' is required. It is recommended that the file
  12227. `pc/Makefile.tst' be copied to `test/Makefile' as a replacement.
  12228. Details can be found in `README_d/README.pc'.
  12229. File: gawk.info,  Node: Atari Installation,  Next: Amiga Installation,  Prev: PC Installation,  Up: Installation
  12230. Installing `gawk' on the Atari ST
  12231. =================================
  12232.    There are no substantial differences when installing `gawk' on
  12233. various Atari models.  Compiled `gawk' executables do not require a
  12234. large amount of memory with most `awk' programs and should run on all
  12235. Motorola processor based models (called further ST, even if that is not
  12236. exactly right).
  12237.    In order to use `gawk', you need to have a shell, either text or
  12238. graphics, that does not map all the characters of a command line to
  12239. upper-case.  Maintaining case distinction in option flags is very
  12240. important (*note Command Line Options: Options.).  These days this is
  12241. the default, and it may only be a problem for some very old machines.
  12242. If your system does not preserve the case of option flags, you will
  12243. need to upgrade your tools.  Support for I/O redirection is necessary
  12244. to make it easy to import `awk' programs from other environments.
  12245. Pipes are nice to have, but not vital.
  12246. * Menu:
  12247. * Atari Compiling::           Compiling `gawk' on Atari
  12248. * Atari Using::               Running `gawk' on Atari
  12249. File: gawk.info,  Node: Atari Compiling,  Next: Atari Using,  Prev: Atari Installation,  Up: Atari Installation
  12250. Compiling `gawk' on the Atari ST
  12251. --------------------------------
  12252.    A proper compilation of `gawk' sources when `sizeof(int)' differs
  12253. from `sizeof(void *)' requires an ANSI C compiler. An initial port was
  12254. done with `gcc'.  You may actually prefer executables where `int's are
  12255. four bytes wide, but the other variant works as well.
  12256.    You may need quite a bit of memory when trying to recompile the
  12257. `gawk' sources, as some source files (`regex.c' in particular) are quite
  12258. big.  If you run out of memory compiling such a file, try reducing the
  12259. optimization level for this particular file; this may help.
  12260.    With a reasonable shell (Bash will do), and in particular if you run
  12261. Linux, MiNT or a similar operating system, you have a pretty good
  12262. chance that the `configure' utility will succeed.  Otherwise sample
  12263. versions of `config.h' and `Makefile.st' are given in the `atari'
  12264. subdirectory and can be edited and copied to the corresponding files in
  12265. the main source directory.  Even if `configure' produced something, it
  12266. might be advisable to compare its results with the sample versions and
  12267. possibly make adjustments.
  12268.    Some `gawk' source code fragments depend on a preprocessor define
  12269. `atarist'.  This basically assumes the TOS environment with `gcc'.
  12270. Modify these sections as appropriate if they are not right for your
  12271. environment.  Also see the remarks about `AWKPATH' and `envsep' in
  12272. *Note Running `gawk' on the Atari ST: Atari Using.
  12273.    As shipped, the sample `config.h' claims that the `system' function
  12274. is missing from the libraries, which is not true, and an alternative
  12275. implementation of this function is provided in `atari/system.c'.
  12276. Depending upon your particular combination of shell and operating
  12277. system, you may wish to change the file to indicate that `system' is
  12278. available.
  12279. File: gawk.info,  Node: Atari Using,  Prev: Atari Compiling,  Up: Atari Installation
  12280. Running `gawk' on the Atari ST
  12281. ------------------------------
  12282.    An executable version of `gawk' should be placed, as usual, anywhere
  12283. in your `PATH' where your shell can find it.
  12284.    While executing, `gawk' creates a number of temporary files.  When
  12285. using `gcc' libraries for TOS, `gawk' looks for either of the
  12286. environment variables `TEMP' or `TMPDIR', in that order.  If either one
  12287. is found, its value is assumed to be a directory for temporary files.
  12288. This directory must exist, and if you can spare the memory, it is a
  12289. good idea to put it on a RAM drive.  If neither `TEMP' nor `TMPDIR' are
  12290. found, then `gawk' uses the current directory for its temporary files.
  12291.    The ST version of `gawk' searches for its program files as described
  12292. in *Note The `AWKPATH' Environment Variable: AWKPATH Variable.  The
  12293. default value for the `AWKPATH' variable is taken from `DEFPATH'
  12294. defined in `Makefile'. The sample `gcc'/TOS `Makefile' for the ST in
  12295. the distribution sets `DEFPATH' to `".,c:\lib\awk,c:\gnu\lib\awk"'.
  12296. The search path can be modified by explicitly setting `AWKPATH' to
  12297. whatever you wish.  Note that colons cannot be used on the ST to
  12298. separate elements in the `AWKPATH' variable, since they have another,
  12299. reserved, meaning.  Instead, you must use a comma to separate elements
  12300. in the path.  When recompiling, the separating character can be
  12301. modified by initializing the `envsep' variable in `atari/gawkmisc.atr'
  12302. to another value.
  12303.    Although `awk' allows great flexibility in doing I/O redirections
  12304. from within a program, this facility should be used with care on the ST
  12305. running under TOS.  In some circumstances the OS routines for file
  12306. handle pool processing lose track of certain events, causing the
  12307. computer to crash, and requiring a reboot.  Often a warm reboot is
  12308. sufficient.  Fortunately, this happens infrequently, and in rather
  12309. esoteric situations.  In particular, avoid having one part of an `awk'
  12310. program using `print' statements explicitly redirected to
  12311. `"/dev/stdout"', while other `print' statements use the default
  12312. standard output, and a calling shell has redirected standard output to
  12313. a file.
  12314.    When `gawk' is compiled with the ST version of `gcc' and its usual
  12315. libraries, it will accept both `/' and `\' as path separators.  While
  12316. this is convenient, it should be remembered that this removes one,
  12317. technically valid, character (`/') from your file names, and that it
  12318. may create problems for external programs, called via the `system'
  12319. function, which may not support this convention.  Whenever it is
  12320. possible that a file created by `gawk' will be used by some other
  12321. program, use only backslashes.  Also remember that in `awk',
  12322. backslashes in strings have to be doubled in order to get literal
  12323. backslashes (*note Escape Sequences::.).
  12324. File: gawk.info,  Node: Amiga Installation,  Next: Bugs,  Prev: Atari Installation,  Up: Installation
  12325. Installing `gawk' on an Amiga
  12326. =============================
  12327.    You can install `gawk' on an Amiga system using a Unix emulation
  12328. environment available via anonymous `ftp' from `ftp.ninemoons.com' in
  12329. the directory `pub/ade/current'.  This includes a shell based on
  12330. `pdksh'.  The primary component of this environment is a Unix emulation
  12331. library, `ixemul.lib'.
  12332.    A more complete distribution for the Amiga is available on the Geek
  12333. Gadgets CD-ROM from:
  12334.      CRONUS
  12335.      1840 E. Warner Road #105-265
  12336.      Tempe, AZ 85284  USA
  12337.      US Toll Free: (800) 804-0833
  12338.      Phone: +1-602-491-0442
  12339.      FAX: +1-602-491-0048
  12340.      Email:  `info@ninemoons.com'
  12341.      WWW: `http://www.ninemoons.com'
  12342.      Anonymous `ftp' site: `ftp.ninemoons.com'
  12343.    Once you have the distribution, you can configure `gawk' simply by
  12344. running `configure':
  12345.      configure -v m68k-amigaos
  12346.    Then run `make', and you should be all set!  (If these steps do not
  12347. work, please send in a bug report; *note Reporting Problems and Bugs:
  12348. Bugs..)
  12349. File: gawk.info,  Node: Bugs,  Next: Other Versions,  Prev: Amiga Installation,  Up: Installation
  12350. Reporting Problems and Bugs
  12351. ===========================
  12352.      There is nothing more dangerous than a bored archeologist.
  12353.      The Hitchhiker's Guide to the Galaxy
  12354.    If you have problems with `gawk' or think that you have found a bug,
  12355. please report it to the developers; we cannot promise to do anything
  12356. but we might well want to fix it.
  12357.    Before reporting a bug, make sure you have actually found a real bug.
  12358. Carefully reread the documentation and see if it really says you can do
  12359. what you're trying to do.  If it's not clear whether you should be able
  12360. to do something or not, report that too; it's a bug in the
  12361. documentation!
  12362.    Before reporting a bug or trying to fix it yourself, try to isolate
  12363. it to the smallest possible `awk' program and input data file that
  12364. reproduces the problem.  Then send us the program and data file, some
  12365. idea of what kind of Unix system you're using, and the exact results
  12366. `gawk' gave you.  Also say what you expected to occur; this will help
  12367. us decide whether the problem was really in the documentation.
  12368.    Once you have a precise problem, there are two e-mail addresses you
  12369. can send mail to.
  12370. Internet:
  12371.      `bug-gnu-utils@prep.ai.mit.edu'
  12372. UUCP:
  12373.      `uunet!prep.ai.mit.edu!bug-gnu-utils'
  12374.    Please include the version number of `gawk' you are using.  You can
  12375. get this information with the command `gawk --version'.  You should
  12376. send a carbon copy of your mail to Arnold Robbins, who can be reached
  12377. at `arnold@gnu.ai.mit.edu'.
  12378.    *Important!* Do *not* try to report bugs in `gawk' by posting to the
  12379. Usenet/Internet newsgroup `comp.lang.awk'.  While the `gawk' developers
  12380. do occasionally read this newsgroup, there is no guarantee that we will
  12381. see your posting.  The steps described above are the official,
  12382. recognized ways for reporting bugs.
  12383.    Non-bug suggestions are always welcome as well.  If you have
  12384. questions about things that are unclear in the documentation or are
  12385. just obscure features, ask Arnold Robbins; he will try to help you out,
  12386. although he may not have the time to fix the problem.  You can send him
  12387. electronic mail at the Internet address above.
  12388.    If you find bugs in one of the non-Unix ports of `gawk', please send
  12389. an electronic mail message to the person who maintains that port.  They
  12390. are listed below, and also in the `README' file in the `gawk'
  12391. distribution.  Information in the `README' file should be considered
  12392. authoritative if it conflicts with this Info file.
  12393.    The people maintaining the non-Unix ports of `gawk' are:
  12394. MS-DOS
  12395.      Scott Deifik, `scottd@amgen.com', and Darrel Hankerson,
  12396.      `hankedr@mail.auburn.edu'.
  12397.      Kai Uwe Rommel, `rommel@ars.de'.
  12398.      Pat Rankin, `rankin@eql.caltech.edu'.
  12399. Atari ST
  12400.      Michal Jaegermann, `michal@gortel.phys.ualberta.ca'.
  12401. Amiga
  12402.      Fred Fish, `fnf@ninemoons.com'.
  12403.    If your bug is also reproducible under Unix, please send copies of
  12404. your report to the general GNU bug list, as well as to Arnold Robbins,
  12405. at the addresses listed above.
  12406. File: gawk.info,  Node: Other Versions,  Prev: Bugs,  Up: Installation
  12407. Other Freely Available `awk' Implementations
  12408. ============================================
  12409.      It's kind of fun to put comments like this in your awk code.
  12410.            `// Do C++ comments work? answer: yes! of course'
  12411.      Michael Brennan
  12412.    There are two other freely available `awk' implementations.  This
  12413. section briefly describes where to get them.
  12414. Unix `awk'
  12415.      Brian Kernighan has been able to make his implementation of `awk'
  12416.      freely available.  You can get it via anonymous `ftp' to the host
  12417.      `netlib.att.com'.  Change directory to `/netlib/research'. Use
  12418.      "binary" or "image" mode, and retrieve `awk.bundle.Z'.
  12419.      This is a shell archive that has been compressed with the
  12420.      `compress' utility. It can be uncompressed with either
  12421.      `uncompress' or the GNU `gunzip' utility.
  12422.      This version requires an ANSI C compiler; GCC (the GNU C compiler)
  12423.      works quite nicely.
  12424. `mawk'
  12425.      Michael Brennan has written an independent implementation of `awk',
  12426.      called `mawk'.  It is available under the GPL (*note GNU GENERAL
  12427.      PUBLIC LICENSE: Copying.), just as `gawk' is.
  12428.      You can get it via anonymous `ftp' to the host `ftp.whidbey.net'.
  12429.      Change directory to `/pub/brennan'.  Use "binary" or "image" mode,
  12430.      and retrieve `mawk1.3.3.tar.gz' (or the latest version that is
  12431.      there).
  12432.      `gunzip' may be used to decompress this file. Installation is
  12433.      similar to `gawk''s (*note Compiling and Installing `gawk' on
  12434.      Unix: Unix Installation.).
  12435. File: gawk.info,  Node: Notes,  Next: Glossary,  Prev: Installation,  Up: Top
  12436. Implementation Notes
  12437. ********************
  12438.    This appendix contains information mainly of interest to
  12439. implementors and maintainers of `gawk'.  Everything in it applies
  12440. specifically to `gawk', and not to other implementations.
  12441. * Menu:
  12442. * Compatibility Mode::          How to disable certain `gawk' extensions.
  12443. * Additions::                   Making Additions To `gawk'.
  12444. * Future Extensions::           New features that may be implemented one day.
  12445. * Improvements::                Suggestions for improvements by volunteers.
  12446. File: gawk.info,  Node: Compatibility Mode,  Next: Additions,  Prev: Notes,  Up: Notes
  12447. Downward Compatibility and Debugging
  12448. ====================================
  12449.    *Note Extensions in `gawk' Not in POSIX `awk': POSIX/GNU, for a
  12450. summary of the GNU extensions to the `awk' language and program.  All
  12451. of these features can be turned off by invoking `gawk' with the
  12452. `--traditional' option, or with the `--posix' option.
  12453.    If `gawk' is compiled for debugging with `-DDEBUG', then there is
  12454. one more option available on the command line:
  12455. `-W parsedebug'
  12456. `--parsedebug'
  12457.      Print out the parse stack information as the program is being
  12458.      parsed.
  12459.    This option is intended only for serious `gawk' developers, and not
  12460. for the casual user.  It probably has not even been compiled into your
  12461. version of `gawk', since it slows down execution.
  12462. File: gawk.info,  Node: Additions,  Next: Future Extensions,  Prev: Compatibility Mode,  Up: Notes
  12463. Making Additions to `gawk'
  12464. ==========================
  12465.    If you should find that you wish to enhance `gawk' in a significant
  12466. fashion, you are perfectly free to do so.  That is the point of having
  12467. free software; the source code is available, and you are free to change
  12468. it as you wish (*note GNU GENERAL PUBLIC LICENSE: Copying.).
  12469.    This section discusses the ways you might wish to change `gawk', and
  12470. any considerations you should bear in mind.
  12471. * Menu:
  12472. * Adding Code::             Adding code to the main body of `gawk'.
  12473. * New Ports::               Porting `gawk' to a new operating system.
  12474. File: gawk.info,  Node: Adding Code,  Next: New Ports,  Prev: Additions,  Up: Additions
  12475. Adding New Features
  12476. -------------------
  12477.    You are free to add any new features you like to `gawk'.  However,
  12478. if you want your changes to be incorporated into the `gawk'
  12479. distribution, there are several steps that you need to take in order to
  12480. make it possible for me to include to your changes.
  12481.   1. Get the latest version.  It is much easier for me to integrate
  12482.      changes if they are relative to the most recent distributed
  12483.      version of `gawk'.  If your version of `gawk' is very old, I may
  12484.      not be able to integrate them at all.  *Note Getting the `gawk'
  12485.      Distribution: Getting, for information on getting the latest
  12486.      version of `gawk'.
  12487.   2. See *note : (Version)Top standards, GNU Coding Standards.  This
  12488.      document describes how GNU software should be written. If you
  12489.      haven't read it, please do so, preferably *before* starting to
  12490.      modify `gawk'.  (The `GNU Coding Standards' are available as part
  12491.      of the Autoconf distribution, from the FSF.)
  12492.   3. Use the `gawk' coding style.  The C code for `gawk' follows the
  12493.      instructions in the `GNU Coding Standards', with minor exceptions.
  12494.      The code is formatted using the traditional "K&R" style,
  12495.      particularly as regards the placement of braces and the use of
  12496.      tabs.  In brief, the coding rules for `gawk' are:
  12497.         * Use old style (non-prototype) function headers when defining
  12498.           functions.
  12499.         * Put the name of the function at the beginning of its own line.
  12500.         * Put the return type of the function, even if it is `int', on
  12501.           the line above the line with the name and arguments of the
  12502.           function.
  12503.         * The declarations for the function arguments should not be
  12504.           indented.
  12505.         * Put spaces around parentheses used in control structures
  12506.           (`if', `while', `for', `do', `switch' and `return').
  12507.         * Do not put spaces in front of parentheses used in function
  12508.           calls.
  12509.         * Put spaces around all C operators, and after commas in
  12510.           function calls.
  12511.         * Do not use the comma operator to produce multiple
  12512.           side-effects, except in `for' loop initialization and
  12513.           increment parts, and in macro bodies.
  12514.         * Use real tabs for indenting, not spaces.
  12515.         * Use the "K&R" brace layout style.
  12516.         * Use comparisons against `NULL' and `'\0'' in the conditions of
  12517.           `if', `while' and `for' statements, and in the `case's of
  12518.           `switch' statements, instead of just the plain pointer or
  12519.           character value.
  12520.         * Use the `TRUE', `FALSE', and `NULL' symbolic constants, and
  12521.           the character constant `'\0'' where appropriate, instead of
  12522.           `1' and `0'.
  12523.         * Provide one-line descriptive comments for each function.
  12524.         * Do not use `#elif'. Many older Unix C compilers cannot handle
  12525.           it.
  12526.         * Do not use the `alloca' function for allocating memory off
  12527.           the stack.  Its use causes more portability trouble than the
  12528.           minor benefit of not having to free the storage. Instead, use
  12529.           `malloc' and `free'.
  12530.      If I have to reformat your code to follow the coding style used in
  12531.      `gawk', I may not bother.
  12532.   4. Be prepared to sign the appropriate paperwork.  In order for the
  12533.      FSF to distribute your changes, you must either place those
  12534.      changes in the public domain, and submit a signed statement to that
  12535.      effect, or assign the copyright in your changes to the FSF.  Both
  12536.      of these actions are easy to do, and *many* people have done so
  12537.      already. If you have questions, please contact me (*note Reporting
  12538.      Problems and Bugs: Bugs.), or `gnu@prep.ai.mit.edu'.
  12539.   5. Update the documentation.  Along with your new code, please supply
  12540.      new sections and or chapters for this Info file.  If at all
  12541.      possible, please use real Texinfo, instead of just supplying
  12542.      unformatted ASCII text (although even that is better than no
  12543.      documentation at all).  Conventions to be followed in `Effective
  12544.      AWK Programming' are provided after the `@bye' at the end of the
  12545.      Texinfo source file.  If possible, please update the man page as
  12546.      well.
  12547.      You will also have to sign paperwork for your documentation
  12548.      changes.
  12549.   6. Submit changes as context diffs or unified diffs.  Use `diff -c -r
  12550.      -N' or `diff -u -r -N' to compare the original `gawk' source tree
  12551.      with your version.  (I find context diffs to be more readable, but
  12552.      unified diffs are more compact.) I recommend using the GNU version
  12553.      of `diff'.  Send the output produced by either run of `diff' to me
  12554.      when you submit your changes.  *Note Reporting Problems and Bugs:
  12555.      Bugs, for the electronic mail information.
  12556.      Using this format makes it easy for me to apply your changes to the
  12557.      master version of the `gawk' source code (using `patch').  If I
  12558.      have to apply the changes manually, using a text editor, I may not
  12559.      do so, particularly if there are lots of changes.
  12560.    Although this sounds like a lot of work, please remember that while
  12561. you may write the new code, I have to maintain it and support it, and
  12562. if it isn't possible for me to do that with a minimum of extra work,
  12563. then I probably will not.
  12564. File: gawk.info,  Node: New Ports,  Prev: Adding Code,  Up: Additions
  12565. Porting `gawk' to a New Operating System
  12566. ----------------------------------------
  12567.    If you wish to port `gawk' to a new operating system, there are
  12568. several steps to follow.
  12569.   1. Follow the guidelines in *Note Adding New Features: Adding Code,
  12570.      concerning coding style, submission of diffs, and so on.
  12571.   2. When doing a port, bear in mind that your code must co-exist
  12572.      peacefully with the rest of `gawk', and the other ports. Avoid
  12573.      gratuitous changes to the system-independent parts of the code. If
  12574.      at all possible, avoid sprinkling `#ifdef's just for your port
  12575.      throughout the code.
  12576.      If the changes needed for a particular system affect too much of
  12577.      the code, I probably will not accept them.  In such a case, you
  12578.      will, of course, be able to distribute your changes on your own,
  12579.      as long as you comply with the GPL (*note GNU GENERAL PUBLIC
  12580.      LICENSE: Copying.).
  12581.   3. A number of the files that come with `gawk' are maintained by other
  12582.      people at the Free Software Foundation.  Thus, you should not
  12583.      change them unless it is for a very good reason. I.e. changes are
  12584.      not out of the question, but changes to these files will be
  12585.      scrutinized extra carefully.  The files are `alloca.c',
  12586.      `getopt.h', `getopt.c', `getopt1.c', `regex.h', `regex.c', `dfa.h',
  12587.      `dfa.c', `install-sh', and `mkinstalldirs'.
  12588.   4. Be willing to continue to maintain the port.  Non-Unix operating
  12589.      systems are supported by volunteers who maintain the code needed
  12590.      to compile and run `gawk' on their systems. If no-one volunteers
  12591.      to maintain a port, that port becomes unsupported, and it may be
  12592.      necessary to remove it from the distribution.
  12593.   5. Supply an appropriate `gawkmisc.???' file.  Each port has its own
  12594.      `gawkmisc.???' that implements certain operating system specific
  12595.      functions. This is cleaner than a plethora of `#ifdef's scattered
  12596.      throughout the code.  The `gawkmisc.c' in the main source
  12597.      directory includes the appropriate `gawkmisc.???' file from each
  12598.      subdirectory.  Be sure to update it as well.
  12599.      Each port's `gawkmisc.???' file has a suffix reminiscent of the
  12600.      machine or operating system for the port. For example,
  12601.      `pc/gawkmisc.pc' and `vms/gawkmisc.vms'. The use of separate
  12602.      suffixes, instead of plain `gawkmisc.c', makes it possible to move
  12603.      files from a port's subdirectory into the main subdirectory,
  12604.      without accidentally destroying the real `gawkmisc.c' file.
  12605.      (Currently, this is only an issue for the MS-DOS and OS/2 ports.)
  12606.   6. Supply a `Makefile' and any other C source and header files that
  12607.      are necessary for your operating system.  All your code should be
  12608.      in a separate subdirectory, with a name that is the same as, or
  12609.      reminiscent of, either your operating system or the computer
  12610.      system.  If possible, try to structure things so that it is not
  12611.      necessary to move files out of the subdirectory into the main
  12612.      source directory.  If that is not possible, then be sure to avoid
  12613.      using names for your files that duplicate the names of files in
  12614.      the main source directory.
  12615.   7. Update the documentation.  Please write a section (or sections)
  12616.      for this Info file describing the installation and compilation
  12617.      steps needed to install and/or compile `gawk' for your system.
  12618.   8. Be prepared to sign the appropriate paperwork.  In order for the
  12619.      FSF to distribute your code, you must either place your code in
  12620.      the public domain, and submit a signed statement to that effect,
  12621.      or assign the copyright in your code to the FSF.  Both of these
  12622.      actions are easy to do, and *many* people have done so already. If
  12623.      you have questions, please contact me, or `gnu@prep.ai.mit.edu'.
  12624.    Following these steps will make it much easier to integrate your
  12625. changes into `gawk', and have them co-exist happily with the code for
  12626. other operating systems that is already there.
  12627.    In the code that you supply, and that you maintain, feel free to use
  12628. a coding style and brace layout that suits your taste.
  12629. File: gawk.info,  Node: Future Extensions,  Next: Improvements,  Prev: Additions,  Up: Notes
  12630. Probable Future Extensions
  12631. ==========================
  12632.      AWK is a language similar to PERL, only considerably more elegant.
  12633.      Arnold Robbins
  12634.      
  12635.      Hey!
  12636.      Larry Wall
  12637.    This section briefly lists extensions and possible improvements that
  12638. indicate the directions we are currently considering for `gawk'.  The
  12639. file `FUTURES' in the `gawk' distributions lists these extensions as
  12640. well.
  12641.    This is a list of probable future changes that will be usable by the
  12642. `awk' language programmer.
  12643. Localization
  12644.      The GNU project is starting to support multiple languages.  It
  12645.      will at least be possible to make `gawk' print its warnings and
  12646.      error messages in languages other than English.  It may be
  12647.      possible for `awk' programs to also use the multiple language
  12648.      facilities, separate from `gawk' itself.
  12649. Databases
  12650.      It may be possible to map a GDBM/NDBM/SDBM file into an `awk'
  12651.      array.
  12652. A `PROCINFO' Array
  12653.      The special files that provide process-related information (*note
  12654.      Special File Names in `gawk': Special Files.) may be superseded by
  12655.      a `PROCINFO' array that would provide the same information, in an
  12656.      easier to access fashion.
  12657. More `lint' warnings
  12658.      There are more things that could be checked for portability.
  12659. Control of subprocess environment
  12660.      Changes made in `gawk' to the array `ENVIRON' may be propagated to
  12661.      subprocesses run by `gawk'.
  12662.    This is a list of probable improvements that will make `gawk'
  12663. perform better.
  12664. An Improved Version of `dfa'
  12665.      The `dfa' pattern matcher from GNU `grep' has some problems.
  12666.      Either a new version or a fixed one will deal with some important
  12667.      regexp matching issues.
  12668. Use of GNU `malloc'
  12669.      The GNU version of `malloc' could potentially speed up `gawk',
  12670.      since it relies heavily on the use of dynamic memory allocation.
  12671. Use of the `rx' regexp library
  12672.      The `rx' regular expression library could potentially speed up all
  12673.      regexp operations that require knowing the exact location of
  12674.      matches.  This includes record termination, field and array
  12675.      splitting, and the `sub', `gsub', `gensub' and `match' functions.
  12676. File: gawk.info,  Node: Improvements,  Prev: Future Extensions,  Up: Notes
  12677. Suggestions for Improvements
  12678. ============================
  12679.    Here are some projects that would-be `gawk' hackers might like to
  12680. take on.  They vary in size from a few days to a few weeks of
  12681. programming, depending on which one you choose and how fast a
  12682. programmer you are.  Please send any improvements you write to the
  12683. maintainers at the GNU project.  *Note Adding New Features: Adding Code,
  12684. for guidelines to follow when adding new features to `gawk'.  *Note
  12685. Reporting Problems and Bugs: Bugs, for information on contacting the
  12686. maintainers.
  12687.   1. Compilation of `awk' programs: `gawk' uses a Bison (YACC-like)
  12688.      parser to convert the script given it into a syntax tree; the
  12689.      syntax tree is then executed by a simple recursive evaluator.
  12690.      This method incurs a lot of overhead, since the recursive
  12691.      evaluator performs many procedure calls to do even the simplest
  12692.      things.
  12693.      It should be possible for `gawk' to convert the script's parse tree
  12694.      into a C program which the user would then compile, using the
  12695.      normal C compiler and a special `gawk' library to provide all the
  12696.      needed functions (regexps, fields, associative arrays, type
  12697.      coercion, and so on).
  12698.      An easier possibility might be for an intermediate phase of `awk'
  12699.      to convert the parse tree into a linear byte code form like the
  12700.      one used in GNU Emacs Lisp.  The recursive evaluator would then be
  12701.      replaced by a straight line byte code interpreter that would be
  12702.      intermediate in speed between running a compiled program and doing
  12703.      what `gawk' does now.
  12704.   2. The programs in the test suite could use documenting in this
  12705.      Info file.
  12706.   3. See the `FUTURES' file for more ideas.  Contact us if you would
  12707.      seriously like to tackle any of the items listed there.
  12708. File: gawk.info,  Node: Glossary,  Next: Copying,  Prev: Notes,  Up: Top
  12709. Glossary
  12710. ********
  12711. Action
  12712.      A series of `awk' statements attached to a rule.  If the rule's
  12713.      pattern matches an input record, `awk' executes the rule's action.
  12714.      Actions are always enclosed in curly braces.  *Note Overview of
  12715.      Actions: Action Overview.
  12716. Amazing `awk' Assembler
  12717.      Henry Spencer at the University of Toronto wrote a retargetable
  12718.      assembler completely as `awk' scripts.  It is thousands of lines
  12719.      long, including machine descriptions for several eight-bit
  12720.      microcomputers.  It is a good example of a program that would have
  12721.      been better written in another language.
  12722. Amazingly Workable Formatter (`awf')
  12723.      Henry Spencer at the University of Toronto wrote a formatter that
  12724.      accepts a large subset of the `nroff -ms' and `nroff -man'
  12725.      formatting commands, using `awk' and `sh'.
  12726.      The American National Standards Institute.  This organization
  12727.      produces many standards, among them the standards for the C and
  12728.      C++ programming languages.
  12729. Assignment
  12730.      An `awk' expression that changes the value of some `awk' variable
  12731.      or data object.  An object that you can assign to is called an
  12732.      "lvalue".  The assigned values are called "rvalues".  *Note
  12733.      Assignment Expressions: Assignment Ops.
  12734. `awk' Language
  12735.      The language in which `awk' programs are written.
  12736. `awk' Program
  12737.      An `awk' program consists of a series of "patterns" and "actions",
  12738.      collectively known as "rules".  For each input record given to the
  12739.      program, the program's rules are all processed in turn.  `awk'
  12740.      programs may also contain function definitions.
  12741. `awk' Script
  12742.      Another name for an `awk' program.
  12743.      The GNU version of the standard shell (the Bourne-Again shell).
  12744.      See "Bourne Shell."
  12745.      See "Bulletin Board System."
  12746. Boolean Expression
  12747.      Named after the English mathematician Boole. See "Logical
  12748.      Expression."
  12749. Bourne Shell
  12750.      The standard shell (`/bin/sh') on Unix and Unix-like systems,
  12751.      originally written by Steven R. Bourne.  Many shells (Bash, `ksh',
  12752.      `pdksh', `zsh') are generally upwardly compatible with the Bourne
  12753.      shell.
  12754. Built-in Function
  12755.      The `awk' language provides built-in functions that perform various
  12756.      numerical, time stamp related, and string computations.  Examples
  12757.      are `sqrt' (for the square root of a number) and `substr' (for a
  12758.      substring of a string).  *Note Built-in Functions: Built-in.
  12759. Built-in Variable
  12760.      `ARGC', `ARGIND', `ARGV', `CONVFMT', `ENVIRON', `ERRNO',
  12761.      `FIELDWIDTHS', `FILENAME', `FNR', `FS', `IGNORECASE', `NF', `NR',
  12762.      `OFMT', `OFS', `ORS', `RLENGTH', `RSTART', `RS', `RT', and
  12763.      `SUBSEP', are the variables that have special meaning to `awk'.
  12764.      Changing some of them affects `awk''s running environment.
  12765.      Several of these variables are specific to `gawk'.  *Note Built-in
  12766.      Variables::.
  12767. Braces
  12768.      See "Curly Braces."
  12769. Bulletin Board System
  12770.      A computer system allowing users to log in and read and/or leave
  12771.      messages for other users of the system, much like leaving paper
  12772.      notes on a bulletin board.
  12773.      The system programming language that most GNU software is written
  12774.      in.  The `awk' programming language has C-like syntax, and this
  12775.      Info file points out similarities between `awk' and C when
  12776.      appropriate.
  12777. Character Set
  12778.      The set of numeric codes used by a computer system to represent the
  12779.      characters (letters, numbers, punctuation, etc.) of a particular
  12780.      country or place. The most common character set in use today is
  12781.      ASCII (American Standard Code for Information Interchange).  Many
  12782.      European countries use an extension of ASCII known as ISO-8859-1
  12783.      (ISO Latin-1).
  12784.      A preprocessor for `pic' that reads descriptions of molecules and
  12785.      produces `pic' input for drawing them.  It was written in `awk' by
  12786.      Brian Kernighan and Jon Bentley, and is available from
  12787.      `netlib@research.att.com'.
  12788. Compound Statement
  12789.      A series of `awk' statements, enclosed in curly braces.  Compound
  12790.      statements may be nested.  *Note Control Statements in Actions:
  12791.      Statements.
  12792. Concatenation
  12793.      Concatenating two strings means sticking them together, one after
  12794.      another, giving a new string.  For example, the string `foo'
  12795.      concatenated with the string `bar' gives the string `foobar'.
  12796.      *Note String Concatenation: Concatenation.
  12797. Conditional Expression
  12798.      An expression using the `?:' ternary operator, such as `EXPR1 ?
  12799.      EXPR2 : EXPR3'.  The expression EXPR1 is evaluated; if the result
  12800.      is true, the value of the whole expression is the value of EXPR2,
  12801.      otherwise the value is EXPR3.  In either case, only one of EXPR2
  12802.      and EXPR3 is evaluated.  *Note Conditional Expressions:
  12803.      Conditional Exp.
  12804. Comparison Expression
  12805.      A relation that is either true or false, such as `(a < b)'.
  12806.      Comparison expressions are used in `if', `while', `do', and `for'
  12807.      statements, and in patterns to select which input records to
  12808.      process.  *Note Variable Typing and Comparison Expressions: Typing
  12809.      and Comparison.
  12810. Curly Braces
  12811.      The characters `{' and `}'.  Curly braces are used in `awk' for
  12812.      delimiting actions, compound statements, and function bodies.
  12813. Dark Corner
  12814.      An area in the language where specifications often were (or still
  12815.      are) not clear, leading to unexpected or undesirable behavior.
  12816.      Such areas are marked in this Info file with "(d.c.)" in the text,
  12817.      and are indexed under the heading "dark corner."
  12818. Data Objects
  12819.      These are numbers and strings of characters.  Numbers are
  12820.      converted into strings and vice versa, as needed.  *Note
  12821.      Conversion of Strings and Numbers: Conversion.
  12822. Double Precision
  12823.      An internal representation of numbers that can have fractional
  12824.      parts.  Double precision numbers keep track of more digits than do
  12825.      single precision numbers, but operations on them are more
  12826.      expensive.  This is the way `awk' stores numeric values.  It is
  12827.      the C type `double'.
  12828. Dynamic Regular Expression
  12829.      A dynamic regular expression is a regular expression written as an
  12830.      ordinary expression.  It could be a string constant, such as
  12831.      `"foo"', but it may also be an expression whose value can vary.
  12832.      *Note Using Dynamic Regexps: Computed Regexps.
  12833. Environment
  12834.      A collection of strings, of the form NAME`='VAL, that each program
  12835.      has available to it. Users generally place values into the
  12836.      environment in order to provide information to various programs.
  12837.      Typical examples are the environment variables `HOME' and `PATH'.
  12838. Empty String
  12839.      See "Null String."
  12840. Escape Sequences
  12841.      A special sequence of characters used for describing non-printing
  12842.      characters, such as `\n' for newline, or `\033' for the ASCII ESC
  12843.      (escape) character.  *Note Escape Sequences::.
  12844. Field
  12845.      When `awk' reads an input record, it splits the record into pieces
  12846.      separated by whitespace (or by a separator regexp which you can
  12847.      change by setting the built-in variable `FS').  Such pieces are
  12848.      called fields.  If the pieces are of fixed length, you can use the
  12849.      built-in variable `FIELDWIDTHS' to describe their lengths.  *Note
  12850.      Specifying How Fields are Separated: Field Separators, and also see
  12851.      *Note Reading Fixed-width Data: Constant Size.
  12852. Floating Point Number
  12853.      Often referred to in mathematical terms as a "rational" number,
  12854.      this is just a number that can have a fractional part.  See
  12855.      "Double Precision" and "Single Precision."
  12856. Format
  12857.      Format strings are used to control the appearance of output in the
  12858.      `printf' statement.  Also, data conversions from numbers to strings
  12859.      are controlled by the format string contained in the built-in
  12860.      variable `CONVFMT'.  *Note Format-Control Letters: Control Letters.
  12861. Function
  12862.      A specialized group of statements used to encapsulate general or
  12863.      program-specific tasks.  `awk' has a number of built-in functions,
  12864.      and also allows you to define your own.  *Note Built-in Functions:
  12865.      Built-in, and *Note User-defined Functions: User-defined.
  12866.      See "Free Software Foundation."
  12867. Free Software Foundation
  12868.      A non-profit organization dedicated to the production and
  12869.      distribution of freely distributable software.  It was founded by
  12870.      Richard M. Stallman, the author of the original Emacs editor.  GNU
  12871.      Emacs is the most widely used version of Emacs today.
  12872. `gawk'
  12873.      The GNU implementation of `awk'.
  12874. General Public License
  12875.      This document describes the terms under which `gawk' and its source
  12876.      code may be distributed. (*note GNU GENERAL PUBLIC LICENSE:
  12877.      Copying.)
  12878.      "GNU's not Unix".  An on-going project of the Free Software
  12879.      Foundation to create a complete, freely distributable,
  12880.      POSIX-compliant computing environment.
  12881.      See "General Public License."
  12882. Hexadecimal
  12883.      Base 16 notation, where the digits are `0'-`9' and `A'-`F', with
  12884.      `A' representing 10, `B' representing 11, and so on up to `F' for
  12885.      15.  Hexadecimal numbers are written in C using a leading `0x', to
  12886.      indicate their base.  Thus, `0x12' is 18 (one times 16 plus 2).
  12887.      Abbreviation for "Input/Output," the act of moving data into and/or
  12888.      out of a running program.
  12889. Input Record
  12890.      A single chunk of data read in by `awk'.  Usually, an `awk' input
  12891.      record consists of one line of text.  *Note How Input is Split
  12892.      into Records: Records.
  12893. Integer
  12894.      A whole number, i.e. a number that does not have a fractional part.
  12895. Keyword
  12896.      In the `awk' language, a keyword is a word that has special
  12897.      meaning.  Keywords are reserved and may not be used as variable
  12898.      names.
  12899.      `gawk''s keywords are: `BEGIN', `END', `if', `else', `while',
  12900.      `do...while', `for', `for...in', `break', `continue', `delete',
  12901.      `next', `nextfile', `function', `func', and `exit'.
  12902. Logical Expression
  12903.      An expression using the operators for logic, AND, OR, and NOT,
  12904.      written `&&', `||', and `!' in `awk'. Often called Boolean
  12905.      expressions, after the mathematician who pioneered this kind of
  12906.      mathematical logic.
  12907. Lvalue
  12908.      An expression that can appear on the left side of an assignment
  12909.      operator.  In most languages, lvalues can be variables or array
  12910.      elements.  In `awk', a field designator can also be used as an
  12911.      lvalue.
  12912. Null String
  12913.      A string with no characters in it.  It is represented explicitly in
  12914.      `awk' programs by placing two double-quote characters next to each
  12915.      other (`""').  It can appear in input data by having two successive
  12916.      occurrences of the field separator appear next to each other.
  12917. Number
  12918.      A numeric valued data object.  The `gawk' implementation uses
  12919.      double precision floating point to represent numbers.  Very old
  12920.      `awk' implementations use single precision floating point.
  12921. Octal
  12922.      Base-eight notation, where the digits are `0'-`7'.  Octal numbers
  12923.      are written in C using a leading `0', to indicate their base.
  12924.      Thus, `013' is 11 (one times 8 plus 3).
  12925. Pattern
  12926.      Patterns tell `awk' which input records are interesting to which
  12927.      rules.
  12928.      A pattern is an arbitrary conditional expression against which
  12929.      input is tested.  If the condition is satisfied, the pattern is
  12930.      said to "match" the input record.  A typical pattern might compare
  12931.      the input record against a regular expression.  *Note Pattern
  12932.      Elements: Pattern Overview.
  12933. POSIX
  12934.      The name for a series of standards being developed by the IEEE
  12935.      that specify a Portable Operating System interface.  The "IX"
  12936.      denotes the Unix heritage of these standards.  The main standard
  12937.      of interest for `awk' users is `IEEE Standard for Information
  12938.      Technology, Standard 1003.2-1992, Portable Operating System
  12939.      Interface (POSIX) Part 2: Shell and Utilities'.  Informally, this
  12940.      standard is often referred to as simply "P1003.2."
  12941. Private
  12942.      Variables and/or functions that are meant for use exclusively by
  12943.      library functions, and not for the main `awk' program. Special
  12944.      care must be taken when naming such variables and functions.
  12945.      *Note Naming Library Function Global Variables: Library Names.
  12946. Range (of input lines)
  12947.      A sequence of consecutive lines from the input file.  A pattern
  12948.      can specify ranges of input lines for `awk' to process, or it can
  12949.      specify single lines.  *Note Pattern Elements: Pattern Overview.
  12950. Recursion
  12951.      When a function calls itself, either directly or indirectly.  If
  12952.      this isn't clear, refer to the entry for "recursion."
  12953. Redirection
  12954.      Redirection means performing input from other than the standard
  12955.      input stream, or output to other than the standard output stream.
  12956.      You can redirect the output of the `print' and `printf' statements
  12957.      to a file or a system command, using the `>', `>>', and `|'
  12958.      operators.  You can redirect input to the `getline' statement using
  12959.      the `<' and `|' operators.  *Note Redirecting Output of `print'
  12960.      and `printf': Redirection, and *Note Explicit Input with
  12961.      `getline': Getline.
  12962. Regexp
  12963.      Short for "regular expression".  A regexp is a pattern that
  12964.      denotes a set of strings, possibly an infinite set.  For example,
  12965.      the regexp `R.*xp' matches any string starting with the letter `R'
  12966.      and ending with the letters `xp'.  In `awk', regexps are used in
  12967.      patterns and in conditional expressions.  Regexps may contain
  12968.      escape sequences.  *Note Regular Expressions: Regexp.
  12969. Regular Expression
  12970.      See "regexp."
  12971. Regular Expression Constant
  12972.      A regular expression constant is a regular expression written
  12973.      within slashes, such as `/foo/'.  This regular expression is chosen
  12974.      when you write the `awk' program, and cannot be changed doing its
  12975.      execution.  *Note How to Use Regular Expressions: Regexp Usage.
  12976.      A segment of an `awk' program that specifies how to process single
  12977.      input records.  A rule consists of a "pattern" and an "action".
  12978.      `awk' reads an input record; then, for each rule, if the input
  12979.      record satisfies the rule's pattern, `awk' executes the rule's
  12980.      action.  Otherwise, the rule does nothing for that input record.
  12981. Rvalue
  12982.      A value that can appear on the right side of an assignment
  12983.      operator.  In `awk', essentially every expression has a value.
  12984.      These values are rvalues.
  12985. `sed'
  12986.      See "Stream Editor."
  12987. Short-Circuit
  12988.      The nature of the `awk' logical operators `&&' and `||'.  If the
  12989.      value of the entire expression can be deduced from evaluating just
  12990.      the left-hand side of these operators, the right-hand side will not
  12991.      be evaluated (*note Boolean Expressions: Boolean Ops.).
  12992. Side Effect
  12993.      A side effect occurs when an expression has an effect aside from
  12994.      merely producing a value.  Assignment expressions, increment and
  12995.      decrement expressions and function calls have side effects.  *Note
  12996.      Assignment Expressions: Assignment Ops.
  12997. Single Precision
  12998.      An internal representation of numbers that can have fractional
  12999.      parts.  Single precision numbers keep track of fewer digits than
  13000.      do double precision numbers, but operations on them are less
  13001.      expensive in terms of CPU time.  This is the type used by some
  13002.      very old versions of `awk' to store numeric values.  It is the C
  13003.      type `float'.
  13004. Space
  13005.      The character generated by hitting the space bar on the keyboard.
  13006. Special File
  13007.      A file name interpreted internally by `gawk', instead of being
  13008.      handed directly to the underlying operating system.  For example,
  13009.      `/dev/stderr'.  *Note Special File Names in `gawk': Special Files.
  13010. Stream Editor
  13011.      A program that reads records from an input stream and processes
  13012.      them one or more at a time.  This is in contrast with batch
  13013.      programs, which may expect to read their input files in entirety
  13014.      before starting to do anything, and with interactive programs,
  13015.      which require input from the user.
  13016. String
  13017.      A datum consisting of a sequence of characters, such as `I am a
  13018.      string'.  Constant strings are written with double-quotes in the
  13019.      `awk' language, and may contain escape sequences.  *Note Escape
  13020.      Sequences::.
  13021.      The character generated by hitting the `TAB' key on the keyboard.
  13022.      It usually expands to up to eight spaces upon output.
  13023.      A computer operating system originally developed in the early
  13024.      1970's at AT&T Bell Laboratories.  It initially became popular in
  13025.      universities around the world, and later moved into commercial
  13026.      evnironments as a software development system and network server
  13027.      system. There are many commercial versions of Unix, as well as
  13028.      several work-alike systems whose source code is freely available
  13029.      (such as Linux, NetBSD, and FreeBSD).
  13030. Whitespace
  13031.      A sequence of space, tab, or newline characters occurring inside
  13032.      an input record or a string.
  13033. File: gawk.info,  Node: Copying,  Next: Index,  Prev: Glossary,  Up: Top
  13034. GNU GENERAL PUBLIC LICENSE
  13035. **************************
  13036.                          Version 2, June 1991
  13037.      Copyright (C) 1989, 1991 Free Software Foundation, Inc.
  13038.      59 Temple Place --- Suite 330, Boston, MA 02111-1307, USA
  13039.      
  13040.      Everyone is permitted to copy and distribute verbatim copies
  13041.      of this license document, but changing it is not allowed.
  13042. Preamble
  13043. ========
  13044.    The licenses for most software are designed to take away your
  13045. freedom to share and change it.  By contrast, the GNU General Public
  13046. License is intended to guarantee your freedom to share and change free
  13047. software--to make sure the software is free for all its users.  This
  13048. General Public License applies to most of the Free Software
  13049. Foundation's software and to any other program whose authors commit to
  13050. using it.  (Some other Free Software Foundation software is covered by
  13051. the GNU Library General Public License instead.)  You can apply it to
  13052. your programs, too.
  13053.    When we speak of free software, we are referring to freedom, not
  13054. price.  Our General Public Licenses are designed to make sure that you
  13055. have the freedom to distribute copies of free software (and charge for
  13056. this service if you wish), that you receive source code or can get it
  13057. if you want it, that you can change the software or use pieces of it in
  13058. new free programs; and that you know you can do these things.
  13059.    To protect your rights, we need to make restrictions that forbid
  13060. anyone to deny you these rights or to ask you to surrender the rights.
  13061. These restrictions translate to certain responsibilities for you if you
  13062. distribute copies of the software, or if you modify it.
  13063.    For example, if you distribute copies of such a program, whether
  13064. gratis or for a fee, you must give the recipients all the rights that
  13065. you have.  You must make sure that they, too, receive or can get the
  13066. source code.  And you must show them these terms so they know their
  13067. rights.
  13068.    We protect your rights with two steps: (1) copyright the software,
  13069. and (2) offer you this license which gives you legal permission to copy,
  13070. distribute and/or modify the software.
  13071.    Also, for each author's protection and ours, we want to make certain
  13072. that everyone understands that there is no warranty for this free
  13073. software.  If the software is modified by someone else and passed on, we
  13074. want its recipients to know that what they have is not the original, so
  13075. that any problems introduced by others will not reflect on the original
  13076. authors' reputations.
  13077.    Finally, any free program is threatened constantly by software
  13078. patents.  We wish to avoid the danger that redistributors of a free
  13079. program will individually obtain patent licenses, in effect making the
  13080. program proprietary.  To prevent this, we have made it clear that any
  13081. patent must be licensed for everyone's free use or not licensed at all.
  13082.    The precise terms and conditions for copying, distribution and
  13083. modification follow.
  13084.     TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
  13085.   0. This License applies to any program or other work which contains a
  13086.      notice placed by the copyright holder saying it may be distributed
  13087.      under the terms of this General Public License.  The "Program",
  13088.      below, refers to any such program or work, and a "work based on
  13089.      the Program" means either the Program or any derivative work under
  13090.      copyright law: that is to say, a work containing the Program or a
  13091.      portion of it, either verbatim or with modifications and/or
  13092.      translated into another language.  (Hereinafter, translation is
  13093.      included without limitation in the term "modification".)  Each
  13094.      licensee is addressed as "you".
  13095.      Activities other than copying, distribution and modification are
  13096.      not covered by this License; they are outside its scope.  The act
  13097.      of running the Program is not restricted, and the output from the
  13098.      Program is covered only if its contents constitute a work based on
  13099.      the Program (independent of having been made by running the
  13100.      Program).  Whether that is true depends on what the Program does.
  13101.   1. You may copy and distribute verbatim copies of the Program's
  13102.      source code as you receive it, in any medium, provided that you
  13103.      conspicuously and appropriately publish on each copy an appropriate
  13104.      copyright notice and disclaimer of warranty; keep intact all the
  13105.      notices that refer to this License and to the absence of any
  13106.      warranty; and give any other recipients of the Program a copy of
  13107.      this License along with the Program.
  13108.      You may charge a fee for the physical act of transferring a copy,
  13109.      and you may at your option offer warranty protection in exchange
  13110.      for a fee.
  13111.   2. You may modify your copy or copies of the Program or any portion
  13112.      of it, thus forming a work based on the Program, and copy and
  13113.      distribute such modifications or work under the terms of Section 1
  13114.      above, provided that you also meet all of these conditions:
  13115.        a. You must cause the modified files to carry prominent notices
  13116.           stating that you changed the files and the date of any change.
  13117.        b. You must cause any work that you distribute or publish, that
  13118.           in whole or in part contains or is derived from the Program
  13119.           or any part thereof, to be licensed as a whole at no charge
  13120.           to all third parties under the terms of this License.
  13121.        c. If the modified program normally reads commands interactively
  13122.           when run, you must cause it, when started running for such
  13123.           interactive use in the most ordinary way, to print or display
  13124.           an announcement including an appropriate copyright notice and
  13125.           a notice that there is no warranty (or else, saying that you
  13126.           provide a warranty) and that users may redistribute the
  13127.           program under these conditions, and telling the user how to
  13128.           view a copy of this License.  (Exception: if the Program
  13129.           itself is interactive but does not normally print such an
  13130.           announcement, your work based on the Program is not required
  13131.           to print an announcement.)
  13132.      These requirements apply to the modified work as a whole.  If
  13133.      identifiable sections of that work are not derived from the
  13134.      Program, and can be reasonably considered independent and separate
  13135.      works in themselves, then this License, and its terms, do not
  13136.      apply to those sections when you distribute them as separate
  13137.      works.  But when you distribute the same sections as part of a
  13138.      whole which is a work based on the Program, the distribution of
  13139.      the whole must be on the terms of this License, whose permissions
  13140.      for other licensees extend to the entire whole, and thus to each
  13141.      and every part regardless of who wrote it.
  13142.      Thus, it is not the intent of this section to claim rights or
  13143.      contest your rights to work written entirely by you; rather, the
  13144.      intent is to exercise the right to control the distribution of
  13145.      derivative or collective works based on the Program.
  13146.      In addition, mere aggregation of another work not based on the
  13147.      Program with the Program (or with a work based on the Program) on
  13148.      a volume of a storage or distribution medium does not bring the
  13149.      other work under the scope of this License.
  13150.   3. You may copy and distribute the Program (or a work based on it,
  13151.      under Section 2) in object code or executable form under the terms
  13152.      of Sections 1 and 2 above provided that you also do one of the
  13153.      following:
  13154.        a. Accompany it with the complete corresponding machine-readable
  13155.           source code, which must be distributed under the terms of
  13156.           Sections 1 and 2 above on a medium customarily used for
  13157.           software interchange; or,
  13158.        b. Accompany it with a written offer, valid for at least three
  13159.           years, to give any third party, for a charge no more than your
  13160.           cost of physically performing source distribution, a complete
  13161.           machine-readable copy of the corresponding source code, to be
  13162.           distributed under the terms of Sections 1 and 2 above on a
  13163.           medium customarily used for software interchange; or,
  13164.        c. Accompany it with the information you received as to the offer
  13165.           to distribute corresponding source code.  (This alternative is
  13166.           allowed only for non-commercial distribution and only if you
  13167.           received the program in object code or executable form with
  13168.           such an offer, in accord with Subsection b above.)
  13169.      The source code for a work means the preferred form of the work for
  13170.      making modifications to it.  For an executable work, complete
  13171.      source code means all the source code for all modules it contains,
  13172.      plus any associated interface definition files, plus the scripts
  13173.      used to control compilation and installation of the executable.
  13174.      However, as a special exception, the source code distributed need
  13175.      not include anything that is normally distributed (in either
  13176.      source or binary form) with the major components (compiler,
  13177.      kernel, and so on) of the operating system on which the executable
  13178.      runs, unless that component itself accompanies the executable.
  13179.      If distribution of executable or object code is made by offering
  13180.      access to copy from a designated place, then offering equivalent
  13181.      access to copy the source code from the same place counts as
  13182.      distribution of the source code, even though third parties are not
  13183.      compelled to copy the source along with the object code.
  13184.   4. You may not copy, modify, sublicense, or distribute the Program
  13185.      except as expressly provided under this License.  Any attempt
  13186.      otherwise to copy, modify, sublicense or distribute the Program is
  13187.      void, and will automatically terminate your rights under this
  13188.      License.  However, parties who have received copies, or rights,
  13189.      from you under this License will not have their licenses
  13190.      terminated so long as such parties remain in full compliance.
  13191.   5. You are not required to accept this License, since you have not
  13192.      signed it.  However, nothing else grants you permission to modify
  13193.      or distribute the Program or its derivative works.  These actions
  13194.      are prohibited by law if you do not accept this License.
  13195.      Therefore, by modifying or distributing the Program (or any work
  13196.      based on the Program), you indicate your acceptance of this
  13197.      License to do so, and all its terms and conditions for copying,
  13198.      distributing or modifying the Program or works based on it.
  13199.   6. Each time you redistribute the Program (or any work based on the
  13200.      Program), the recipient automatically receives a license from the
  13201.      original licensor to copy, distribute or modify the Program
  13202.      subject to these terms and conditions.  You may not impose any
  13203.      further restrictions on the recipients' exercise of the rights
  13204.      granted herein.  You are not responsible for enforcing compliance
  13205.      by third parties to this License.
  13206.   7. If, as a consequence of a court judgment or allegation of patent
  13207.      infringement or for any other reason (not limited to patent
  13208.      issues), conditions are imposed on you (whether by court order,
  13209.      agreement or otherwise) that contradict the conditions of this
  13210.      License, they do not excuse you from the conditions of this
  13211.      License.  If you cannot distribute so as to satisfy simultaneously
  13212.      your obligations under this License and any other pertinent
  13213.      obligations, then as a consequence you may not distribute the
  13214.      Program at all.  For example, if a patent license would not permit
  13215.      royalty-free redistribution of the Program by all those who
  13216.      receive copies directly or indirectly through you, then the only
  13217.      way you could satisfy both it and this License would be to refrain
  13218.      entirely from distribution of the Program.
  13219.      If any portion of this section is held invalid or unenforceable
  13220.      under any particular circumstance, the balance of the section is
  13221.      intended to apply and the section as a whole is intended to apply
  13222.      in other circumstances.
  13223.      It is not the purpose of this section to induce you to infringe any
  13224.      patents or other property right claims or to contest validity of
  13225.      any such claims; this section has the sole purpose of protecting
  13226.      the integrity of the free software distribution system, which is
  13227.      implemented by public license practices.  Many people have made
  13228.      generous contributions to the wide range of software distributed
  13229.      through that system in reliance on consistent application of that
  13230.      system; it is up to the author/donor to decide if he or she is
  13231.      willing to distribute software through any other system and a
  13232.      licensee cannot impose that choice.
  13233.      This section is intended to make thoroughly clear what is believed
  13234.      to be a consequence of the rest of this License.
  13235.   8. If the distribution and/or use of the Program is restricted in
  13236.      certain countries either by patents or by copyrighted interfaces,
  13237.      the original copyright holder who places the Program under this
  13238.      License may add an explicit geographical distribution limitation
  13239.      excluding those countries, so that distribution is permitted only
  13240.      in or among countries not thus excluded.  In such case, this
  13241.      License incorporates the limitation as if written in the body of
  13242.      this License.
  13243.   9. The Free Software Foundation may publish revised and/or new
  13244.      versions of the General Public License from time to time.  Such
  13245.      new versions will be similar in spirit to the present version, but
  13246.      may differ in detail to address new problems or concerns.
  13247.      Each version is given a distinguishing version number.  If the
  13248.      Program specifies a version number of this License which applies
  13249.      to it and "any later version", you have the option of following
  13250.      the terms and conditions either of that version or of any later
  13251.      version published by the Free Software Foundation.  If the Program
  13252.      does not specify a version number of this License, you may choose
  13253.      any version ever published by the Free Software Foundation.
  13254.  10. If you wish to incorporate parts of the Program into other free
  13255.      programs whose distribution conditions are different, write to the
  13256.      author to ask for permission.  For software which is copyrighted
  13257.      by the Free Software Foundation, write to the Free Software
  13258.      Foundation; we sometimes make exceptions for this.  Our decision
  13259.      will be guided by the two goals of preserving the free status of
  13260.      all derivatives of our free software and of promoting the sharing
  13261.      and reuse of software generally.
  13262.                                 NO WARRANTY
  13263.  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
  13264.      WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
  13265.      LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  13266.      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
  13267.      WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT
  13268.      NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13269.      FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE
  13270.      QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
  13271.      PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY
  13272.      SERVICING, REPAIR OR CORRECTION.
  13273.  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
  13274.      WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
  13275.      MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
  13276.      LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
  13277.      INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
  13278.      INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  13279.      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
  13280.      OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY
  13281.      OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
  13282.      ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  13283.                       END OF TERMS AND CONDITIONS
  13284. How to Apply These Terms to Your New Programs
  13285. =============================================
  13286.    If you develop a new program, and you want it to be of the greatest
  13287. possible use to the public, the best way to achieve this is to make it
  13288. free software which everyone can redistribute and change under these
  13289. terms.
  13290.    To do so, attach the following notices to the program.  It is safest
  13291. to attach them to the start of each source file to most effectively
  13292. convey the exclusion of warranty; and each file should have at least
  13293. the "copyright" line and a pointer to where the full notice is found.
  13294.      ONE LINE TO GIVE THE PROGRAM'S NAME AND AN IDEA OF WHAT IT DOES.
  13295.      Copyright (C) 19YY  NAME OF AUTHOR
  13296.      
  13297.      This program is free software; you can redistribute it and/or
  13298.      modify it under the terms of the GNU General Public License
  13299.      as published by the Free Software Foundation; either version 2
  13300.      of the License, or (at your option) any later version.
  13301.      
  13302.      This program is distributed in the hope that it will be useful,
  13303.      but WITHOUT ANY WARRANTY; without even the implied warranty of
  13304.      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13305.      GNU General Public License for more details.
  13306.      
  13307.      You should have received a copy of the GNU General Public License
  13308.      along with this program; if not, write to the Free Software
  13309.      Foundation, Inc., 59 Temple Place --- Suite 330, Boston, MA 02111-1307, USA.
  13310.    Also add information on how to contact you by electronic and paper
  13311. mail.
  13312.    If the program is interactive, make it output a short notice like
  13313. this when it starts in an interactive mode:
  13314.      Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
  13315.      Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
  13316.      type `show w'.  This is free software, and you are welcome
  13317.      to redistribute it under certain conditions; type `show c'
  13318.      for details.
  13319.    The hypothetical commands `show w' and `show c' should show the
  13320. appropriate parts of the General Public License.  Of course, the
  13321. commands you use may be called something other than `show w' and `show
  13322. c'; they could even be mouse-clicks or menu items--whatever suits your
  13323. program.
  13324.    You should also get your employer (if you work as a programmer) or
  13325. your school, if any, to sign a "copyright disclaimer" for the program,
  13326. if necessary.  Here is a sample; alter the names:
  13327.      Yoyodyne, Inc., hereby disclaims all copyright
  13328.      interest in the program `Gnomovision'
  13329.      (which makes passes at compilers) written
  13330.      by James Hacker.
  13331.      
  13332.      SIGNATURE OF TY COON, 1 April 1989
  13333.      Ty Coon, President of Vice
  13334.    This General Public License does not permit incorporating your
  13335. program into proprietary programs.  If your program is a subroutine
  13336. library, you may consider it more useful to permit linking proprietary
  13337. applications with the library.  If this is what you want to do, use the
  13338. GNU Library General Public License instead of this License.
  13339. File: gawk.info,  Node: Index,  Prev: Copying,  Up: Top
  13340. Index
  13341. *****
  13342. * Menu:
  13343. * ! operator:                            Boolean Ops.
  13344. * != operator:                           Typing and Comparison.
  13345. * !~ operator <1>:                       Regexp Constants.
  13346. * !~ operator <2>:                       Typing and Comparison.
  13347. * !~ operator <3>:                       Regexp Usage.
  13348. * !~ operator <4>:                       Case-sensitivity.
  13349. * !~ operator:                           Computed Regexps.
  13350. * # (comment):                           Comments.
  13351. * #! (executable scripts):               Executable Scripts.
  13352. * $ (field operator):                    Fields.
  13353. * && operator:                           Boolean Ops.
  13354. * --assign option:                       Options.
  13355. * --compat option:                       Options.
  13356. * --copyleft option:                     Options.
  13357. * --copyright option:                    Options.
  13358. * --field-separator option:              Options.
  13359. * --file option:                         Options.
  13360. * --help option:                         Options.
  13361. * --lint option:                         Options.
  13362. * --lint-old option:                     Options.
  13363. * --posix option:                        Options.
  13364. * --source option:                       Options.
  13365. * --traditional option:                  Options.
  13366. * --usage option:                        Options.
  13367. * --version option:                      Options.
  13368. * -f option:                             Long.
  13369. * -F option <1>:                         Command Line Field Separator.
  13370. * -F option:                             Options.
  13371. * -f option:                             Options.
  13372. * -v option:                             Options.
  13373. * -W option:                             Options.
  13374. * /dev/fd:                               Special Files.
  13375. * /dev/pgrpid:                           Special Files.
  13376. * /dev/pid:                              Special Files.
  13377. * /dev/ppid:                             Special Files.
  13378. * /dev/stderr:                           Special Files.
  13379. * /dev/stdin:                            Special Files.
  13380. * /dev/stdout:                           Special Files.
  13381. * /dev/user <1>:                         Special Files.
  13382. * /dev/user:                             Passwd Functions.
  13383. * < operator:                            Typing and Comparison.
  13384. * <= operator:                           Typing and Comparison.
  13385. * == operator:                           Typing and Comparison.
  13386. * > operator:                            Typing and Comparison.
  13387. * >= operator:                           Typing and Comparison.
  13388. * \' regexp operator:                    GNU Regexp Operators.
  13389. * \< regexp operator:                    GNU Regexp Operators.
  13390. * \> regexp operator:                    GNU Regexp Operators.
  13391. * \` regexp operator:                    GNU Regexp Operators.
  13392. * \B regexp operator:                    GNU Regexp Operators.
  13393. * \W regexp operator:                    GNU Regexp Operators.
  13394. * \w regexp operator:                    GNU Regexp Operators.
  13395. * \y regexp operator:                    GNU Regexp Operators.
  13396. * _gr_init:                              Group Functions.
  13397. * _pw_init:                              Passwd Functions.
  13398. * _tm_addup:                             Mktime Function.
  13399. * _tm_isleap:                            Mktime Function.
  13400. * accessing fields:                      Fields.
  13401. * account information <1>:               Passwd Functions.
  13402. * account information:                   Group Functions.
  13403. * acronym:                               History.
  13404. * action, curly braces:                  Action Overview.
  13405. * action, default:                       Very Simple.
  13406. * action, definition of:                 Action Overview.
  13407. * action, empty:                         Very Simple.
  13408. * action, separating statements:         Action Overview.
  13409. * adding new features:                   Adding Code.
  13410. * addition:                              Arithmetic Ops.
  13411. * Aho, Alfred:                           History.
  13412. * AI programming, using gawk:            Distribution contents.
  13413. * alarm.awk:                             Alarm Program.
  13414. * amiga:                                 Amiga Installation.
  13415. * anchors in regexps:                    Regexp Operators.
  13416. * and operator:                          Boolean Ops.
  13417. * anonymous ftp <1>:                     Getting.
  13418. * anonymous ftp:                         Other Versions.
  13419. * applications of awk:                   When.
  13420. * ARGC:                                  Auto-set.
  13421. * ARGIND <1>:                            Auto-set.
  13422. * ARGIND:                                Other Arguments.
  13423. * argument processing:                   Getopt Function.
  13424. * arguments in function call:            Function Calls.
  13425. * arguments, command line:               Invoking Gawk.
  13426. * ARGV <1>:                              Auto-set.
  13427. * ARGV:                                  Other Arguments.
  13428. * arithmetic operators:                  Arithmetic Ops.
  13429. * array assignment:                      Assigning Elements.
  13430. * array reference:                       Reference to Elements.
  13431. * Array subscripts and IGNORECASE:       Array Intro.
  13432. * array subscripts, uninitialized variables: Uninitialized Subscripts.
  13433. * arrays:                                Array Intro.
  13434. * arrays, associative:                   Array Intro.
  13435. * arrays, definition of:                 Array Intro.
  13436. * arrays, deleting an element:           Delete.
  13437. * arrays, deleting entire contents:      Delete.
  13438. * arrays, multi-dimensional subscripts:  Multi-dimensional.
  13439. * arrays, presence of elements:          Reference to Elements.
  13440. * arrays, sparse:                        Array Intro.
  13441. * arrays, special for statement:         Scanning an Array.
  13442. * arrays, the in operator:               Reference to Elements.
  13443. * artificial intelligence, using gawk:   Distribution contents.
  13444. * ASCII:                                 Ordinal Functions.
  13445. * assert:                                Assert Function.
  13446. * assert, C version:                     Assert Function.
  13447. * assertions:                            Assert Function.
  13448. * assignment operators:                  Assignment Ops.
  13449. * assignment to fields:                  Changing Fields.
  13450. * associative arrays:                    Array Intro.
  13451. * atan2:                                 Numeric Functions.
  13452. * atari:                                 Atari Installation.
  13453. * automatic initialization:              More Complex.
  13454. * awk language, POSIX version <1>:       OFMT.
  13455. * awk language, POSIX version <2>:       Next Statement.
  13456. * awk language, POSIX version <3>:       Continue Statement.
  13457. * awk language, POSIX version <4>:       Format Modifiers.
  13458. * awk language, POSIX version <5>:       Field Splitting Summary.
  13459. * awk language, POSIX version <6>:       Arithmetic Ops.
  13460. * awk language, POSIX version <7>:       User-modified.
  13461. * awk language, POSIX version <8>:       Precedence.
  13462. * awk language, POSIX version <9>:       Assignment Ops.
  13463. * awk language, POSIX version <10>:      String Functions.
  13464. * awk language, POSIX version <11>:      Regexp Operators.
  13465. * awk language, POSIX version <12>:      Escape Sequences.
  13466. * awk language, POSIX version <13>:      Regexp Operators.
  13467. * awk language, POSIX version <14>:      String Functions.
  13468. * awk language, POSIX version <15>:      Definition Syntax.
  13469. * awk language, POSIX version <16>:      Break Statement.
  13470. * awk language, POSIX version <17>:      Regexp Operators.
  13471. * awk language, POSIX version:           Conversion.
  13472. * awk language, V.4 version <1>:         SVR4.
  13473. * awk language, V.4 version:             Escape Sequences.
  13474. * AWKPATH environment variable:          AWKPATH Variable.
  13475. * awksed:                                Simple Sed.
  13476. * backslash continuation <1>:            Statements/Lines.
  13477. * backslash continuation:                Egrep Program.
  13478. * backslash continuation and comments:   Statements/Lines.
  13479. * backslash continuation in csh <1>:     More Complex.
  13480. * backslash continuation in csh:         Statements/Lines.
  13481. * basic function of awk:                 Getting Started.
  13482. * BBS-list file:                         Sample Data Files.
  13483. * BEGIN special pattern:                 BEGIN/END.
  13484. * beginfile:                             Filetrans Function.
  13485. * body of a loop:                        While Statement.
  13486. * book, using this:                      This Manual.
  13487. * boolean expressions:                   Boolean Ops.
  13488. * boolean operators:                     Boolean Ops.
  13489. * break statement:                       Break Statement.
  13490. * break, outside of loops:               Break Statement.
  13491. * Brennan, Michael <1>:                  Other Versions.
  13492. * Brennan, Michael <2>:                  Delete.
  13493. * Brennan, Michael <3>:                  Other Versions.
  13494. * Brennan, Michael:                      Simple Sed.
  13495. * buffer matching operators:             GNU Regexp Operators.
  13496. * buffering output:                      I/O Functions.
  13497. * buffering, interactive vs. non-interactive: I/O Functions.
  13498. * buffering, non-interactive vs. interactive: I/O Functions.
  13499. * buffers, flushing:                     I/O Functions.
  13500. * bugs, known in gawk:                   Known Bugs.
  13501. * built-in functions:                    Built-in.
  13502. * built-in variables:                    Built-in Variables.
  13503. * built-in variables, convey information: Auto-set.
  13504. * built-in variables, user modifiable:   User-modified.
  13505. * call by reference:                     Function Caveats.
  13506. * call by value:                         Function Caveats.
  13507. * calling a function <1>:                Function Caveats.
  13508. * calling a function:                    Function Calls.
  13509. * case conversion:                       String Functions.
  13510. * case sensitivity:                      Case-sensitivity.
  13511. * changing contents of a field:          Changing Fields.
  13512. * changing the record separator:         Records.
  13513. * character classes:                     Regexp Operators.
  13514. * character encodings:                   Ordinal Functions.
  13515. * character list:                        Regexp Operators.
  13516. * character list, complemented:          Regexp Operators.
  13517. * character sets:                        Ordinal Functions.
  13518. * chr:                                   Ordinal Functions.
  13519. * close <1>:                             I/O Functions.
  13520. * close:                                 Close Files And Pipes.
  13521. * closing input files and pipes:         Close Files And Pipes.
  13522. * closing output files and pipes:        Close Files And Pipes.
  13523. * coding style used in gawk:             Adding Code.
  13524. * collating elements:                    Regexp Operators.
  13525. * collating symbols:                     Regexp Operators.
  13526. * command line:                          Invoking Gawk.
  13527. * command line formats:                  Running gawk.
  13528. * command line, setting FS on:           Command Line Field Separator.
  13529. * comments:                              Comments.
  13530. * comments and backslash continuation:   Statements/Lines.
  13531. * common mistakes <1>:                   Typing and Comparison.
  13532. * common mistakes <2>:                   Print Examples.
  13533. * common mistakes <3>:                   Basic Field Splitting.
  13534. * common mistakes:                       Computed Regexps.
  13535. * comp.lang.awk:                         Bugs.
  13536. * comparison expressions:                Typing and Comparison.
  13537. * comparisons, string vs. regexp:        Typing and Comparison.
  13538. * compatibility mode <1>:                Options.
  13539. * compatibility mode:                    POSIX/GNU.
  13540. * complemented character list:           Regexp Operators.
  13541. * compound statement:                    Statements.
  13542. * computed regular expressions:          Computed Regexps.
  13543. * concatenation:                         Concatenation.
  13544. * conditional expression:                Conditional Exp.
  13545. * configuring gawk:                      Configuration Philosophy.
  13546. * constants, types of:                   Constants.
  13547. * continuation of lines:                 Statements/Lines.
  13548. * continue statement:                    Continue Statement.
  13549. * continue, outside of loops:            Continue Statement.
  13550. * control statement:                     Statements.
  13551. * conversion of case:                    String Functions.
  13552. * conversion of strings and numbers:     Conversion.
  13553. * conversions, during subscripting:      Numeric Array Subscripts.
  13554. * converting dates to timestamps:        Mktime Function.
  13555. * CONVFMT <1>:                           Numeric Array Subscripts.
  13556. * CONVFMT <2>:                           Conversion.
  13557. * CONVFMT:                               User-modified.
  13558. * cos:                                   Numeric Functions.
  13559. * csh, backslash continuation <1>:       More Complex.
  13560. * csh, backslash continuation:           Statements/Lines.
  13561. * curly braces:                          Action Overview.
  13562. * custom.h configuration file:           Configuration Philosophy.
  13563. * cut utility:                           Cut Program.
  13564. * cut.awk:                               Cut Program.
  13565. * d.c., see "dark corner":               This Manual.
  13566. * dark corner <1>:                       Control Letters.
  13567. * dark corner <2>:                       Continue Statement.
  13568. * dark corner <3>:                       Using Constant Regexps.
  13569. * dark corner <4>:                       Single Character Fields.
  13570. * dark corner <5>:                       OFMT.
  13571. * dark corner <6>:                       Auto-set.
  13572. * dark corner <7>:                       Truth Values.
  13573. * dark corner <8>:                       Field Splitting Summary.
  13574. * dark corner <9>:                       Assignment Options.
  13575. * dark corner <10>:                      This Manual.
  13576. * dark corner <11>:                      Escape Sequences.
  13577. * dark corner <12>:                      Format Modifiers.
  13578. * dark corner <13>:                      Break Statement.
  13579. * dark corner <14>:                      Invoking Gawk.
  13580. * dark corner <15>:                      Plain Getline.
  13581. * dark corner <16>:                      Using Constant Regexps.
  13582. * dark corner <17>:                      Getline Summary.
  13583. * dark corner <18>:                      Multiple Line.
  13584. * dark corner <19>:                      String Functions.
  13585. * dark corner <20>:                      Conversion.
  13586. * dark corner <21>:                      Uninitialized Subscripts.
  13587. * dark corner <22>:                      Auto-set.
  13588. * dark corner <23>:                      Records.
  13589. * dark corner <24>:                      Exit Statement.
  13590. * dark corner <25>:                      Other Arguments.
  13591. * dark corner:                           Using BEGIN/END.
  13592. * data-driven languages:                 Getting Started.
  13593. * dates, converting to timestamps:       Mktime Function.
  13594. * decrement operators:                   Increment Ops.
  13595. * default action:                        Very Simple.
  13596. * default pattern:                       Very Simple.
  13597. * defining functions:                    Definition Syntax.
  13598. * Deifik, Scott <1>:                     Bugs.
  13599. * Deifik, Scott:                         Acknowledgements.
  13600. * delete statement:                      Delete.
  13601. * deleting elements of arrays:           Delete.
  13602. * deleting entire arrays:                Delete.
  13603. * deprecated features:                   Obsolete.
  13604. * deprecated options:                    Obsolete.
  13605. * differences between gawk and awk <1>:  Records.
  13606. * differences between gawk and awk <2>:  Scalar Constants.
  13607. * differences between gawk and awk <3>:  Getline Summary.
  13608. * differences between gawk and awk <4>:  ARGC and ARGV.
  13609. * differences between gawk and awk <5>:  Calling Built-in.
  13610. * differences between gawk and awk <6>:  Nextfile Statement.
  13611. * differences between gawk and awk <7>:  AWKPATH Variable.
  13612. * differences between gawk and awk <8>:  Getline Intro.
  13613. * differences between gawk and awk <9>:  Special Files.
  13614. * differences between gawk and awk <10>: Conditional Exp.
  13615. * differences between gawk and awk <11>: Arithmetic Ops.
  13616. * differences between gawk and awk <12>: String Functions.
  13617. * differences between gawk and awk <13>: I/O And BEGIN/END.
  13618. * differences between gawk and awk <14>: Redirection.
  13619. * differences between gawk and awk <15>: Case-sensitivity.
  13620. * differences between gawk and awk <16>: Using Constant Regexps.
  13621. * differences between gawk and awk <17>: Close Files And Pipes.
  13622. * differences between gawk and awk <18>: String Functions.
  13623. * differences between gawk and awk <19>: Close Files And Pipes.
  13624. * differences between gawk and awk <20>: Delete.
  13625. * differences between gawk and awk <21>: Single Character Fields.
  13626. * differences between gawk and awk:      Records.
  13627. * directory search:                      AWKPATH Variable.
  13628. * division:                              Arithmetic Ops.
  13629. * documenting awk programs <1>:          Library Names.
  13630. * documenting awk programs:              Comments.
  13631. * dupword.awk:                           Dupword Program.
  13632. * dynamic regular expressions:           Computed Regexps.
  13633. * EBCDIC:                                Ordinal Functions.
  13634. * egrep <1>:                             One-shot.
  13635. * egrep:                                 Regexp Operators.
  13636. * egrep utility:                         Egrep Program.
  13637. * egrep.awk:                             Egrep Program.
  13638. * element assignment:                    Assigning Elements.
  13639. * element of array:                      Reference to Elements.
  13640. * empty action:                          Very Simple.
  13641. * empty pattern:                         Empty.
  13642. * empty program:                         Invoking Gawk.
  13643. * empty string <1>:                      Truth Values.
  13644. * empty string <2>:                      Conversion.
  13645. * empty string <3>:                      Regexp Field Splitting.
  13646. * empty string:                          Records.
  13647. * END special pattern:                   BEGIN/END.
  13648. * endfile:                               Filetrans Function.
  13649. * endgrent:                              Group Functions.
  13650. * endpwent:                              Passwd Functions.
  13651. * ENVIRON:                               Auto-set.
  13652. * environment variable, AWKPATH:         AWKPATH Variable.
  13653. * environment variable, POSIXLY_CORRECT: Options.
  13654. * equivalence classes:                   Regexp Operators.
  13655. * ERRNO <1>:                             Getline Intro.
  13656. * ERRNO <2>:                             Close Files And Pipes.
  13657. * ERRNO:                                 Auto-set.
  13658. * errors, common <1>:                    Typing and Comparison.
  13659. * errors, common <2>:                    Computed Regexps.
  13660. * errors, common <3>:                    Basic Field Splitting.
  13661. * errors, common:                        Print Examples.
  13662. * escape processing, sub et. al.:        String Functions.
  13663. * escape sequence notation:              Escape Sequences.
  13664. * evaluation, order of:                  Calling Built-in.
  13665. * examining fields:                      Fields.
  13666. * executable scripts:                    Executable Scripts.
  13667. * exit statement:                        Exit Statement.
  13668. * exp:                                   Numeric Functions.
  13669. * explicit input:                        Getline.
  13670. * exponentiation:                        Arithmetic Ops.
  13671. * expression:                            Expressions.
  13672. * expression, assignment:                Assignment Ops.
  13673. * expression, boolean:                   Boolean Ops.
  13674. * expression, comparison:                Typing and Comparison.
  13675. * expression, conditional:               Conditional Exp.
  13676. * expression, matching:                  Typing and Comparison.
  13677. * extract.awk:                           Extract Program.
  13678. * features, adding:                      Adding Code.
  13679. * fflush:                                I/O Functions.
  13680. * field operator $:                      Fields.
  13681. * field separator, choice of:            Basic Field Splitting.
  13682. * field separator, FS:                   Basic Field Splitting.
  13683. * field separator, on command line:      Command Line Field Separator.
  13684. * field, changing contents of:           Changing Fields.
  13685. * fields:                                Fields.
  13686. * fields, separating:                    Basic Field Splitting.
  13687. * FIELDWIDTHS:                           User-modified.
  13688. * file descriptors:                      Special Files.
  13689. * file, awk program:                     Long.
  13690. * FILENAME <1>:                          Reading Files.
  13691. * FILENAME <2>:                          Getline Summary.
  13692. * FILENAME:                              Auto-set.
  13693. * FILENAME, being set by getline:        Getline Summary.
  13694. * Fish, Fred:                            Bugs.
  13695. * flushing buffers:                      I/O Functions.
  13696. * FNR <1>:                               Auto-set.
  13697. * FNR:                                   Records.
  13698. * for (x in ...):                        Scanning an Array.
  13699. * for statement:                         For Statement.
  13700. * format specifier:                      Control Letters.
  13701. * format string:                         Basic Printf.
  13702. * format, numeric output:                OFMT.
  13703. * formatted output:                      Printf.
  13704. * formatted timestamps:                  Gettimeofday Function.
  13705. * Free Software Foundation <1>:          Getting.
  13706. * Free Software Foundation <2>:          Manual History.
  13707. * Free Software Foundation:              Getting.
  13708. * FreeBSD:                               Manual History.
  13709. * Friedl, Jeffrey:                       Acknowledgements.
  13710. * FS <1>:                                Basic Field Splitting.
  13711. * FS:                                    User-modified.
  13712. * ftp, anonymous <1>:                    Getting.
  13713. * ftp, anonymous:                        Other Versions.
  13714. * function call <1>:                     Function Calls.
  13715. * function call:                         Function Caveats.
  13716. * function definition:                   Definition Syntax.
  13717. * function, recursive:                   Definition Syntax.
  13718. * functions, undefined:                  Function Caveats.
  13719. * functions, user-defined:               User-defined.
  13720. * gawk coding style:                     Adding Code.
  13721. * gensub:                                String Functions.
  13722. * getgrent:                              Group Functions.
  13723. * getgrent, C version:                   Group Functions.
  13724. * getgrgid:                              Group Functions.
  13725. * getgrnam:                              Group Functions.
  13726. * getgruser:                             Group Functions.
  13727. * getline:                               Getline.
  13728. * getline, return values:                Getline Intro.
  13729. * getline, setting FILENAME:             Getline Summary.
  13730. * getopt:                                Getopt Function.
  13731. * getopt, C version:                     Getopt Function.
  13732. * getpwent:                              Passwd Functions.
  13733. * getpwent, C version:                   Passwd Functions.
  13734. * getpwnam:                              Passwd Functions.
  13735. * getpwuid:                              Passwd Functions.
  13736. * gettimeofday:                          Gettimeofday Function.
  13737. * getting gawk:                          Getting.
  13738. * GNU Project:                           Manual History.
  13739. * grcat program:                         Group Functions.
  13740. * grcat.c:                               Group Functions.
  13741. * group file:                            Group Functions.
  13742. * group information:                     Group Functions.
  13743. * gsub:                                  String Functions.
  13744. * gsub, third argument of:               String Functions.
  13745. * Hankerson, Darrel <1>:                 Bugs.
  13746. * Hankerson, Darrel:                     Acknowledgements.
  13747. * historical features <1>:               Command Line Field Separator.
  13748. * historical features <2>:               String Functions.
  13749. * historical features <3>:               Break Statement.
  13750. * historical features <4>:               Continue Statement.
  13751. * historical features:                   Historical Features.
  13752. * history of awk:                        History.
  13753. * histsort.awk:                          History Sorting.
  13754. * how awk works:                         Two Rules.
  13755. * Hughes, Phil:                          Acknowledgements.
  13756. * I/O from BEGIN and END:                I/O And BEGIN/END.
  13757. * id utility:                            Id Program.
  13758. * id.awk:                                Id Program.
  13759. * if-else statement:                     If Statement.
  13760. * igawk.sh:                              Igawk Program.
  13761. * IGNORECASE <1>:                        User-modified.
  13762. * IGNORECASE <2>:                        Array Intro.
  13763. * IGNORECASE:                            Case-sensitivity.
  13764. * IGNORECASE and array subscripts:       Array Intro.
  13765. * ignoring case:                         Case-sensitivity.
  13766. * implementation limits <1>:             Getline Summary.
  13767. * implementation limits:                 Redirection.
  13768. * in operator:                           Typing and Comparison.
  13769. * increment operators:                   Increment Ops.
  13770. * index:                                 String Functions.
  13771. * initialization, automatic:             More Complex.
  13772. * input:                                 Reading Files.
  13773. * input file, sample:                    Sample Data Files.
  13774. * input files, skipping:                 Nextfile Function.
  13775. * input pipeline:                        Getline/Pipe.
  13776. * input redirection:                     Getline/File.
  13777. * input, explicit:                       Getline.
  13778. * input, getline command:                Getline.
  13779. * input, multiple line records:          Multiple Line.
  13780. * input, standard:                       Read Terminal.
  13781. * installation, amiga:                   Amiga Installation.
  13782. * installation, atari:                   Atari Installation.
  13783. * installation, MS-DOS and OS/2:         PC Installation.
  13784. * installation, unix:                    Quick Installation.
  13785. * installation, vms:                     VMS Installation.
  13786. * int:                                   Numeric Functions.
  13787. * interaction, awk and other programs:   I/O Functions.
  13788. * interactive buffering vs. non-interactive: I/O Functions.
  13789. * interval expressions:                  Regexp Operators.
  13790. * inventory-shipped file:                Sample Data Files.
  13791. * invocation of gawk:                    Invoking Gawk.
  13792. * ISO 8601:                              Time Functions.
  13793. * ISO 8859-1 <1>:                        Case-sensitivity.
  13794. * ISO 8859-1:                            Glossary.
  13795. * ISO Latin-1 <1>:                       Glossary.
  13796. * ISO Latin-1:                           Case-sensitivity.
  13797. * Jaegermann, Michal <1>:                Acknowledgements.
  13798. * Jaegermann, Michal:                    Bugs.
  13799. * join:                                  Join Function.
  13800. * Kernighan, Brian <1>:                  Concatenation.
  13801. * Kernighan, Brian <2>:                  Acknowledgements.
  13802. * Kernighan, Brian <3>:                  Other Versions.
  13803. * Kernighan, Brian <4>:                  BTL.
  13804. * Kernighan, Brian:                      History.
  13805. * known bugs:                            Known Bugs.
  13806. * labels.awk:                            Labels Program.
  13807. * language, awk:                         This Manual.
  13808. * language, data-driven:                 Getting Started.
  13809. * language, procedural:                  Getting Started.
  13810. * leftmost longest match <1>:            Multiple Line.
  13811. * leftmost longest match:                Leftmost Longest.
  13812. * length:                                String Functions.
  13813. * limitations <1>:                       Redirection.
  13814. * limitations:                           Getline Summary.
  13815. * line break:                            Statements/Lines.
  13816. * line continuation <1>:                 Boolean Ops.
  13817. * line continuation <2>:                 Print Examples.
  13818. * line continuation <3>:                 Statements/Lines.
  13819. * line continuation:                     Conditional Exp.
  13820. * Linux <1>:                             Manual History.
  13821. * Linux:                                 Atari Compiling.
  13822. * locale, definition of:                 Time Functions.
  13823. * log:                                   Numeric Functions.
  13824. * logical false:                         Truth Values.
  13825. * logical operations:                    Boolean Ops.
  13826. * logical true:                          Truth Values.
  13827. * login information:                     Passwd Functions.
  13828. * long options:                          Invoking Gawk.
  13829. * loop:                                  While Statement.
  13830. * loops, exiting:                        Break Statement.
  13831. * lvalue:                                Assignment Ops.
  13832. * mark parity:                           Ordinal Functions.
  13833. * match:                                 String Functions.
  13834. * matching ranges of lines:              Ranges.
  13835. * matching, leftmost longest <1>:        Multiple Line.
  13836. * matching, leftmost longest:            Leftmost Longest.
  13837. * mawk:                                  Other Versions.
  13838. * merging strings:                       Join Function.
  13839. * metacharacters:                        Regexp Operators.
  13840. * mistakes, common <1>:                  Basic Field Splitting.
  13841. * mistakes, common <2>:                  Typing and Comparison.
  13842. * mistakes, common <3>:                  Computed Regexps.
  13843. * mistakes, common:                      Print Examples.
  13844. * mktime:                                Mktime Function.
  13845. * modifiers (in format specifiers):      Format Modifiers.
  13846. * multi-dimensional subscripts:          Multi-dimensional.
  13847. * multiple line records:                 Multiple Line.
  13848. * multiple passes over data:             Other Arguments.
  13849. * multiple statements on one line:       Statements/Lines.
  13850. * multiplication:                        Arithmetic Ops.
  13851. * names, use of:                         Definition Syntax.
  13852. * namespace issues in awk:               Library Names.
  13853. * namespaces:                            Definition Syntax.
  13854. * NetBSD:                                Manual History.
  13855. * new awk:                               History.
  13856. * new awk vs. old awk:                   Names.
  13857. * newline:                               Statements/Lines.
  13858. * next file statement:                   Nextfile Statement.
  13859. * next statement:                        Next Statement.
  13860. * next, inside a user-defined function:  Next Statement.
  13861. * nextfile function:                     Nextfile Function.
  13862. * nextfile statement:                    Nextfile Statement.
  13863. * NF <1>:                                Fields.
  13864. * NF:                                    Auto-set.
  13865. * non-interactive buffering vs. interactive: I/O Functions.
  13866. * not operator:                          Boolean Ops.
  13867. * NR <1>:                                Auto-set.
  13868. * NR:                                    Records.
  13869. * null string <1>:                       Conversion.
  13870. * null string <2>:                       Regexp Field Splitting.
  13871. * null string:                           Truth Values.
  13872. * null string, as array subscript:       Uninitialized Subscripts.
  13873. * number of fields, NF:                  Fields.
  13874. * number of records, NR, FNR:            Records.
  13875. * numbers, used as subscripts:           Numeric Array Subscripts.
  13876. * numeric character values:              Ordinal Functions.
  13877. * numeric constant:                      Scalar Constants.
  13878. * numeric output format:                 OFMT.
  13879. * numeric string:                        Typing and Comparison.
  13880. * numeric value:                         Scalar Constants.
  13881. * obsolete features:                     Obsolete.
  13882. * obsolete options:                      Obsolete.
  13883. * OFMT <1>:                              User-modified.
  13884. * OFMT <2>:                              OFMT.
  13885. * OFMT:                                  Conversion.
  13886. * OFS <1>:                               Output Separators.
  13887. * OFS:                                   User-modified.
  13888. * old awk:                               History.
  13889. * old awk vs. new awk:                   Names.
  13890. * one-liners:                            One-liners.
  13891. * operations, logical:                   Boolean Ops.
  13892. * operator precedence:                   Precedence.
  13893. * operators, arithmetic:                 Arithmetic Ops.
  13894. * operators, assignment:                 Assignment Ops.
  13895. * operators, boolean:                    Boolean Ops.
  13896. * operators, decrement:                  Increment Ops.
  13897. * operators, increment:                  Increment Ops.
  13898. * operators, regexp matching:            Regexp Usage.
  13899. * operators, relational:                 Typing and Comparison.
  13900. * operators, short-circuit:              Boolean Ops.
  13901. * operators, string:                     Concatenation.
  13902. * operators, string-matching:            Regexp Usage.
  13903. * options, command line:                 Invoking Gawk.
  13904. * options, long:                         Invoking Gawk.
  13905. * or operator:                           Boolean Ops.
  13906. * ord:                                   Ordinal Functions.
  13907. * order of evaluation:                   Calling Built-in.
  13908. * ORS <1>:                               Output Separators.
  13909. * ORS:                                   User-modified.
  13910. * output:                                Printing.
  13911. * output field separator, OFS:           Output Separators.
  13912. * output format specifier, OFMT:         OFMT.
  13913. * output record separator, ORS:          Output Separators.
  13914. * output redirection:                    Redirection.
  13915. * output, buffering:                     I/O Functions.
  13916. * output, formatted:                     Printf.
  13917. * output, piping:                        Redirection.
  13918. * passes, multiple:                      Other Arguments.
  13919. * password file:                         Passwd Functions.
  13920. * path, search:                          AWKPATH Variable.
  13921. * pattern, BEGIN:                        BEGIN/END.
  13922. * pattern, default:                      Very Simple.
  13923. * pattern, definition of:                Patterns and Actions.
  13924. * pattern, empty:                        Empty.
  13925. * pattern, END:                          BEGIN/END.
  13926. * pattern, range:                        Ranges.
  13927. * pattern, regular expressions:          Regexp.
  13928. * patterns, types of:                    Kinds of Patterns.
  13929. * per file initialization and clean-up:  Filetrans Function.
  13930. * PERL:                                  Future Extensions.
  13931. * pipeline, input:                       Getline/Pipe.
  13932. * pipes for output:                      Redirection.
  13933. * portability issues <1>:                Delete.
  13934. * portability issues <2>:                Statements/Lines.
  13935. * portability issues <3>:                String Functions.
  13936. * portability issues <4>:                Close Files And Pipes.
  13937. * portability issues <5>:                Definition Syntax.
  13938. * portability issues <6>:                I/O Functions.
  13939. * portability issues <7>:                Portability Notes.
  13940. * portability issues:                    Escape Sequences.
  13941. * porting gawk:                          New Ports.
  13942. * POSIX awk <1>:                         Assignment Ops.
  13943. * POSIX awk <2>:                         Field Splitting Summary.
  13944. * POSIX awk <3>:                         Format Modifiers.
  13945. * POSIX awk <4>:                         String Functions.
  13946. * POSIX awk <5>:                         OFMT.
  13947. * POSIX awk <6>:                         Escape Sequences.
  13948. * POSIX awk <7>:                         Definition Syntax.
  13949. * POSIX awk <8>:                         Arithmetic Ops.
  13950. * POSIX awk <9>:                         Precedence.
  13951. * POSIX awk <10>:                        Conversion.
  13952. * POSIX awk <11>:                        User-modified.
  13953. * POSIX awk <12>:                        Next Statement.
  13954. * POSIX awk <13>:                        Continue Statement.
  13955. * POSIX awk <14>:                        Break Statement.
  13956. * POSIX awk <15>:                        Regexp Operators.
  13957. * POSIX awk <16>:                        String Functions.
  13958. * POSIX awk <17>:                        Precedence.
  13959. * POSIX awk:                             Regexp Operators.
  13960. * POSIX mode:                            Options.
  13961. * POSIXLY_CORRECT environment variable:  Options.
  13962. * precedence:                            Precedence.
  13963. * precedence, regexp operators:          Regexp Operators.
  13964. * print statement:                       Print.
  13965. * printf statement, syntax of:           Basic Printf.
  13966. * printf, format-control characters:     Control Letters.
  13967. * printf, modifiers:                     Format Modifiers.
  13968. * printing:                              Printing.
  13969. * procedural languages:                  Getting Started.
  13970. * process information:                   Special Files.
  13971. * processing arguments:                  Getopt Function.
  13972. * program file:                          Long.
  13973. * program, awk:                          This Manual.
  13974. * program, definition of:                Getting Started.
  13975. * program, self contained:               Executable Scripts.
  13976. * programs, documenting <1>:             Comments.
  13977. * programs, documenting:                 Library Names.
  13978. * pwcat program:                         Passwd Functions.
  13979. * pwcat.c:                               Passwd Functions.
  13980. * quotient:                              Arithmetic Ops.
  13981. * quoting, shell <1>:                    Long.
  13982. * quoting, shell:                        Read Terminal.
  13983. * Rakitzis, Byron:                       History Sorting.
  13984. * rand:                                  Numeric Functions.
  13985. * random numbers, seed of:               Numeric Functions.
  13986. * range pattern:                         Ranges.
  13987. * Rankin, Pat <1>:                       Acknowledgements.
  13988. * Rankin, Pat <2>:                       Bugs.
  13989. * Rankin, Pat:                           Assignment Ops.
  13990. * reading files:                         Reading Files.
  13991. * reading files, getline command:        Getline.
  13992. * reading files, multiple line records:  Multiple Line.
  13993. * record separator, RS:                  Records.
  13994. * record terminator, RT:                 Records.
  13995. * record, definition of:                 Records.
  13996. * records, multiple line:                Multiple Line.
  13997. * recursive function:                    Definition Syntax.
  13998. * redirection of input:                  Getline/File.
  13999. * redirection of output:                 Redirection.
  14000. * reference to array:                    Reference to Elements.
  14001. * regexp:                                Regexp.
  14002. * regexp as expression:                  Typing and Comparison.
  14003. * regexp comparison vs. string comparison: Typing and Comparison.
  14004. * regexp constant:                       Regexp Usage.
  14005. * regexp constants, difference between slashes and quotes: Computed Regexps.
  14006. * regexp match/non-match operators <1>:  Regexp Usage.
  14007. * regexp match/non-match operators:      Typing and Comparison.
  14008. * regexp matching operators:             Regexp Usage.
  14009. * regexp operators:                      Regexp Operators.
  14010. * regexp operators, GNU specific:        GNU Regexp Operators.
  14011. * regexp operators, precedence of:       Regexp Operators.
  14012. * regexp, anchors:                       Regexp Operators.
  14013. * regexp, dynamic:                       Computed Regexps.
  14014. * regexp, effect of command line options: GNU Regexp Operators.
  14015. * regular expression:                    Regexp.
  14016. * regular expression metacharacters:     Regexp Operators.
  14017. * regular expressions as field separators: Basic Field Splitting.
  14018. * regular expressions as patterns:       Regexp.
  14019. * regular expressions as record separators: Records.
  14020. * regular expressions, computed:         Computed Regexps.
  14021. * relational operators:                  Typing and Comparison.
  14022. * remainder:                             Arithmetic Ops.
  14023. * removing elements of arrays:           Delete.
  14024. * return statement:                      Return Statement.
  14025. * RFC-1036:                              Time Functions.
  14026. * RFC-822:                               Time Functions.
  14027. * RLENGTH <1>:                           String Functions.
  14028. * RLENGTH:                               Auto-set.
  14029. * Robbins, Miriam:                       Acknowledgements.
  14030. * Rommel, Kai Uwe <1>:                   Bugs.
  14031. * Rommel, Kai Uwe:                       Acknowledgements.
  14032. * round:                                 Round Function.
  14033. * rounding:                              Round Function.
  14034. * RS <1>:                                User-modified.
  14035. * RS:                                    Records.
  14036. * RSTART <1>:                            String Functions.
  14037. * RSTART:                                Auto-set.
  14038. * RT <1>:                                Records.
  14039. * RT <2>:                                Auto-set.
  14040. * RT:                                    Multiple Line.
  14041. * rule, definition of:                   Getting Started.
  14042. * running awk programs:                  Running gawk.
  14043. * running long programs:                 Long.
  14044. * rvalue:                                Assignment Ops.
  14045. * sample input file:                     Sample Data Files.
  14046. * scanning an array:                     Scanning an Array.
  14047. * script, definition of:                 Getting Started.
  14048. * scripts, executable:                   Executable Scripts.
  14049. * scripts, shell:                        Executable Scripts.
  14050. * search path:                           AWKPATH Variable.
  14051. * search path, for source files:         AWKPATH Variable.
  14052. * sed utility <1>:                       Simple Sed.
  14053. * sed utility <2>:                       Igawk Program.
  14054. * sed utility:                           Field Splitting Summary.
  14055. * seed for random numbers:               Numeric Functions.
  14056. * self contained programs:               Executable Scripts.
  14057. * shell quoting <1>:                     Read Terminal.
  14058. * shell quoting:                         Long.
  14059. * shell scripts:                         Executable Scripts.
  14060. * short-circuit operators:               Boolean Ops.
  14061. * side effect:                           Assignment Ops.
  14062. * simple stream editor:                  Simple Sed.
  14063. * sin:                                   Numeric Functions.
  14064. * single character fields:               Single Character Fields.
  14065. * single quotes, why needed:             One-shot.
  14066. * skipping input files:                  Nextfile Function.
  14067. * skipping lines between markers:        Ranges.
  14068. * sparse arrays:                         Array Intro.
  14069. * split:                                 String Functions.
  14070. * split utility:                         Split Program.
  14071. * split.awk:                             Split Program.
  14072. * sprintf:                               String Functions.
  14073. * sqrt:                                  Numeric Functions.
  14074. * srand:                                 Numeric Functions.
  14075. * Stallman, Richard <1>:                 Acknowledgements.
  14076. * Stallman, Richard:                     Manual History.
  14077. * standard error output:                 Special Files.
  14078. * standard input <1>:                    Special Files.
  14079. * standard input <2>:                    Reading Files.
  14080. * standard input:                        Read Terminal.
  14081. * standard output:                       Special Files.
  14082. * statement, compound:                   Statements.
  14083. * stream editor:                         Field Splitting Summary.
  14084. * stream editor, simple:                 Simple Sed.
  14085. * strftime:                              Time Functions.
  14086. * string comparison vs. regexp comparison: Typing and Comparison.
  14087. * string constants:                      Constants.
  14088. * string operators:                      Concatenation.
  14089. * string-matching operators:             Regexp Usage.
  14090. * sub:                                   String Functions.
  14091. * sub, third argument of:                String Functions.
  14092. * subscripts in arrays:                  Multi-dimensional.
  14093. * SUBSEP <1>:                            User-modified.
  14094. * SUBSEP:                                Multi-dimensional.
  14095. * substr:                                String Functions.
  14096. * subtraction:                           Arithmetic Ops.
  14097. * system:                                I/O Functions.
  14098. * systime:                               Time Functions.
  14099. * Tcl:                                   Library Names.
  14100. * tee utility:                           Tee Program.
  14101. * tee.awk:                               Tee Program.
  14102. * terminator, record:                    Records.
  14103. * time of day:                           Time Functions.
  14104. * timestamps:                            Time Functions.
  14105. * timestamps, converting from dates:     Mktime Function.
  14106. * timestamps, formatted:                 Gettimeofday Function.
  14107. * tolower:                               String Functions.
  14108. * toupper:                               String Functions.
  14109. * translate.awk:                         Translate Program.
  14110. * Trueman, David:                        Acknowledgements.
  14111. * truth values:                          Truth Values.
  14112. * type conversion:                       Conversion.
  14113. * types of variables <1>:                Typing and Comparison.
  14114. * types of variables:                    Assignment Ops.
  14115. * undefined functions:                   Function Caveats.
  14116. * undocumented features:                 Undocumented.
  14117. * uninitialized variables, as array subscripts: Uninitialized Subscripts.
  14118. * uniq utility:                          Uniq Program.
  14119. * uniq.awk:                              Uniq Program.
  14120. * use of comments:                       Comments.
  14121. * user information:                      Passwd Functions.
  14122. * user-defined functions:                User-defined.
  14123. * user-defined variables:                Using Variables.
  14124. * uses of awk:                           What Is Awk.
  14125. * using this book:                       This Manual.
  14126. * values of characters as numbers:       Ordinal Functions.
  14127. * variable shadowing:                    Definition Syntax.
  14128. * variable typing:                       Typing and Comparison.
  14129. * variables, user-defined:               Using Variables.
  14130. * Wall, Larry:                           Future Extensions.
  14131. * wc utility:                            Wc Program.
  14132. * wc.awk:                                Wc Program.
  14133. * Weinberger, Peter:                     History.
  14134. * when to use awk:                       When.
  14135. * while statement:                       While Statement.
  14136. * word boundaries, matching:             GNU Regexp Operators.
  14137. * word, regexp definition of:            GNU Regexp Operators.
  14138. * wordfreq.sh:                           Word Sorting.
  14139. * || operator:                           Boolean Ops.
  14140. * ~ operator <1>:                        Typing and Comparison.
  14141. * ~ operator <2>:                        Regexp Usage.
  14142. * ~ operator <3>:                        Case-sensitivity.
  14143. * ~ operator <4>:                        Computed Regexps.
  14144. * ~ operator:                            Regexp Constants.
  14145. Tag Table:
  14146. Node: Top
  14147. Node: Preface
  14148. 20719
  14149. Node: History
  14150. 22069
  14151. Node: Manual History
  14152. 23427
  14153. Node: Acknowledgements
  14154. 26869
  14155. Node: What Is Awk
  14156. 30496
  14157. Node: This Manual
  14158. 32150
  14159. Node: Conventions
  14160. 34849
  14161. Node: Sample Data Files
  14162. 36141
  14163. Node: Getting Started
  14164. 39224
  14165. Node: Names
  14166. 41532
  14167. Node: Running gawk
  14168. 43102
  14169. Node: One-shot
  14170. 44263
  14171. Node: Read Terminal
  14172. 45650
  14173. Node: Long
  14174. 47262
  14175. Node: Executable Scripts
  14176. 48655
  14177. Node: Comments
  14178. 50910
  14179. Node: Very Simple
  14180. 52070
  14181. Node: Two Rules
  14182. 54117
  14183. Node: More Complex
  14184. 56296
  14185. Node: Statements/Lines
  14186. 59412
  14187. Node: Other Features
  14188. 63685
  14189. Node: When
  14190. 64411
  14191. Node: One-liners
  14192. 66346
  14193. Node: Regexp
  14194. 69233
  14195. Node: Regexp Usage
  14196. 70559
  14197. Node: Escape Sequences
  14198. 72709
  14199. Node: Regexp Operators
  14200. 78161
  14201. Node: GNU Regexp Operators
  14202. 89194
  14203. Node: Case-sensitivity
  14204. 92898
  14205. Node: Leftmost Longest
  14206. 96014
  14207. Node: Computed Regexps
  14208. 97549
  14209. Node: Reading Files
  14210. 100206
  14211. Node: Records
  14212. 101974
  14213. Node: Fields
  14214. 108469
  14215. Node: Non-Constant Fields
  14216. 111538
  14217. Node: Changing Fields
  14218. 113825
  14219. Node: Field Separators
  14220. 118232
  14221. Node: Basic Field Splitting
  14222. 118934
  14223. Node: Regexp Field Splitting
  14224. 122163
  14225. Node: Single Character Fields
  14226. 124730
  14227. Node: Command Line Field Separator
  14228. 125799
  14229. Node: Field Splitting Summary
  14230. 129040
  14231. Node: Constant Size
  14232. 131059
  14233. Node: Multiple Line
  14234. 135096
  14235. Node: Getline
  14236. 140504
  14237. Node: Getline Intro
  14238. 141578
  14239. Node: Plain Getline
  14240. 142541
  14241. Node: Getline/Variable
  14242. 144805
  14243. Node: Getline/File
  14244. 145947
  14245. Node: Getline/Variable/File
  14246. 147257
  14247. Node: Getline/Pipe
  14248. 149231
  14249. Node: Getline/Variable/Pipe
  14250. 151321
  14251. Node: Getline Summary
  14252. 152439
  14253. Node: Printing
  14254. 154033
  14255. Node: Print
  14256. 155101
  14257. Node: Print Examples
  14258. 157201
  14259. Node: Output Separators
  14260. 159811
  14261. Node: OFMT
  14262. 161709
  14263. Node: Printf
  14264. 163111
  14265. Node: Basic Printf
  14266. 164015
  14267. Node: Control Letters
  14268. 165549
  14269. Node: Format Modifiers
  14270. 168237
  14271. Node: Printf Examples
  14272. 172386
  14273. Node: Redirection
  14274. 175164
  14275. Node: Special Files
  14276. 179803
  14277. Node: Close Files And Pipes
  14278. 185040
  14279. Node: Expressions
  14280. 189100
  14281. Node: Constants
  14282. 191296
  14283. Node: Scalar Constants
  14284. 191775
  14285. Node: Regexp Constants
  14286. 192780
  14287. Node: Using Constant Regexps
  14288. 193242
  14289. Node: Variables
  14290. 196443
  14291. Node: Using Variables
  14292. 197097
  14293. Node: Assignment Options
  14294. 198532
  14295. Node: Conversion
  14296. 200477
  14297. Node: Arithmetic Ops
  14298. 203659
  14299. Node: Concatenation
  14300. 205793
  14301. Node: Assignment Ops
  14302. 207215
  14303. Node: Increment Ops
  14304. 212811
  14305. Node: Truth Values
  14306. 215339
  14307. Node: Typing and Comparison
  14308. 216387
  14309. Node: Boolean Ops
  14310. 222394
  14311. Node: Conditional Exp
  14312. 226087
  14313. Node: Function Calls
  14314. 227764
  14315. Node: Precedence
  14316. 230644
  14317. Node: Patterns and Actions
  14318. 234032
  14319. Node: Pattern Overview
  14320. 234458
  14321. Node: Kinds of Patterns
  14322. 235233
  14323. Node: Regexp Patterns
  14324. 236370
  14325. Node: Expression Patterns
  14326. 236924
  14327. Node: Ranges
  14328. 240575
  14329. Node: BEGIN/END
  14330. 243299
  14331. Node: Using BEGIN/END
  14332. 243768
  14333. Node: I/O And BEGIN/END
  14334. 246731
  14335. Node: Empty
  14336. 248747
  14337. Node: Action Overview
  14338. 249046
  14339. Node: Statements
  14340. 251618
  14341. Node: If Statement
  14342. 253324
  14343. Node: While Statement
  14344. 254827
  14345. Node: Do Statement
  14346. 256857
  14347. Node: For Statement
  14348. 257959
  14349. Node: Break Statement
  14350. 261216
  14351. Node: Continue Statement
  14352. 263487
  14353. Node: Next Statement
  14354. 265483
  14355. Node: Nextfile Statement
  14356. 267980
  14357. Node: Exit Statement
  14358. 269894
  14359. Node: Built-in Variables
  14360. 271904
  14361. Node: User-modified
  14362. 273000
  14363. Node: Auto-set
  14364. 277922
  14365. Node: ARGC and ARGV
  14366. 284452
  14367. Node: Arrays
  14368. 287798
  14369. Node: Array Intro
  14370. 289261
  14371. Node: Reference to Elements
  14372. 293301
  14373. Node: Assigning Elements
  14374. 295251
  14375. Node: Array Example
  14376. 295753
  14377. Node: Scanning an Array
  14378. 297472
  14379. Node: Delete
  14380. 299802
  14381. Node: Numeric Array Subscripts
  14382. 301861
  14383. Node: Uninitialized Subscripts
  14384. 303767
  14385. Node: Multi-dimensional
  14386. 305411
  14387. Node: Multi-scanning
  14388. 308506
  14389. Node: Built-in
  14390. 310149
  14391. Node: Calling Built-in
  14392. 311138
  14393. Node: Numeric Functions
  14394. 313109
  14395. Node: String Functions
  14396. 316928
  14397. Node: I/O Functions
  14398. 335860
  14399. Node: Time Functions
  14400. 341445
  14401. Node: User-defined
  14402. 350298
  14403. Node: Definition Syntax
  14404. 351011
  14405. Node: Function Example
  14406. 355260
  14407. Node: Function Caveats
  14408. 357589
  14409. Node: Return Statement
  14410. 361459
  14411. Node: Invoking Gawk
  14412. 364114
  14413. Node: Options
  14414. 365349
  14415. Node: Other Arguments
  14416. 374179
  14417. Node: AWKPATH Variable
  14418. 376827
  14419. Node: Obsolete
  14420. 379576
  14421. Node: Undocumented
  14422. 380242
  14423. Node: Known Bugs
  14424. 380491
  14425. Node: Library Functions
  14426. 381623
  14427. Node: Portability Notes
  14428. 384041
  14429. Node: Nextfile Function
  14430. 385325
  14431. Node: Assert Function
  14432. 390201
  14433. Node: Round Function
  14434. 393540
  14435. Node: Ordinal Functions
  14436. 395184
  14437. Node: Join Function
  14438. 398636
  14439. Node: Mktime Function
  14440. 400688
  14441. Node: Gettimeofday Function
  14442. 412261
  14443. Node: Filetrans Function
  14444. 416273
  14445. Node: Getopt Function
  14446. 419950
  14447. Node: Passwd Functions
  14448. 431306
  14449. Node: Group Functions
  14450. 439639
  14451. Node: Library Names
  14452. 447536
  14453. Node: Sample Programs
  14454. 451461
  14455. Node: Clones
  14456. 451952
  14457. Node: Cut Program
  14458. 453046
  14459. Node: Egrep Program
  14460. 463075
  14461. Node: Id Program
  14462. 470738
  14463. Node: Split Program
  14464. 474009
  14465. Node: Tee Program
  14466. 477377
  14467. Node: Uniq Program
  14468. 480173
  14469. Node: Wc Program
  14470. 487718
  14471. Node: Miscellaneous Programs
  14472. 492136
  14473. Node: Dupword Program
  14474. 493046
  14475. Node: Alarm Program
  14476. 494717
  14477. Node: Translate Program
  14478. 499261
  14479. Node: Labels Program
  14480. 504073
  14481. Node: Word Sorting
  14482. 507617
  14483. Node: History Sorting
  14484. 511962
  14485. Node: Extract Program
  14486. 513931
  14487. Node: Simple Sed
  14488. 520889
  14489. Node: Igawk Program
  14490. 524233
  14491. Node: Language History
  14492. 537554
  14493. Node: V7/SVR3.1
  14494. 538787
  14495. Node: SVR4
  14496. 541442
  14497. Node: POSIX
  14498. 542964
  14499. Node: BTL
  14500. 544584
  14501. Node: POSIX/GNU
  14502. 545347
  14503. Node: Gawk Summary
  14504. 549779
  14505. Node: Command Line Summary
  14506. 550601
  14507. Node: Language Summary
  14508. 553577
  14509. Node: Variables/Fields
  14510. 555958
  14511. Node: Fields Summary
  14512. 556692
  14513. Node: Built-in Summary
  14514. 558478
  14515. Node: Arrays Summary
  14516. 562193
  14517. Node: Data Type Summary
  14518. 563486
  14519. Node: Rules Summary
  14520. 565312
  14521. Node: Pattern Summary
  14522. 566840
  14523. Node: Regexp Summary
  14524. 569025
  14525. Node: Actions Summary
  14526. 572408
  14527. Node: Operator Summary
  14528. 574240
  14529. Node: Control Flow Summary
  14530. 575467
  14531. Node: I/O Summary
  14532. 576024
  14533. Node: Printf Summary
  14534. 579013
  14535. Node: Special File Summary
  14536. 582351
  14537. Node: Built-in Functions Summary
  14538. 584029
  14539. Node: Time Functions Summary
  14540. 588029
  14541. Node: String Constants Summary
  14542. 588920
  14543. Node: Functions Summary
  14544. 590240
  14545. Node: Historical Features
  14546. 591301
  14547. Node: Installation
  14548. 592799
  14549. Node: Gawk Distribution
  14550. 594014
  14551. Node: Getting
  14552. 594517
  14553. Node: Extracting
  14554. 597463
  14555. Node: Distribution contents
  14556. 598850
  14557. Node: Unix Installation
  14558. 603626
  14559. Node: Quick Installation
  14560. 604135
  14561. Node: Configuration Philosophy
  14562. 605653
  14563. Node: VMS Installation
  14564. 608055
  14565. Node: VMS Compilation
  14566. 608594
  14567. Node: VMS Installation Details
  14568. 610198
  14569. Node: VMS Running
  14570. 611840
  14571. Node: VMS POSIX
  14572. 613430
  14573. Node: PC Installation
  14574. 614710
  14575. Node: Atari Installation
  14576. 618113
  14577. Node: Atari Compiling
  14578. 619297
  14579. Node: Atari Using
  14580. 621206
  14581. Node: Amiga Installation
  14582. 624053
  14583. Node: Bugs
  14584. 625164
  14585. Node: Other Versions
  14586. 628240
  14587. Node: Notes
  14588. 629814
  14589. Node: Compatibility Mode
  14590. 630421
  14591. Node: Additions
  14592. 631264
  14593. Node: Adding Code
  14594. 631962
  14595. Node: New Ports
  14596. 637302
  14597. Node: Future Extensions
  14598. 641470
  14599. Node: Improvements
  14600. 643718
  14601. Node: Glossary
  14602. 645586
  14603. Node: Copying
  14604. 662651
  14605. Node: Index
  14606. 681843
  14607. End Tag Table
  14608.