aboutsummaryrefslogtreecommitdiffstats
path: root/gawk.texinfo
diff options
context:
space:
mode:
Diffstat (limited to 'gawk.texinfo')
-rw-r--r--gawk.texinfo5962
1 files changed, 3882 insertions, 2080 deletions
diff --git a/gawk.texinfo b/gawk.texinfo
index 4c22e8ad..1a28e666 100644
--- a/gawk.texinfo
+++ b/gawk.texinfo
@@ -3,6 +3,8 @@
@setfilename gawk-info
@settitle The GAWK Manual
@c %**end of header (This is for running Texinfo on a region.)
+@syncodeindex fn cp
+@syncodeindex vr cp
@iftex
@finalout
@@ -36,18 +38,25 @@ except that this permission notice may be stated in a translation approved
by the Foundation.
@end ifinfo
+@c @smallbook
+@c For printing as a small manual, uncomment the above line. Then change
+@c every `@example' to `@smallexample' and every `@end example' to
+@c `@end smallexample'. That's all.
+
@setchapternewpage odd
@titlepage
@sp 11
@center @titlefont{The GAWK Manual}
@sp 4
-@center by Diane Barlow Close and Richard Stallman
-@center with Paul H. Rubin
-@center and Arnold D. Robbins
+@center by
+@center Diane Barlow Close
+@center Arnold D. Robbins
+@center Paul H. Rubin
+@center Richard Stallman
@sp 2
-@center Edition 0.1 Beta
+@center Edition 0.11 Beta
@sp 2
-@center March 1989
+@center October 1989
@c Include the Distribution inside the titlepage environment so
@c that headings are turned off. Headings on and off do not work.
@@ -57,9 +66,9 @@ by the Foundation.
Copyright @copyright{} 1989 Free Software Foundation, Inc.
@sp 2
-This is Edition 0.1 Beta of @cite{The GAWK Manual}, @*
-for the 2.02 Beta, 23 December 1988, version @*
-of the GNU implementation of AWK.
+This is Edition 0.11 Beta of @cite{The GAWK Manual}, @*
+for the 2.11 Beta version of the GNU implementation @*
+of AWK.
@sp 2
Published by the Free Software Foundation @*
@@ -82,7 +91,7 @@ except that this permission notice may be stated in a translation approved
by the Foundation.
@end titlepage
-@node Top, Preface, (dir), (dir)
+@node Top, Preface, (dir), (dir)
@comment node-name, next, previous, up
@c Preface or Licensing nodes should come right after the Top
@c node, in `unnumbered' sections, then the chapter, `What is gawk'.
@@ -94,15 +103,13 @@ contains the following chapters:
@end ifinfo
@menu
-* Preface:: What you can do with @code{awk}; brief history
- and acknowledgements.
+* Preface:: What you can do with @code{awk}; brief history
+ and acknowledgements.
-* License:: Your right to copy and distribute @code{gawk}.
+* Copying:: Your right to copy and distribute @code{gawk}.
-* This Manual:: Using this manual.
-@ifinfo
- Includes sample input files that you can use.
-@end ifinfo
+* This Manual:: Using this manual.
+ Includes sample input files that you can use.
* Getting Started:: A basic introduction to using @code{awk}.
How to run an @code{awk} program. Command line syntax.
@@ -110,7 +117,7 @@ contains the following chapters:
* Printing:: How to print using @code{awk}. Describes the
@code{print} and @code{printf} statements.
- Also describes redirection of output.
+ Also describes redirection of output.
* One-liners:: Short, sample @code{awk} programs.
@@ -120,17 +127,25 @@ contains the following chapters:
Describes expressions and the various operators in
detail. Also describes comparison expressions.
+* Expressions:: Expressions are the basic building blocks of statements.
+
* Statements:: The various control statements are described in
detail.
* Arrays:: The description and use of arrays. Also includes
- array--oriented control statements.
+ array-oriented control statements.
+
+* Built-in:: The built-in functions are summarized here.
+
+* User-defined:: User-defined functions are described in detail.
-* User-defined:: User--defined functions are described in detail.
+* Var: Built-in Variables. The built-in variables are summarized here.
-* Built-in:: The built--in functions are summarized here.
+* Command Line:: How to run @code{gawk}.
-* Special:: The special variables are summarized here.
+* Language History:: The evolution of the @code{awk} language.
+
+* Gawk Summary:: @code{gawk} Options and Language Summary.
* Sample Program:: A sample @code{awk} program with a complete explanation.
@@ -141,21 +156,20 @@ contains the following chapters:
* Index::
@end menu
-
-@node Preface, License, Top , Top
+@node Preface, Copying, Top , Top
@comment node-name, next, previous, up
@unnumbered Preface
-@cindex What is @code{awk}
+@c @cindex what is @code{awk}
If you are like many computer users, you frequently would like to make
changes in various text files wherever certain patterns appear, or
extract data from parts of certain lines while discarding the rest. To
write a program to do this in a language such as C or Pascal is a
-time--consuming inconvenience that may take many lines of code. The job
+time-consuming inconvenience that may take many lines of code. The job
may be easier with @code{awk}.
-The @code{awk} utility interprets a special--purpose programming language
-that makes it possible to handle simple data--reformatting jobs easily
+The @code{awk} utility interprets a special-purpose programming language
+that makes it possible to handle simple data-reformatting jobs easily
with just a few lines of code.
The GNU implementation of @code{awk} is called @code{gawk}; it is fully
@@ -165,11 +179,10 @@ version of @code{awk}. All properly written
distinguish between @code{gawk} and other @code{awk} implementations in
this manual.@refill
-@cindex Uses of @code{awk}
+@cindex uses of @code{awk}
This manual teaches you what @code{awk} does and how you can use
-@code{awk} effectively. You should already be familiar with basic,
-general--purpose, operating system commands such as @code{ls}. Using
-@code{awk} you can: @refill
+@code{awk} effectively. You should already be familiar with basic
+system commands such as @code{ls}. Using @code{awk} you can: @refill
@itemize @bullet
@item
@@ -189,20 +202,23 @@ languages!
@end itemize
@menu
-* History:: The history of gawk and awk. Acknowledgements.
+* History:: The history of @code{gawk} and @code{awk}. Acknowledgements.
@end menu
-@node History, , , Preface
+@node History, , Preface, Preface
@comment node-name, next, previous, up
@unnumberedsec History of @code{awk} and @code{gawk}
-@cindex Acronym
-@cindex History of @code{awk}
+@cindex acronym
+@cindex history of @code{awk}
The name @code{awk} comes from the initials of its designers: Alfred V.
Aho, Peter J. Weinberger, and Brian W. Kernighan. The original version of
@code{awk} was written in 1977. In 1985 a new version made the programming
-language more powerful, introducing user--defined functions, multiple input
+language more powerful, introducing user-defined functions, multiple input
streams, and computed regular expressions.
+This new version became generally available with System V Release 3.1.
+The version in System V Release 4 added some new features and also cleaned
+up the behaviour in some of the ``dark corners'' of the language.@refill
@comment We don't refer people to non-free information
@comment In 1988, the original authors
@comment published @cite{The AWK Programming Language} (Addison-Wesley, ISBN
@@ -210,9 +226,9 @@ streams, and computed regular expressions.
The GNU implementation, @code{gawk}, was written in 1986 by Paul Rubin
and Jay Fenlason, with advice from Richard Stallman. John Woods
-contributed parts of the code as well. In 1988, David Trueman, with
-help from Arnold Robbins, reworked @code{gawk} for compatibility with
-the newer @code{awk}.
+contributed parts of the code as well. In 1988 and 1989, David Trueman, with
+help from Arnold Robbins, thoroughly reworked @code{gawk} for compatibility
+with the newer @code{awk}.
Many people need to be thanked for their assistance in producing this
manual. Jay Fenlason contributed many ideas and sample programs. Richard
@@ -226,8 +242,8 @@ Finally, we would like to thank Brian Kernighan of Bell Labs for invaluable
assistance during the testing and debugging of @code{gawk}, and for
help in clarifying several points about the language.@refill
-@node License, This Manual, Preface, Top
-@unnumbered GNU GENERAL PUBLIC LICENSE
+@node Copying, This Manual, Preface, Top
+@unnumbered GNU General Public License
@center Version 1, February 1989
@display
@@ -238,6 +254,7 @@ Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
@end display
+@c fakenode - this is for prepinfo.
@unnumberedsec Preamble
The license agreements of most software companies try to keep users
@@ -280,6 +297,7 @@ authors' reputations.
modification follow.
@iftex
+@c fakenode -- this is for prepinfo.
@unnumberedsec TERMS AND CONDITIONS
@end iftex
@ifinfo
@@ -423,6 +441,7 @@ of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
@iftex
+@c fakenode -- this is for prepinfo.
@heading NO WARRANTY
@end iftex
@ifinfo
@@ -453,6 +472,7 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
@end enumerate
@iftex
+@c fakenode -- this is for prepinfo.
@heading END OF TERMS AND CONDITIONS
@end iftex
@ifinfo
@@ -460,7 +480,8 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
@end ifinfo
@page
-@unnumberedsec Appendix: How to Apply These Terms to Your New Programs
+@c fakenode -- this is for prepinfo.
+@unnumberedsec Appendix: Using These Terms in New Programs
If you develop a new program, and you want it to be of the greatest
possible use to humanity, the best way to achieve this is to make it
@@ -524,21 +545,21 @@ Ty Coon, President of Vice
That's all there is to it!
-@node This Manual, Getting Started, License , Top
+@node This Manual, Getting Started, Copying, Top
@chapter Using This Manual
-@cindex Manual, using this
-@cindex Using this manual
-@cindex Language, @code{awk}
-@cindex Program, @code{awk}
+@cindex manual, using this
+@cindex using this manual
+@cindex language, @code{awk}
+@cindex program, @code{awk}
@cindex @code{awk} language
@cindex @code{awk} program
-The term @code{gawk} refers to a program (a version of @code{awk})
-developed by the Free Software Foundation, and to the language you
-use to tell it what to do. When we need to be careful, we call the program
-``the @code{awk} utility'' and the language ``the @code{awk} language''.
-The purpose of this manual is to explain the @code{awk} language and how to
-run the @code{awk} utility.
+The term @code{gawk} refers to a particular program (a version of
+@code{awk}, developed as part the GNU project), and to the language you
+use to tell this program what to do. When we need to be careful, we
+call the program ``the @code{awk} utility'' and the language ``the
+@code{awk} language''. The purpose of this manual is to explain the
+@code{awk} language and how to run the @code{awk} utility.
The term @dfn{@code{awk} program} refers to a program written by you in
the @code{awk} programming language.@refill
@@ -546,13 +567,13 @@ the @code{awk} programming language.@refill
@xref{Getting Started}, for the bare essentials you need to know to
start using @code{awk}.
-Useful ``one--liners'' are included to give you a feel for the
+Some useful ``one-liners'' are included to give you a feel for the
@code{awk} language (@pxref{One-liners}).
@ignore
@strong{I deleted four paragraphs here because they would confuse the
beginner more than help him. They mention terms such as ``field'',
-``pattern'', ``action'', ``built--in function'' which the beginner
+``pattern'', ``action'', ``built-in function'' which the beginner
doesn't know.}
@strong{If you can find a way to introduce several of these concepts here,
@@ -576,27 +597,29 @@ that illustrates the concept being described is shown.@refill
@menu
This chapter contains the following sections:
-* The Files:: Sample data files for use in the @code{awk} programs
+* Sample Data Files:: Sample data files for use in the @code{awk} programs
illustrated in this manual.
@end menu
-@node The Files, , , This Manual
-@section Input Files for the Examples
+@node Sample Data Files, , This Manual, This Manual
+@section Data Files for the Examples
-@cindex Input file, sample
-@cindex Sample input file
+@cindex input file, sample
+@cindex sample input file
@cindex @file{BBS-list} file
-This manual contains many sample programs. The data for many of those
-programs comes from two files. The first file, called @file{BBS-list},
-represents a list of computer bulletin board systems and information about
-those systems.
-
-Each line of this file is one @dfn{record}. Each record contains the name
-of a computer bulletin board, its phone number, the board's baud rate, and a
-code for the number of hours it is operational. An @samp{A} in the last
-column means the board operates 24 hours all week. A @samp{B} in the last
-column means the board operates evening and weekend hours, only. A @samp{C}
-means the board operates only on weekends.
+Many of the examples in this manual take their input from two sample
+data files. The first, called @file{BBS-list}, represents a list of
+computer bulletin board systems and information about those systems.
+The second data file, called @file{inventory-shipped}, contains
+information about shipments on a monthly basis. Each line of these
+files is one @dfn{record}.
+
+In the file @file{BBS-list}, each record contains the name of a computer
+bulletin board, its phone number, the board's baud rate, and a code for
+the number of hours it is operational. An @samp{A} in the last column
+means the board operates 24 hours all week. A @samp{B} in the last
+column means the board operates evening and weekend hours, only. A
+@samp{C} means the board operates only on weekends.
@group
@example
@@ -613,12 +636,15 @@ sdace 555-3430 2400/1200/300 A
sabafoo 555-2127 1200/300 C
@end example
@end group
-The second data file, called @file{inventory-shipped}, represents
-information about shipments during the year. Each line of this file is also
-one record. Each record contains the month of the year, the number of green
-crates shipped, the number of red boxes shipped, the number of orange bags
-shipped, and the number of blue packages shipped, respectively.
+
@cindex @file{inventory-shipped} file
+The second data file, called @file{inventory-shipped}, represents
+information about shipments during the year. Each line of this file is
+also one record. Each record contains the month of the year, the number
+of green crates shipped, the number of red boxes shipped, the number of
+orange bags shipped, and the number of blue packages shipped,
+respectively. There are 16 entries, covering the 12 months of one year
+and 4 months of the next year.
@group
@example
@@ -655,29 +681,28 @@ learn in this manual.
@node Getting Started, Reading Files, This Manual, Top
@chapter Getting Started With @code{awk}
+@cindex script, definition of
+@cindex rule, definition of
+@cindex program, definition of
+@cindex basic function of @code{gawk}
-@cindex Script, definition of
-@cindex Rule, definition of
-@cindex Pattern, definition of
-@cindex Action, definition of
-@cindex Program, definition of
-@cindex Basic function of @code{gawk}
The basic function of @code{awk} is to search files for lines (or other
-units of text) that contain certain patterns. When a line matching any
-of those patterns is found, @code{awk} performs specified actions on
-that line. Then @code{awk} keeps processing input lines until the end
-of the file is reached.@refill
+units of text) that contain certain patterns. When a line matches one
+of the patterns, @code{awk} performs specified actions on that line.
+@code{awk} keeps processing input lines in this way until the end of the
+input file is reached.@refill
-An @code{awk} @dfn{program} or @dfn{script} consists of a series of
-@dfn{rules}. (They may also contain @dfn{function definitions}, but
-that is an advanced feature, so let's ignore it for now.
-@xref{User-defined}.)
+When you run @code{awk}, you specify an @code{awk} @dfn{program} which
+tells @code{awk} what to do. The program consists of a series of
+@dfn{rules}. (It may also contain @dfn{function definitions}, but that
+is an advanced feature, so let's ignore it for now.
+@xref{User-defined}.) Each rule specifies one pattern to search for,
+and one action to perform when that pattern is found.
-A rule contains a @dfn{pattern}, an @dfn{action}, or both. Actions are
-enclosed in curly braces to distinguish them from patterns. Therefore,
-an @code{awk} program is a sequence of rules in the form:@refill
-@cindex Action, curly braces
-@cindex Curly braces
+Syntactically, a rule consists of a pattern followed by an action. The
+action is enclosed in curly braces to separate it from the pattern.
+Rules are usually separated by newlines. Therefore, an @code{awk}
+program looks like this:
@example
@var{pattern} @{ @var{action} @}
@@ -687,22 +712,23 @@ an @code{awk} program is a sequence of rules in the form:@refill
@menu
* Very Simple:: A very simple example.
-* Two Rules:: A less simple one--line example with two rules.
+* Two Rules:: A less simple one-line example with two rules.
* More Complex:: A more complex example.
-* Running gawk:: How to run gawk programs; includes command line syntax.
-* Comments:: Adding documentation to gawk programs.
+* Running gawk:: How to run @code{gawk} programs; includes command line syntax.
+* Comments:: Adding documentation to @code{gawk} programs.
* Statements/Lines:: Subdividing or combining statements into lines.
-
-* When:: When to use gawk and when to use other things.
+* When:: When to use @code{gawk} and when to use other things.
@end menu
-@node Very Simple, Two Rules, , Getting Started
+@node Very Simple, Two Rules, Getting Started, Getting Started
@section A Very Simple Example
-@cindex @code{print $0}
+@cindex @samp{print $0}
The following command runs a simple @code{awk} program that searches the
input file @file{BBS-list} for the string of characters: @samp{foo}. (A
-string of characters is usually called, quite simply, a @dfn{string}.)
+string of characters is usually called, quite simply, a @dfn{string}.
+The term @dfn{string} is perhaps based on similar usage in English, such
+as ``a string of pearls,'' or, ``a string of cars in a train.'')
@example
awk '/foo/ @{ print $0 @}' BBS-list
@@ -710,7 +736,7 @@ awk '/foo/ @{ print $0 @}' BBS-list
@noindent
When lines containing @samp{foo} are found, they are printed, because
-@w{@code{print $0}} means print the current line. (Just @code{print} by
+@w{@samp{print $0}} means print the current line. (Just @samp{print} by
itself also means the same thing, so we could have written that
instead.)
@@ -718,7 +744,7 @@ You will notice that slashes, @samp{/}, surround the string @samp{foo}
in the actual @code{awk} program. The slashes indicate that @samp{foo}
is a pattern to search for. This type of pattern is called a
@dfn{regular expression}, and is covered in more detail later
-(@pxref{Regexp}). There are single quotes around the @code{awk} program
+(@pxref{Regexp}). There are single-quotes around the @code{awk} program
so that the shell won't interpret any of it as special shell
characters.@refill
@@ -731,27 +757,24 @@ macfoo 555-6480 1200/300 A
sabafoo 555-2127 1200/300 C
@end example
-@cindex Action, default
-@cindex Pattern, default
-@cindex Default action
-@cindex Default pattern
+@cindex action, default
+@cindex pattern, default
+@cindex default action
+@cindex default pattern
In an @code{awk} rule, either the pattern or the action can be omitted,
-but not both.
-
-If the pattern is omitted, then the action is performed for @emph{every}
-input line.@refill
+but not both. If the pattern is omitted, then the action is performed
+for @emph{every} input line. If the action is omitted, the default
+action is to print all lines that match the pattern.
-If the action is omitted, the default action is to print all lines that
-match the pattern. We could leave out the action (the print statement
-and the curly braces) in the above example, and the result would be the
-same: all lines matching the pattern @samp{foo} would be printed. (By
-comparison, omitting the print statement but retaining the curly braces
-makes an empty action that does nothing; then no lines would be
-printed.)
+Thus, we could leave out the action (the @code{print} statement and the curly
+braces) in the above example, and the result would be the same: all
+lines matching the pattern @samp{foo} would be printed. By comparison,
+omitting the @code{print} statement but retaining the curly braces makes an
+empty action that does nothing; then no lines would be printed.
@node Two Rules, More Complex, Very Simple, Getting Started
@section An Example with Two Rules
-@cindex How gawk works
+@cindex how @code{awk} works
The @code{awk} utility reads the input files one line at a
time. For each line, @code{awk} tries the patterns of all the rules.
@@ -760,7 +783,7 @@ which they appear in the @code{awk} program. If no patterns match, then
no actions are run.
After processing all the rules (perhaps none) that match the line,
-@code{awk} reads the next line (however, @pxref{Next}).
+@code{awk} reads the next line (however, @pxref{Next Statement}).
This continues until the end of the file is reached.@refill
For example, the @code{awk} program:
@@ -811,7 +834,7 @@ Apr 21 70 74 514
Note how the line in @file{BBS-list} beginning with @samp{sabafoo}
was printed twice, once for each rule.
-@node More Complex, Running gawk, Two Rules, Getting Started
+@node More Complex, Running gawk, Two Rules, Getting Started
@comment node-name, next, previous, up
@section A More Complex Example
@@ -829,10 +852,10 @@ ls -l | awk '$5 == "Nov" @{ sum += $4 @}
This command prints the total number of bytes in all the files in the
current directory that were last modified in November (of any year).
(In the C shell you would need to type a semicolon and then a backslash
-at the end of the first line; in the Bourne shell you can type the example
-as shown.)
+at the end of the first line; in the Bourne shell or the Bourne-Again
+shell, you can type the example as shown.)
-The @w{@code{ls -l}} part of this example is a command that gives you a full
+The @w{@samp{ls -l}} part of this example is a command that gives you a full
listing of all the files in a directory, including file size and date.
Its output looks like this:
@@ -848,39 +871,39 @@ Its output looks like this:
@end example
@noindent
-The first field contains read--write permissions, the second field contains
+The first field contains read-write permissions, the second field contains
the number of links to the file, and the third field identifies the owner of
the file. The fourth field contains the size of the file in bytes. The
fifth, sixth, and seventh fields contain the month, day, and time,
respectively, that the file was last modified. Finally, the eighth field
contains the name of the file.
-The @samp{$5 == "Nov"} in our @code{awk} program is an expression that
-tests whether the fifth field of the output from @w{@code{ls -l}}
+The @code{$5 == "Nov"} in our @code{awk} program is an expression that
+tests whether the fifth field of the output from @w{@samp{ls -l}}
matches the string @samp{Nov}. Each time a line has the string
@samp{Nov} in its fifth field, the action @samp{@{ sum += $4 @}} is
performed. This adds the fourth field (the file size) to the variable
@code{sum}. As a result, when @code{awk} has finished reading all the
-input lines, @code{sum} will be the sum of the sizes of files whose
+input lines, @code{sum} is the sum of the sizes of files whose
lines matched the pattern.@refill
After the last line of output from @code{ls} has been processed, the
-@code{END} pattern is executed, and the value of @code{sum} is
+@code{END} rule is executed, and the value of @code{sum} is
printed. In this example, the value of @code{sum} would be 80600.@refill
These more advanced @code{awk} techniques are covered in later sections
(@pxref{Actions}). Before you can move on to more advanced @code{awk}
programming, you have to know how @code{awk} interprets your input and
-displays your output. By manipulating @dfn{fields} and using special
-@dfn{print} statements, you can produce some very useful and spectacular
-looking reports.@refill
+displays your output. By manipulating fields and using @code{print}
+statements, you can produce some very useful and spectacular looking
+reports.@refill
@node Running gawk, Comments, More Complex, Getting Started
@section How to Run @code{awk} Programs
-@cindex Command line formats
-@cindex Running gawk programs
+@cindex command line formats
+@cindex running @code{awk} programs
There are several ways to run an @code{awk} program. If the program is
short, it is easiest to include it in the command that runs @code{awk},
like this:
@@ -890,8 +913,8 @@ awk '@var{program}' @var{input-file1} @var{input-file2} @dots{}
@end example
@noindent
-where @var{program} consists of a series of @var{patterns} and
-@var{actions}, as described earlier.
+where @var{program} consists of a series of patterns and actions, as
+described earlier.
When the program is long, you would probably prefer to put it in a file
and run it with a command like this:
@@ -901,15 +924,14 @@ awk -f @var{program-file} @var{input-file1} @var{input-file2} @dots{}
@end example
@menu
-* One-shot:: Running a short throw--away @code{awk} program.
-* Read Terminal:: Using no input files (input from terminal instead).
-* Long:: Putting permanent @code{awk} programs in files.
-* Executable Scripts:: Making self--contained @code{awk} programs.
-* Command Line:: How the @code{awk} command line is laid out.
+* One-shot:: Running a short throw-away @code{awk} program.
+* Read Terminal:: Using no input files (input from terminal instead).
+* Long:: Putting permanent @code{awk} programs in files.
+* Executable Scripts:: Making self-contained @code{awk} programs.
@end menu
-@node One-shot, Read Terminal, , Running gawk
-@subsection One--shot Throw--away @code{awk} Programs
+@node One-shot, Read Terminal, Running gawk, Running gawk
+@subsection One-shot Throw-away @code{awk} Programs
Once you are familiar with @code{awk}, you will often type simple
programs at the moment you want to use them. Then you can write the
@@ -923,7 +945,7 @@ awk '@var{program}' @var{input-file1} @var{input-file2} @dots{}
where @var{program} consists of a series of @var{patterns} and
@var{actions}, as described earlier.
-@cindex Single quotes, why they are needed
+@cindex single quotes, why needed
This command format tells the shell to start @code{awk} and use the
@var{program} to process records in the input file(s). There are single
quotes around the @var{program} so that the shell doesn't interpret any
@@ -932,16 +954,16 @@ shell to treat all of @var{program} as a single argument for
@code{awk}. They also allow @var{program} to be more than one line
long.@refill
-This format is also useful for running short or medium--sized @code{awk}
+This format is also useful for running short or medium-sized @code{awk}
programs from shell scripts, because it avoids the need for a separate
-file for the @code{awk} program. A self--contained shell script is more
+file for the @code{awk} program. A self-contained shell script is more
reliable since there are no other files to misplace.
@node Read Terminal, Long, One-shot, Running gawk
@subsection Running @code{awk} without Input Files
-@cindex Standard input
-@cindex Input, standard
+@cindex standard input
+@cindex input, standard
You can also use @code{awk} without any input files. If you type the
command line:@refill
@@ -952,17 +974,17 @@ awk '@var{program}'
@noindent
then @code{awk} applies the @var{program} to the @dfn{standard input},
which usually means whatever you type on the terminal. This continues
-until you indicate end--of--file by typing @kbd{Control-d}.
+until you indicate end-of-file by typing @kbd{Control-d}.
-For example, if you type:
+For example, if you execute this command:
@example
awk '/th/'
@end example
@noindent
-whatever you type next will be taken as data for that @code{awk}
-program. If you go on to type the following data,
+whatever you type next is taken as data for that @code{awk}
+program. If you go on to type the following data:
@example
Kathy
@@ -976,7 +998,7 @@ Thomas
@end example
@noindent
-then @code{awk} will print
+then @code{awk} prints this output:
@example
Kathy
@@ -985,17 +1007,19 @@ Seth
@end example
@noindent
-@cindex Case sensitivity and gawk
-@cindex Pattern, case sensitive
+@cindex case sensitivity
+@cindex pattern, case sensitive
as matching the pattern @samp{th}. Notice that it did not recognize
@samp{Thomas} as matching the pattern. The @code{awk} language is
-@dfn{case sensitive}, and matches patterns @emph{exactly}.@refill
+@dfn{case sensitive}, and matches patterns exactly. (However, you can
+override this with the variable @code{IGNORECASE}.
+@xref{Case-sensitivity}.)
@node Long, Executable Scripts, Read Terminal, Running gawk
@subsection Running Long Programs
@cindex running long programs
-@cindex -f option
+@cindex @samp{-f} option
@cindex program file
@cindex file, @code{awk} program
Sometimes your @code{awk} programs can be very long. In this case it is
@@ -1015,7 +1039,7 @@ from the file @var{source-file}. Any file name can be used for
@end example
@noindent
-into the file @file{th-prog}. Then the command:
+into the file @file{th-prog}. Then this command:
@example
awk -f th-prog
@@ -1035,25 +1059,22 @@ with @samp{-f}, because most file names don't contain any of the shell's
special characters.
If you want to identify your @code{awk} program files clearly as such,
-you can add the extension @file{.awk} to the filename. This doesn't
+you can add the extension @file{.awk} to the file name. This doesn't
affect the execution of the @code{awk} program, but it does make
``housekeeping'' easier.
-@node Executable Scripts, Command Line, Long, Running gawk
+@node Executable Scripts, , Long, Running gawk
@c node-name, next, previous, up
@subsection Executable @code{awk} Programs
-@cindex Executable Scripts
-@cindex Scripts, Executable
-@cindex Self contained Programs
-@cindex Program, Self contained
-@cindex #!
-
-(The following section assumes that you are already somewhat familiar
-with @code{awk}.)
+@cindex executable scripts
+@cindex scripts, executable
+@cindex self contained programs
+@cindex program, self contained
+@cindex @samp{#!}
-Once you have learned @code{awk}, you may want to write self--contained
+Once you have learned @code{awk}, you may want to write self-contained
@code{awk} scripts, using the @samp{#!} script mechanism. You can do
-this on BSD Unix systems and GNU.
+this on BSD Unix systems and (someday) on GNU.
For example, you could create a text file named @file{hello}, containing
the following (where @samp{BEGIN} is a feature we have not yet
@@ -1063,7 +1084,6 @@ discussed):
#! /bin/awk -f
# a sample awk program
-
BEGIN @{ print "hello, world" @}
@end example
@@ -1084,19 +1104,18 @@ awk -f hello
@end example
@noindent
-Self--contained @code{awk} scripts are particularly useful for putting
-@code{awk} programs into production on your system, without your users
-having to know that they are actually using an @code{awk} program.
+Self-contained @code{awk} scripts are useful when you want to write a
+program which users can invoke without knowing that the program is
+written in @code{awk}.
-@cindex Shell Scripts
-@cindex Scripts, Shell
+@cindex shell scripts
+@cindex scripts, shell
If your system does not support the @samp{#!} mechanism, you can get a
similar effect using a regular shell script. It would look something
like this:
@example
-: a sample awk program
-
+: The colon makes sure this script is executed by the Bourne shell.
awk '@var{program}' "$@@"
@end example
@@ -1105,7 +1124,9 @@ single quotes to protect it from interpretation by the shell. If you
omit the quotes, only a shell wizard can predict the result.
The @samp{"$@@"} causes the shell to forward all the command line
-arguments to the @code{awk} program, without interpretation.
+arguments to the @code{awk} program, without interpretation. The first
+line, which starts with a colon, is used so that this shell script will
+work even if invoked by a user who uses the C shell.
@c Someday: (See @cite{The Bourne Again Shell}, by ??.)
@c We don't refer to hoarded information.
@@ -1117,119 +1138,23 @@ arguments to the @code{awk} program, without interpretation.
@c @cite{The KornShell Command and Programming Language} by Morris Bolsky
@c and David Korn, Prentice-Hall, 1989.)
-@node Command Line, , Executable Scripts, Running gawk
-@c node-name, next, previous, up
-@subsection Details of the @code{awk} Command Line
-@cindex Command Line
-@cindex Invocation of @code{gawk}
-@cindex Arguments, Command Line
-@cindex Options, Command Line
-
-(The following section assumes that you are already familiar with
-@code{awk}.)
-
-There are two ways to run @code{awk}. Here are templates for both of
-them; items enclosed in @samp{[} and @samp{]} in these templates are
-optional.
-
-@example
-awk [ -F@var{fs} ] [ -- ] '@var{program}' @var{file} @dots{}
-awk [ -F@var{fs} ] -f @var{source-file} [ -f @var{source-file} @dots{} ] [ -- ] @var{file} @dots{}
-@end example
-
-Options begin with a minus sign, and consist of a single character.
-The options and their meanings are as follows:
-
-@table @code
-@item -F@var{fs}
-This sets the @code{FS} variable to @var{fs} (@pxref{Special}).
-As a special case, if @var{fs} is @samp{t}, then @code{FS} will be set
-to the tab character (@code{"\t"}).
-
-@item -f @var{source-file}
-Indicates that the @code{awk} program is to be found in @var{source-file}
-instead of in the first non--option argument.
-
-@item --
-This signals the end of the command line options. If you wish to
-specify an input file named @file{-f}, you can precede it with the
-@samp{--} argument to prevent the @file{-f} from being interpreted as an
-option. This handling of @samp{--} follows the POSIX argument parsing
-conventions.
-@end table
-
-Any other options will be flagged as invalid with a warning message, but
-are otherwise ignored.
-
-If the @samp{-f} option is @emph{not} used, then the first non--option
-command line argument is expected to be the program text.
-
-The @samp{-f} option may be used more than once on the command line.
-@code{awk} will read its program source from all of the named files, as
-if they had been concatenated together into one big file. This is useful
-for creating libraries of @code{awk} functions. Useful functions can be
-written once, and then retrieved from a standard place, instead of having
-to be included into each individual program. You can still type in a program
-at the terminal and use library functions, by specifying @file{/dev/tty}
-as one of the arguments to a @samp{-f}. Type your program, and end it
-with the keyboard end--of--file character @kbd{Control-d}.
-
-Any additional arguments on the command line are made available to your
-@code{awk} program in the @code{ARGV} array (@pxref{Special}). These
-arguments are normally treated as input files to be processed in the
-order specified. However, an argument that has the form
-@var{var}@code{=}@var{value}, means to assign the value @var{value} to
-the variable @var{var}---it does not specify a file at all.
-
-@vindex ARGV
-Command line options and the program text (if present) are omitted from
-the @code{ARGV} array. All other arguments, including variable assignments,
-are included (@pxref{Special}).
-
-The distinction between file name arguments and variable--assignment
-arguments is made when @code{awk} is about to open the next input file.
-At that point in execution, it checks the ``file name'' to see whether
-it is really a variable assignment; if so, instead of trying to read a
-file it will, @emph{at that point in the execution}, assign the
-variable.
-
-Therefore, the variables actually receive the specified values after all
-previously specified files have been read. In particular, the values of
-variables assigned in this fashion are @emph{not} available inside a
-@code{BEGIN} rule (@pxref{BEGIN/END}), since such rules are run before
-@code{awk} begins scanning the argument list.@refill
-
-@vindex OFS
-@vindex ORS
-@vindex RS
-The variable assignment feature is most useful for assigning to variables
-such as @code{RS}, @code{OFS}, and @code{ORS}, which control input and
-output formats, before listing the data files. It is also useful for
-controlling state if multiple passes are needed over a data file. For
-example:@refill
-
-@cindex Multiple passes over data
-@cindex Passes, Multiple
-@example
-awk 'pass == 1 @{ @var{pass 1 stuff} @}
- pass == 2 @{ @var{pass 2 stuff} @}' pass=1 datafile pass=2 datafile
-@end example
-
@node Comments, Statements/Lines, Running gawk, Getting Started
@section Comments in @code{awk} Programs
-@cindex Comments
-@cindex Use of comments
-@cindex Documenting @code{awk} programs
-@cindex Programs, documenting
+@cindex comments
+@cindex use of comments
+@cindex documenting @code{awk} programs
+@cindex programs, documenting
-When you write a complicated @code{awk} program, you can put @dfn{comments}
-in the program file to help you remember what the program does, and how it
-works.
+A @dfn{comment} is some text that is included in a program for the sake
+of human readers, and that is not really part of the program. Comments
+can explain what the program does, and how it works. Nearly all
+programming languages have provisions for comments, because programs are
+hard to understand without their extra help.
-A comment starts with the the sharp sign character, @kbd{#}, and continues
-to the end of the line. The @code{awk} language ignores the rest of a line
-following a sharp sign. For example, we could have put the following into
-@file{th-prog}:@refill
+In the @code{awk} language, a comment starts with the sharp sign
+character, @samp{#}, and continues to the end of the line. The
+@code{awk} language ignores the rest of a line following a sharp sign.
+For example, we could have put the following into @file{th-prog}:@refill
@example
# This program finds records containing the pattern @samp{th}. This is how
@@ -1237,9 +1162,9 @@ following a sharp sign. For example, we could have put the following into
/th/
@end example
-You can put comment lines into keyboard--composed throw--away @code{awk}
+You can put comment lines into keyboard-composed throw-away @code{awk}
programs also, but this usually isn't very useful; the purpose of a
-comment is to help yourself or another person understand the program at
+comment is to help you or another person understand the program at
another time.
@node Statements/Lines, When, Comments, Getting Started
@@ -1253,23 +1178,19 @@ awk '/12/ @{ print $0 @}
/21/ @{ print $0 @}' BBS-list inventory-shipped
@end example
-But sometimes statements can be more than one line, and lines can contain
-several statements.
-
-You can split a statement into multiple lines by inserting a newline after
-any of the following:
+But sometimes statements can be more than one line, and lines can
+contain several statements. You can split a statement into multiple
+lines by inserting a newline after any of the following:
@example
-, @{ ? : || &&
+, @{ ? : || && do else
@end example
@noindent
-Lines ending in @code{do} or @code{else} automatically have their
-statements continued on the following line(s). A newline at any other
-point ends the statement.@refill
+A newline at any other point is considered the end of the statement.
-@cindex Backslash Continuation
-@cindex Continuing statements on the next line
+@cindex backslash continuation
+@cindex continuation of lines
If you would like to split a single statement into two lines at a point
where a newline would terminate it, you can @dfn{continue} it by ending the
first line with a backslash character, @samp{\}. This is allowed
@@ -1289,14 +1210,14 @@ make them even more pretty by keeping the statements short. Backslash
continuation is most useful when your @code{awk} program is in a separate
source file, instead of typed in on the command line.
-@strong{Warning: this does not work if you are using the C shell.}
-Continuation with backslash works for @code{awk} programs in files, and
-also for one--shot programs @emph{provided} you are using the Bourne
-shell, the Korn shell, or the Bourne--again shell. But the C shell used
-on Berkeley Unix behaves differently! There, you must use two backslashes
-in a row, followed by a newline.@refill
+@strong{Warning: backslash continuation does not work as described above
+with the C shell.} Continuation with backslash works for @code{awk}
+programs in files, and also for one-shot programs @emph{provided} you
+are using the Bourne shell or the Bourne-again shell. But the C shell
+used on Berkeley Unix behaves differently! There, you must use two
+backslashes in a row, followed by a newline.@refill
-@cindex Multiple statements on one line
+@cindex multiple statements on one line
When @code{awk} statements within one rule are short, you might want to put
more than one of them on a line. You do this by separating the statements
with semicolons, @samp{;}.
@@ -1308,33 +1229,33 @@ Thus, the above example program could have been written:@refill
@end example
@noindent
-@emph{Note:} It is a new requirement that rules on the same line require
-semicolons as a separator in the @code{awk} language; it was done for
-consistency with the statements in the action part of rules.
+@strong{Note:} the requirement that rules on the same line must be
+separated with a semicolon is a recent change in the @code{awk}
+language; it was done for consistency with the treatment of statements
+within an action.
-@node When, , Statements/Lines, Getting Started
+@node When, , Statements/Lines, Getting Started
@section When to Use @code{awk}
-@cindex When to use @code{awk}
-@cindex Applications of @code{awk}
-What use is all of this to me, you might ask? Using additional operating
-system utilities, more advanced patterns, field separators, arithmetic
-statements, and other selection criteria, you can produce much more complex
-output. The @code{awk} language is very useful for producing reports from
-large amounts of raw data, like summarizing information from the output of
-standard operating system programs such as @code{ls}. (@xref{More
-Complex, , A More Complex Example}.)
+@cindex when to use @code{awk}
+@cindex applications of @code{awk}
+What use is all of this to me, you might ask? Using additional utility
+programs, more advanced patterns, field separators, arithmetic
+statements, and other selection criteria, you can produce much more
+complex output. The @code{awk} language is very useful for producing
+reports from large amounts of raw data, such as summarizing information
+from the output of other utility programs such as @code{ls}.
+(@xref{More Complex, , A More Complex Example}.)
Programs written with @code{awk} are usually much smaller than they would
be in other languages. This makes @code{awk} programs easy to compose and
use. Often @code{awk} programs can be quickly composed at your terminal,
used once, and thrown away. Since @code{awk} programs are interpreted, you
-can avoid the usually lengthy edit--compile--test--debug cycle of software
+can avoid the usually lengthy edit-compile-test-debug cycle of software
development.
-@cindex Emacs Lisp
Complex programs have been written in @code{awk}, including a complete
-retargetable assembler for 8--bit microprocessors (@pxref{Glossary} for
+retargetable assembler for 8-bit microprocessors (@pxref{Glossary}, for
more information) and a microcode assembler for a special purpose Prolog
computer. However, @code{awk}'s capabilities are strained by tasks of
such complexity.
@@ -1343,83 +1264,80 @@ If you find yourself writing @code{awk} scripts of more than, say, a few
hundred lines, you might consider using a different programming
language. Emacs Lisp is a good choice if you need sophisticated string
or pattern matching capabilities. The shell is also good at string and
-pattern matching; in addition it allows powerful use of the standard
-utilities. More conventional languages like C, C++, or Lisp offer
+pattern matching; in addition, it allows powerful use of the system
+utilities. More conventional languages, such as C, C++, and Lisp, offer
better facilities for system programming and for managing the complexity
of large programs. Programs in these languages may require more lines
-of source code than the equivalent @code{awk} programs, but they will be
+of source code than the equivalent @code{awk} programs, but they are
easier to maintain and usually run more efficiently.@refill
@node Reading Files, Printing, Getting Started, Top
-@chapter Reading Files (Input)
+@chapter Reading Input Files
-@cindex Reading files, general
-@cindex Input, general
-@cindex Standard input
-@cindex Input, standard
-@cindex General input
+@cindex reading files
+@cindex input
+@cindex standard input
@vindex FILENAME
In the typical @code{awk} program, all input is read either from the
standard input (usually the keyboard) or from files whose names you
specify on the @code{awk} command line. If you specify input files,
@code{awk} reads data from the first one until it reaches the end; then
it reads the second file until it reaches the end, and so on. The name
-of the current input file can be found in the special variable
-@code{FILENAME} (@pxref{Special}).@refill
-
-The input is split automatically into @dfn{records}, and processed by
-the rules one record at a time. (Records are the units of text
-mentioned in the introduction; by default, a record is a line of text.)
-Each record read is split automatically into @dfn{fields}, to make it
-more convenient for a rule to work on parts of the record under
+of the current input file can be found in the built-in variable
+@code{FILENAME} (@pxref{Built-in Variables}).@refill
+
+The input is read in units called @dfn{records}, and processed by the
+rules one record at a time. By default, each record is one line. Each
+record read is split automatically into @dfn{fields}, to make it more
+convenient for a rule to work on parts of the record under
consideration.
On rare occasions you will need to use the @code{getline} command,
-which can do explicit input from any number of files.
+which can do explicit input from any number of files (@pxref{Getline}).
@menu
-* Records:: Controlling how data is split into records.
-* Fields:: An introduction to fields.
-* Field Separators:: The field separator and how to change it.
-* Multiple:: Reading multi--line records.
-
-* Assignment Options:: Setting variables on the command line and a summary
- of command line syntax. This is an advanced method
- of input.
-
-* Getline:: Reading files under explicit program control
- using the @code{getline} function.
-* Close Input:: Closing an input file (so you can read from
- the beginning once more).
+* Records:: Controlling how data is split into records.
+* Fields:: An introduction to fields.
+* Non-Constant Fields:: Non-constant Field Numbers.
+* Changing Fields:: Changing the Contents of a Field.
+* Field Separators:: The field separator and how to change it.
+* Multiple Line:: Reading multi-line records.
+
+* Getline:: Reading files under explicit program control
+ using the @code{getline} function.
+
+* Close Input:: Closing an input file (so you can read from
+ the beginning once more).
@end menu
-@node Records, Fields, , Reading Files
+@node Records, Fields, Reading Files, Reading Files
@section How Input is Split into Records
-@cindex Record separator, @code{RS}
+@cindex record separator
The @code{awk} language divides its input into records and fields.
-Records are separated from each other by the @dfn{record separator}. By
-default, the record separator is the @dfn{newline} character.
-Therefore, normally, a record is a line of text.@refill
+Records are separated by a character called the @dfn{record separator}.
+By default, the record separator is the newline character. Therefore,
+normally, a record is a line of text.@refill
-@cindex Changing the record separator
+@c @cindex changing the record separator
@vindex RS
Sometimes you may want to use a different character to separate your
-records. You can use different characters by changing the special
+records. You can use different characters by changing the built-in
variable @code{RS}.
The value of @code{RS} is a string that says how to separate records;
the default value is @code{"\n"}, the string of just a newline
-character. This is why lines of text are the default record. Although
-@code{RS} can have any string as its value, only the first character of
-the string will be used as the record separator. The other characters
-are ignored. @code{RS} is exceptional in this regard; @code{awk} uses
-the full value of all its other special variables.@refill
+character. This is why records are, by default, single lines.
+
+@code{RS} can have any string as its value, but only the first character
+of the string is used as the record separator. The other characters are
+ignored. @code{RS} is exceptional in this regard; @code{awk} uses the
+full value of all its other built-in variables.@refill
@ignore
Someday this should be true!
-The value of @code{RS} is not limited to a one--character string. It can
+The value of @code{RS} is not limited to a one-character string. It can
be any regular expression (@pxref{Regexp}). In general, each record
ends at the next string that matches the regular expression; the next
record starts at the end of the matching string. This general rule is
@@ -1430,50 +1348,51 @@ the end of this string (at the first character of the following line).
The newline, since it matches @code{RS}, is not part of either record.
@end ignore
-The value of @code{RS} is changed by @dfn{assigning} it a new value
-(@pxref{Assignment Ops}).
-One way to do this is at the beginning of your @code{awk} program,
-before any input has been processed, using the special @code{BEGIN}
-pattern (@pxref{BEGIN/END}). This way, @code{RS} is changed to its new
-value before any input is read. The new value of @code{RS} is enclosed
-in quotation marks. For example:@refill
+You can change the value of @code{RS} in the @code{awk} program with the
+assignment operator, @samp{=} (@pxref{Assignment Ops}). The new
+record-separator character should be enclosed in quotation marks to make
+a string constant. Often the right time to do this is at the beginning
+of execution, before any input has been processed, so that the very
+first record will be read with the proper separator. To do this, use
+the special @code{BEGIN} pattern (@pxref{BEGIN/END}). For
+example:@refill
@example
awk 'BEGIN @{ RS = "/" @} ; @{ print $0 @}' BBS-list
@end example
@noindent
-changes the value of @code{RS} to @samp{/}, the slash character, before
-reading any input. Records are now separated by a slash. The second
-rule in the @code{awk} program (the action with no pattern) will proceed
-to print each record. Since each @code{print} statement adds a newline
-at the end of its output, the effect of this @code{awk} program is to
-copy the input with each slash changed to a newline.
+changes the value of @code{RS} to @code{"/"}, before reading any input.
+This is a string whose first character is a slash; as a result, records
+are separated by slashes. Then the input file is read, and the second
+rule in the @code{awk} program (the action with no pattern) prints each
+record. Since each @code{print} statement adds a newline at the end of
+its output, the effect of this @code{awk} program is to copy the input
+with each slash changed to a newline.
Another way to change the record separator is on the command line,
-using the variable--assignment feature (@pxref{Command Line}).
+using the variable-assignment feature (@pxref{Command Line}).
@example
awk '@dots{}' RS="/" @var{source-file}
@end example
@noindent
-@code{RS} will be set to @samp{/} before processing @var{source-file}.
+This sets @code{RS} to @samp{/} before processing @var{source-file}.
The empty string (a string of no characters) has a special meaning
as the value of @code{RS}: it means that records are separated only
-by blank lines. @xref{Multiple}, for more details.
+by blank lines. @xref{Multiple Line}, for more details.
-@cindex Number of records, @code{NR}
-@cindex Number of records, @code{FNR}
+@cindex number of records, @code{NR} or @code{FNR}
@vindex NR
@vindex FNR
The @code{awk} utility keeps track of the number of records that have
been read so far from the current input file. This value is stored in a
-special variable called @code{FNR}. It is reset to zero when a new file
-is started. Another variable, @code{NR}, is the total number of input
-records read so far from all files. It starts at zero but is never
-automatically reset to zero.
+built-in variable called @code{FNR}. It is reset to zero when a new
+file is started. Another built-in variable, @code{NR}, is the total
+number of input records read so far from all files. It starts at zero
+but is never automatically reset to zero.
If you change the value of @code{RS} in the middle of an @code{awk} run,
the new value is used to delimit subsequent records, but the record
@@ -1483,9 +1402,9 @@ affected.
@node Fields, Non-Constant Fields, Records, Reading Files
@section Examining Fields
-@cindex Examining fields
-@cindex Fields
-@cindex Accessing fields
+@cindex examining fields
+@cindex fields
+@cindex accessing fields
When @code{awk} reads an input record, the record is
automatically separated or @dfn{parsed} by the interpreter into pieces
called @dfn{fields}. By default, fields are separated by whitespace,
@@ -1501,8 +1420,8 @@ operate on the whole record if you wish---but fields are what make
simple @code{awk} programs so powerful.
@cindex @code{$} (field operator)
-@cindex Operators, @code{$}
-To refer to a field in an @code{awk} program, you use a dollar--sign,
+@cindex operators, @code{$}
+To refer to a field in an @code{awk} program, you use a dollar-sign,
@samp{$}, followed by the number of the field you want. Thus, @code{$1}
refers to the first field, @code{$2} to the second, and so on. For
example, suppose the following is a line of input:@refill
@@ -1518,7 +1437,6 @@ Here the first field, or @code{$1}, is @samp{This}; the second field, or
@samp{e} and the @samp{.}, the period is considered part of the seventh
field.@refill
-@cindex @code{$NF}, last field in record
No matter how many fields there are, the last field in a record can be
represented by @code{$NF}. So, in the example above, @code{$NF} would
be the same as @code{$7}, which is @samp{example.}. Why this works is
@@ -1527,8 +1445,8 @@ field beyond the last one, such as @code{$8} when the record has only 7
fields, you get the empty string.
@vindex NF
-@cindex Number of fields, @code{NF}
-Plain @code{NF}, with no @samp{$}, is a special variable whose value
+@cindex number of fields, @code{NF}
+Plain @code{NF}, with no @samp{$}, is a built-in variable whose value
is the number of fields in the current record.
@code{$0}, which looks like an attempt to refer to the zeroth field, is
@@ -1542,10 +1460,11 @@ awk '$1 ~ /foo/ @{ print $0 @}' BBS-list
@end example
@noindent
-This example contains the @dfn{matching} operator @code{~}
-(@pxref{Comparison Ops}). Using this operator, all records in the file
-@file{BBS-list} whose first field contains the string @samp{foo} are
-printed.@refill
+This example prints each record in the file @file{BBS-list} whose first
+field contains the string @samp{foo}. The operator @samp{~} is called a
+@dfn{matching operator} (@pxref{Comparison Ops}); it tests whether a
+string (here, the field @code{$1}) contains a match for a given regular
+expression.@refill
By contrast, the following example:
@@ -1554,30 +1473,18 @@ awk '/foo/ @{ print $1, $NF @}' BBS-list
@end example
@noindent
-looks for the string @samp{foo} in @emph{the entire record} and prints
-the first field and the last field for each input record containing the
-pattern.@refill
-
-The following program will search the system password file, and print
-the entries for users who have no password.
-
-@example
-awk -F: '$2 == ""' /etc/passwd
-@end example
-
-@noindent
-This program uses the @samp{-F} option on the command line to set the
-file separator. (Fields in @file{/etc/passwd} are separated by colons.
-The second field represents a user's encrypted password, but if the
-field is empty, that user has no password.)
+looks for @samp{foo} in @emph{the entire record} and prints the first
+field and the last field for each input record containing a
+match.@refill
@node Non-Constant Fields, Changing Fields, Fields, Reading Files
@section Non-constant Field Numbers
The number of a field does not need to be a constant. Any expression in
the @code{awk} language can be used after a @samp{$} to refer to a
-field. The @code{awk} utility evaluates the expression and uses the
-@dfn{numeric value} as a field number. Consider this example:@refill
+field. The value of the expression specifies the field number. If the
+value is a string, rather than a number, it is converted to a number.
+Consider this example:@refill
@example
awk '@{ print $NR @}'
@@ -1585,11 +1492,10 @@ awk '@{ print $NR @}'
@noindent
Recall that @code{NR} is the number of records read so far: 1 in the
-first record, 2 in the second, etc. So this example will print the
-first field of the first record, the second field of the second record,
-and so on. For the twentieth record, field number 20 will be printed;
-most likely this will make a blank line, because the record will not
-have 20 fields.
+first record, 2 in the second, etc. So this example prints the first
+field of the first record, the second field of the second record, and so
+on. For the twentieth record, field number 20 is printed; most likely,
+the record has fewer than 20 fields, so this prints a blank line.
Here is another example of using expressions as field numbers:
@@ -1597,32 +1503,30 @@ Here is another example of using expressions as field numbers:
awk '@{ print $(2*2) @}' BBS-list
@end example
-The @code{awk} language must evaluate the expression @samp{(2*2)} and use
-its value as the field number to print. The @samp{*} sign represents
-multiplication, so the expression @samp{2*2} evaluates to 4. This example,
-then, prints the hours of operation (the fourth field) for every line of the
-file @file{BBS-list}.@refill
-
-@cindex Fields, negative-numbered
-@cindex Negative-numbered fields
-When you use non--constant field numbers, you may ask for a field
-with a negative number. This always results in an empty string, just
-like a field whose number is too large for the input record. For
-example, @samp{$(1-4)} would try to examine field number -3; it would
-result in an empty string.
+The @code{awk} language must evaluate the expression @code{(2*2)} and use
+its value as the number of the field to print. The @samp{*} sign
+represents multiplication, so the expression @code{2*2} evaluates to 4.
+The parentheses are used so that the multiplication is done before the
+@samp{$} operation; they are necessary whenever there is a binary
+operator in the field-number expression. This example, then, prints the
+hours of operation (the fourth field) for every line of the file
+@file{BBS-list}.@refill
If the field number you compute is zero, you get the entire record.
+Thus, @code{$(2-2)} has the same value as @code{$0}. Negative field
+numbers are not allowed.
-The number of fields in the current record is stored in the special variable
-@code{NF} (@pxref{Special}). The expression @samp{$NF} is not a special
-feature: it is the direct consequence of evaluating @code{NF} and using
-its value as a field number.
+The number of fields in the current record is stored in the built-in
+variable @code{NF} (@pxref{Built-in Variables}). The expression
+@code{$NF} is not a special feature: it is the direct consequence of
+evaluating @code{NF} and using its value as a field number.
@node Changing Fields, Field Separators, Non-Constant Fields, Reading Files
@section Changing the Contents of a Field
-@cindex Field, changing contents of
-@cindex Changing contents of a field
+@cindex field, changing contents of
+@cindex changing contents of a field
+@cindex assignment to fields
You can change the contents of a field as seen by @code{awk} within an
@code{awk} program; this changes what @code{awk} perceives as the
current input record. (The actual input is untouched: @code{awk} never
@@ -1637,18 +1541,18 @@ awk '@{ $3 = $2 - 10; print $2, $3 @}' inventory-shipped
@noindent
The @samp{-} sign represents subtraction, so this program reassigns
field three, @code{$3}, to be the value of field two minus ten,
-@samp{@code{$2} - 10}. (@xref{Arithmetic Ops}.) Then field two, and the
+@code{$2 - 10}. (@xref{Arithmetic Ops}.) Then field two, and the
new value for field three, are printed.
In order for this to work, the text in field @code{$2} must make sense
as a number; the string of characters must be converted to a number in
order for the computer to do arithmetic on it. The number resulting
from the subtraction is converted back to a string of characters which
-then becomes field 3. @xref{Conversion}.
+then becomes field three. @xref{Conversion}.
When you change the value of a field (as perceived by @code{awk}), the
text of the input record is recalculated to contain the new field where
-the old one was. @code{$0} will from that time on reflect the altered
+the old one was. Therefore, @code{$0} changes to reflect the altered
field. Thus,
@example
@@ -1656,35 +1560,38 @@ awk '@{ $2 = $2 - 10; print $0 @}' inventory-shipped
@end example
@noindent
-will print a copy of the input file, with 10 subtracted from the second
+prints a copy of the input file, with 10 subtracted from the second
field of each line.
You can also assign contents to fields that are out of range. For
example:
@example
-awk '@{ $6 = ($5 + $4 + $3 + $2)/4) ; print $6 @}' inventory-shipped
+awk '@{ $6 = ($5 + $4 + $3 + $2) ; print $6 @}' inventory-shipped
@end example
@noindent
-We've just created @code{$6}, whose value is the average of fields
-@code{$2}, @code{$3}, @code{$4}, and @code{$5}. The @samp{+} sign represents
-addition, and the @samp{/} sign represents division. For the file
-@file{inventory-shipped} @code{$6} represents the average number of parcels
-shipped for a particular month.
+We've just created @code{$6}, whose value is the sum of fields
+@code{$2}, @code{$3}, @code{$4}, and @code{$5}. The @samp{+} sign
+represents addition. For the file @file{inventory-shipped}, @code{$6}
+represents the total number of parcels shipped for a particular month.
+
+Creating a new field changes the internal @code{awk} copy of the current
+input record---the value of @code{$0}. Thus, if you do @samp{print $0}
+after adding a field, the record printed includes the new field, with
+the appropriate number of field separators between it and the previously
+existing fields.
-Creating a new field changes what @code{awk} interprets as the current
-input record. The value of @code{$0} will be recomputed. This
-recomputation affects and is affected by features not yet discussed, in
-particular, the @dfn{Output Field Separator}, @code{OFS}, which is used
-to separate the fields (@pxref{Output Separators}), and @code{NF} (the
-number of fields; @pxref{Fields}). For example, the value of @code{NF}
-will be set to the number of the highest out--of--range field you
+This recomputation affects and is affected by several features not yet
+discussed, in particular, the @dfn{output field separator}, @code{OFS},
+which is used to separate the fields (@pxref{Output Separators}), and
+@code{NF} (the number of fields; @pxref{Fields}). For example, the
+value of @code{NF} is set to the number of the highest field you
create.@refill
-Note, however, that merely @emph{referencing} an out--of--range field
-will @emph{not} change the value of either @code{$0} or @code{NF}.
-Referencing an out--of--range field merely produces a null string. For
+Note, however, that merely @emph{referencing} an out-of-range field
+does @emph{not} change the value of either @code{$0} or @code{NF}.
+Referencing an out-of-range field merely produces a null string. For
example:@refill
@example
@@ -1695,71 +1602,92 @@ else
@end example
@noindent
-should print @samp{everything is normal}. (@xref{If}, for more
-information about @code{awk}'s @samp{if-else} statements.)
+should print @samp{everything is normal}, because @code{NF+1} is certain
+to be out of range. (@xref{If Statement}, for more information about
+@code{awk}'s @code{if-else} statements.)
-@node Field Separators, Multiple, Changing Fields, Reading Files
+@node Field Separators, Multiple Line, Changing Fields, Reading Files
@section Specifying How Fields Are Separated
-
@vindex FS
-@cindex Fields, semantics of
-@cindex Fields, separating
-@cindex Field separator, @code{FS}
-You can change the way @code{awk} splits a record into fields by changing the
-value of the @dfn{field separator}. The field separator is represented by
-the special variable @code{FS} in an @code{awk} program, and can be set
-by @samp{-F} on the command line. The @code{awk} language scans each input
-line for the field separator character to determine the positions of fields
-within that line. Shell programmers take note! @code{awk} uses the variable
-@code{FS}, not @code{IFS}.@refill
-
-The default value of the field separator is a string containing a single
-space. This value is actually a special case; as you know, by default, fields
-are separated by whitespace sequences, not by single spaces: two spaces
-in a row do not delimit an empty field. ``Whitespace'' is defined as sequences
-of one or more spaces or tab characters.
-
-You change the value of @code{FS} by @dfn{assigning} it a new value. You
-can do this using the special @code{BEGIN} pattern (@pxref{BEGIN/END}).
-This pattern allows you to change the value of @code{FS} before any input is
-read. The new value of @code{FS} is enclosed in quotations. For example,
-set the value of @code{FS} to the string @samp{","}:
+@cindex fields, separating
+@cindex field separator, @code{FS}
+@cindex @samp{-F} option
+
+The way @code{awk} splits an input record into fields is controlled by
+the @dfn{field separator}, which is a regular expression. @code{awk}
+scans the input record for matches for this regular expression; these
+matches separate fields. The fields themselves are the text between the
+matches. For example, if the field separator is @samp{oo}, then the
+following line:
+
+@example
+moo goo gai pan
+@end example
+
+@noindent
+would be split into three fields: @samp{m}, @samp{@ g} and @samp{@ gai@
+pan}.
+
+The field separator is represented by the built-in variable @code{FS}.
+Shell programmers take note! @code{awk} does not use the name
+@code{IFS} which is used by the shell.@refill
+
+You can change the value of @code{FS} in the @code{awk} program with the
+assignment operator, @samp{=} (@pxref{Assignment Ops}). Often the right
+time to do this is at the beginning of execution, before any input has
+been processed, so that the very first record will be read with the
+proper separator. To do this, use the special @code{BEGIN} pattern
+(@pxref{BEGIN/END}). For example, here we set the value of @code{FS} to
+the string @code{","}:
@example
awk 'BEGIN @{ FS = "," @} ; @{ print $2 @}'
@end example
@noindent
-and use the input line:@refill
+Given the input line,
@example
John Q. Smith, 29 Oak St., Walamazoo, MI 42139
@end example
@noindent
-This @code{awk} program will extract the string @samp{29 Oak St.}.
+this @code{awk} program extracts the string @samp{29 Oak St.}.
-@cindex Separator character, choice of
-@cindex Field separator, choice of
-@cindex Regular expressions, field separators and
+@cindex field separator, choice of
+@cindex regular expressions as field separators
Sometimes your input data will contain separator characters that don't
-separate fields the way you thought they would. For instance, the person's
-name in the example we've been using might have a title or suffix attached,
-such as @samp{John Q. Smith, LXIX}. If you assigned @code{FS} to be
-@samp{,} then:
+separate fields the way you thought they would. For instance, the
+person's name in the example we've been using might have a title or
+suffix attached, such as @samp{John Q. Smith, LXIX}. From input
+containing such a name:
@example
-awk 'BEGIN @{ FS = "," @} ; @{ print $2 @}
+John Q. Smith, LXIX, 29 Oak St., Walamazoo, MI 42139
@end example
@noindent
-would extract @samp{LXIX}, instead of @samp{29 Oak St.}. If you were
-expecting the program to print the address, you would be surprised. So,
-choose your data layout and separator characters carefully to prevent
-problems like this from happening.@refill
+the previous sample program would extract @samp{LXIX}, instead of
+@samp{29 Oak St.}. If you were expecting the program to print the
+address, you would be surprised. So choose your data layout and
+separator characters carefully to prevent such problems.
-You can assign @code{FS} to be a series of characters. For example, the
-assignment:@refill
+As you know, by default, fields are separated by whitespace sequences
+(spaces and tabs), not by single spaces: two spaces in a row do not
+delimit an empty field. The default value of the field separator is a
+string @w{@code{" "}} containing a single space. If this value were
+interpreted in the usual way, each space character would separate
+fields, so two spaces in a row would make an empty field between them.
+The reason this does not happen is that a single space as the value of
+@code{FS} is a special case: it is taken to specify the default manner
+of delimiting fields.
+
+If @code{FS} is any other single character, such as @code{","}, then two
+successive occurrences of that character do delimit an empty field. The
+space character is the only special case.
+
+You can set @code{FS} to be a string containing several characters. For
+example, the assignment:@refill
@example
FS = ", \t"
@@ -1770,16 +1698,15 @@ makes every area of an input line that consists of a comma followed by a
space and a tab, into a field separator. (@samp{\t} stands for a
tab.)@refill
-If @code{FS} is any single character other than a blank, then that character
-is used as the field separator, and two successive occurrences of that
-character do delimit an empty field.
-
-If you assign @code{FS} to a string longer than one character, that string
-is evaluated as a @dfn{regular expression} (@pxref{Regexp}). The value of
-the regular expression is used as a field separator.
+More generally, the value of @code{FS} may be a string containing any
+regular expression. Then each match in the record for the regular
+expression separates fields. For example, if you want single spaces to
+separate fields the way single commas were used above, you can set
+@code{FS} to @w{@code{"[@ ]"}}. This regular expression matches a single
+space and nothing else.
-@cindex Field separator, setting on command line
-@cindex Command line, setting @code{FS} on
+@cindex field separator, setting on command line
+@cindex command line, setting @code{FS} on
@code{FS} can be set on the command line. You use the @samp{-F} argument to
do so. For example:
@@ -1795,34 +1722,33 @@ the @samp{-F} and @samp{-f} options have nothing to do with each other.
You can use both options at the same time to set the @code{FS} argument
@emph{and} get an @code{awk} program from a file.
-As a special case, if the argument to @samp{-F} is @samp{t}, then @code{FS}
-is set to the tab character. (This is because if you type @samp{-F\t},
-without the quotes, at the shell, the @samp{\} gets deleted, so @code{awk}
-figures that you really want your fields to be separated with tabs, and
-not @samp{t}s. Use @code{FS="t"} if you really do want to separate your
-fields with @samp{t}s.)
+As a special case, in compatibility mode (@pxref{Command Line}), if the
+argument to @samp{-F} is @samp{t}, then @code{FS} is set to the tab
+character. (This is because if you type @samp{-F\t}, without the quotes,
+at the shell, the @samp{\} gets deleted, so @code{awk} figures that you
+really want your fields to be separated with tabs, and not @samp{t}s.
+Use @samp{FS="t"} on the command line if you really do want to separate
+your fields with @samp{t}s.)
For example, let's use an @code{awk} program file called @file{baud.awk}
-that contains the pattern @samp{/300/}, and the action @samp{print $1}.
-We'll use the operating system utility @code{cat} to ``look'' at our
-program:@refill
+that contains the pattern @code{/300/}, and the action @samp{print $1}.
+Here is the program:
@example
-% cat baud.awk
/300/ @{ print $1 @}
@end example
-Let's also set @code{FS} to be the @samp{-} character. We will apply
-all this information to the file @file{BBS-list}. This @code{awk} program
-will now print a list of the names of the bulletin boards that operate at
-300 baud and the first three digits of their phone numbers.@refill
+Let's also set @code{FS} to be the @samp{-} character, and run the
+program on the file @file{BBS-list}. The following command prints a
+list of the names of the bulletin boards that operate at 300 baud and
+the first three digits of their phone numbers:@refill
@example
awk -F- -f baud.awk BBS-list
@end example
@noindent
-produces this output:
+It produces this output:
@example
aardvark 555
@@ -1851,154 +1777,138 @@ separator, instead of the @samp{-} in the phone number that was
originally intended. This demonstrates why you have to be careful in
choosing your field and record separators.
-@node Multiple, Assignment Options, Field Separators, Reading Files
-@section Multiple--Line Records
+The following program searches the system password file, and prints
+the entries for users who have no password:
-@cindex Multiple line records
-@cindex Input, multiple line records
-@cindex Reading files, multiple line records
-@cindex Records, multiple line
-In some data bases, a single line cannot conveniently hold all the information
-in one entry. Then you will want to use multi--line records.
+@example
+awk -F: '$2 == ""' /etc/passwd
+@end example
+
+@noindent
+Here we use the @samp{-F} option on the command line to set the field
+separator. Note that fields in @file{/etc/passwd} are separated by
+colons. The second field represents a user's encrypted password, but if
+the field is empty, that user has no password.
+
+@node Multiple Line, Getline, Field Separators, Reading Files
+@section Multiple-Line Records
+
+@cindex multiple line records
+@cindex input, multiple line records
+@cindex reading files, multiple line records
+@cindex records, multiple line
+In some data bases, a single line cannot conveniently hold all the
+information in one entry. In such cases, you can use multi-line
+records.
The first step in doing this is to choose your data format: when records
-are not defined as single lines, how will you want to define them?
+are not defined as single lines, how do you want to define them?
What should separate records?
One technique is to use an unusual character or string to separate
records. For example, you could use the formfeed character (written
@samp{\f} in @code{awk}, as in C) to separate them, making each record
a page of the file. To do this, just set the variable @code{RS} to
-@code{"\f"} (a string containing the formfeed character), or whatever
-string you prefer to use.
+@code{"\f"} (a string containing the formfeed character). Any
+other character could equally well be used, as long as it won't be part
+of the data in a record.
@ignore
Another technique is to have blank lines separate records. The string
@code{"^\n+"} is a regular expression that matches any sequence of
newlines starting at the beginning of a line---in other words, it
matches a sequence of blank lines. If you set @code{RS} to this string,
-a record will always end at the first blank line encountered. In
+a record always ends at the first blank line encountered. In
addition, a regular expression always matches the longest possible
-sequence when there is a choice. So the next record won't start until
+sequence when there is a choice. So the next record doesn't start until
the first nonblank line that follows---no matter how many blank lines
-appear in a row, they will be consider one record--separator.
+appear in a row, they are considered one record-separator.
@end ignore
-Another technique is to have blank lines separate records.
-By a special dispensation, a null string as the value of @code{RS}
-indicates that records are separated by one or more blank lines.
-If you set @code{RS} to the null string,
-a record will always end at the first blank line encountered.
-And the next record won't start until
-the first nonblank line that follows---no matter how many blank lines
-appear in a row, they will be considered one record--separator.@refill
-
-The second step is to separate the fields in the record. One way to
-do this is to put each field on a separate line: to do this, just set
-the variable @code{FS} to the string @code{"\n"}. (This
-simple regular expression matches a single newline.) Another idea is to
-divide each of the lines into fields in the normal manner; the regular
-expression @w{@code{"[ \t\n]+"}} will do this nicely by treating the newlines
-inside the record just like spaces.@refill
-
-When @code{RS} is set to the null string, the newline character @emph{always}
-acts as a field separator. This is in addition to whatever value @code{FS}
-has. The probable reason for this rule is so that you get rational
-behavior in the default case (i.e. @w{@code{FS == " "}}). This can be
-a problem if you really don't want the newline character to separate
-fields, since there is no way to do that. However, you can work around this
-by using the @code{split} function to manually break up your data
-(@pxref{String Functions}).
+Another technique is to have blank lines separate records. By a special
+dispensation, a null string as the value of @code{RS} indicates that
+records are separated by one or more blank lines. If you set @code{RS}
+to the null string, a record always ends at the first blank line
+encountered. And the next record doesn't start until the first nonblank
+line that follows---no matter how many blank lines appear in a row, they
+are considered one record-separator.
+
+The second step is to separate the fields in the record. One way to do
+this is to put each field on a separate line: to do this, just set the
+variable @code{FS} to the string @code{"\n"}. (This simple regular
+expression matches a single newline.)
+
+Another idea is to divide each of the lines into fields in the normal
+manner. This happens by default as a result of a special feature: when
+@code{RS} is set to the null string, the newline character @emph{always}
+acts as a field separator. This is in addition to whatever field
+separations result from @code{FS}.
+
+The original motivation for this special exception was probably so that
+you get useful behavior in the default case (i.e., @w{@code{FS == "
+"}}). This feature can be a problem if you really don't want the
+newline character to separate fields, since there is no way to
+prevent it. However, you can work around this by using the @code{split}
+function to break up the record manually (@pxref{String Functions}).
@ignore
Here are two ways to use records separated by blank lines and break each
line into fields normally:
@example
-awk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} @{ print $0 @}' BBS-list
+awk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} @{ print $1 @}' BBS-list
@exdent @r{or}
-awk 'BEGIN @{ RS = "^\n+"; FS = "[ \t\n]+" @} @{ print $0 @}' BBS-list
+awk 'BEGIN @{ RS = "^\n+"; FS = "[ \t\n]+" @} @{ print $1 @}' BBS-list
@end example
@end ignore
+@ignore
Here is how to use records separated by blank lines and break each
line into fields normally:
@example
-awk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} ; @{ print $0 @}' BBS-list
-@end example
-
-@node Assignment Options, Getline, Multiple, Reading Files
-@section Assigning Variables on the Command Line
-
-You can include variable @dfn{assignments} among the file names on the
-command line used to invoke @code{awk} (@pxref{Command Line}). Such
-assignments have the form:
-
-@example
-@var{variable}=@var{text}
-@end example
-
-@noindent
-and allow you to change variables either at the beginning of the
-@code{awk} run or in between input files. The variable assignment is
-performed at a time determined by its position among the input file
-arguments: after the processing of the preceding input file argument.
-For example:
-
-@example
-awk '@{ print $n @}' n=4 inventory-shipped n=2 BBS-list
+awk 'BEGIN @{ RS = ""; FS = "[ \t\n]+" @} ; @{ print $1 @}' BBS-list
@end example
+@end ignore
-@noindent
-prints the value of field number @code{n} for all input records. Before
-the first file is read, the command line sets the variable @code{n}
-equal to 4. This causes the fourth field of the file
-@file{inventory-shipped} to be printed. After the first file has
-finished, but before the second file is started, @code{n} is set to 2,
-so that the second field of the file @file{BBS-list} will be printed.
-
-Command line arguments are made available for explicit examination by
-the @code{awk} program in an array named @code{ARGV} (@pxref{Special}).
-
-@node Getline, , Assignment Options, Reading Files
+@node Getline, Close Input, Multiple Line, Reading Files
@section Explicit Input with @code{getline}
@findex getline
-@cindex Input, @code{getline} function
-@cindex Reading files, @code{getline} function
+@cindex input, explicit
+@cindex explicit input
+@cindex input, @code{getline} command
+@cindex reading files, @code{getline} command
So far we have been getting our input files from @code{awk}'s main
input stream---either the standard input (usually your terminal) or the
files specified on the command line. The @code{awk} language has a
-special built--in function called @code{getline} that
+special built-in command called @code{getline} that
can be used to read input under your explicit control.
This command is quite complex and should @emph{not} be used by
-beginners. The command (and its variations) is covered here because
-this is the section about input. The examples that follow the
-explanation of the @code{getline} command include material that has not
-been covered yet. Therefore, come back and attempt the @code{getline}
-command @emph{after} you have reviewed the rest of this manual and have
-a good knowledge of how @code{awk} works.
-
-When retrieving input, @code{getline} returns a 1 if it found a record, and
-a 0 if the end of the file was encountered. If there was some error in
-getting a record, such as a file that could not be opened, then @code{getline}
-returns a -1.
+beginners. It is covered here because this is the chapter on input.
+The examples that follow the explanation of the @code{getline} command
+include material that has not been covered yet. Therefore, come back
+and study the @code{getline} command @emph{after} you have reviewed the
+rest of this manual and have a good knowledge of how @code{awk} works.
+
+@code{getline} returns 1 if it finds a record, and 0 if the end of the
+file is encountered. If there is some error in getting a record, such
+as a file that cannot be opened, then @code{getline} returns @minus{}1.
In the following examples, @var{command} stands for a string value that
represents a shell command.
@table @code
@item getline
-The @code{getline} function can be used by itself, in an @code{awk}
-program, to read input from the current input. All it does in this
-case is read the next input record and split it up into fields. This
-is useful if you've finished processing the current record, but you
-want to do some special processing @emph{right now} on the next
-record. Here's an example:@refill
+The @code{getline} command can be used without arguments to read input
+from the current input file. All it does in this case is read the next
+input record and split it up into fields. This is useful if you've
+finished processing the current record, but you want to do some special
+processing @emph{right now} on the next record. Here's an
+example:@refill
@example
awk '@{
@@ -2025,31 +1935,32 @@ awk '@{
This @code{awk} program deletes all comments, @samp{/* @dots{}
*/}, from the input. By replacing the @samp{print $0} with other
statements, you could perform more complicated processing on the
-de--commented input, such as search it for matches for a regular
+decommented input, such as searching it for matches for a regular
expression.
This form of the @code{getline} command sets @code{NF} (the number of
-fields; @pxref{Fields}), @code{NR} (the number of records read so far), the
-@code{FNR} variable (@pxref{Records}), and the value of @code{$0}.
+fields; @pxref{Fields}), @code{NR} (the number of records read so far;
+@pxref{Records}), @code{FNR} (the number of records read from this input
+file), and the value of @code{$0}.
-@emph{Note:} The new value of @code{$0} will be used in testing
-the patterns of any subsequent rules. The original value
+@strong{Note:} the new value of @code{$0} is used in testing
+the patterns of any subsequent rules. The original value
of @code{$0} that triggered the rule which executed @code{getline}
is lost. By contrast, the @code{next} statement reads a new record
but immediately begins processing it normally, starting with the first
-rule in the program. @xref{Next}.
+rule in the program. @xref{Next Statement}.
@item getline @var{var}
This form of @code{getline} reads a record into the variable @var{var}.
-This is useful when you want your program to read the next record from the
-input file, but you don't want to subject the record to the normal input
-processing.
+This is useful when you want your program to read the next record from
+the current input file, but you don't want to subject the record to the
+normal input processing.
For example, suppose the next line is a comment, or a special string,
-and you want to read it, but you must make certain that it won't
-accidentally trigger any rules. This version of @code{getline} will
-allow you to read that line and store it in a variable so that the main
-read--a--line--and--check--each--rule loop of @code{awk} never sees it.
+and you want to read it, but you must make certain that it won't trigger
+any rules. This version of @code{getline} allows you to read that line
+and store it in a variable so that the main
+read-a-line-and-check-each-rule loop of @code{awk} never sees it.
The following example swaps every two lines of input. For example, given:
@@ -2083,15 +1994,18 @@ awk '@{
@}'
@end example
-The @code{getline} function used in this way sets only @code{NR} and
-@code{FNR} (and of course, @var{var}). The record is not split into fields,
-so the values of the fields (including @code{$0}) and the value of @code{NF}
-do not change.@refill
+The @code{getline} function used in this way sets only the variables
+@code{NR} and @code{FNR} (and of course, @var{var}). The record is not
+split into fields, so the values of the fields (including @code{$0}) and
+the value of @code{NF} do not change.@refill
@item getline < @var{file}
+@cindex input redirection
+@cindex redirection of input
This form of the @code{getline} function takes its input from the file
-@var{file}. Here @var{file} is a string--valued expression that
-specifies the file name.
+@var{file}. Here @var{file} is a string-valued expression that
+specifies the file name. @samp{< @var{file}} is called a @dfn{redirection}
+since it directs input to come from a different place.
This form is useful if you want to read your input from a particular
file, instead of from the main input stream. For example, the following
@@ -2123,14 +2037,14 @@ the new record is tested against any subsequent rules, just as when
@item getline @var{var} < @var{file}
This form of the @code{getline} function takes its input from the file
@var{file} and puts it in the variable @var{var}. As above, @var{file}
-is a string--valued expression that specifies the file to read from.
+is a string-valued expression that specifies the file to read from.
-In this version of @code{getline}, none of the built--in variables are
+In this version of @code{getline}, none of the built-in variables are
changed, and the record is not split into fields. The only variable
changed is @var{var}.
For example, the following program copies all the input files to the
-output, except for records that say @w{@code{@@include @var{filename}}}.
+output, except for records that say @w{@samp{@@include @var{filename}}}.
Such a record is replaced by the contents of the file
@var{filename}.@refill
@@ -2149,7 +2063,7 @@ Note here how the name of the extra input file is not built into
the program; it is taken from the data, from the second field on
the @samp{@@include} line.
-The @code{close} command is used to ensure that if two identical
+The @code{close} function is called to ensure that if two identical
@samp{@@include} lines appear in the input, the entire specified file is
included twice. @xref{Close Input}.
@@ -2180,9 +2094,9 @@ awk '@{
@end example
@noindent
-The @code{close} command is used to ensure that if two identical
-@samp{@@execute} lines appear in the input, the command is run again
-for each one. @xref{Close Input}.
+The @code{close} function is called to ensure that if two identical
+@samp{@@execute} lines appear in the input, the command is run again for
+each one. @xref{Close Input}.
Given the input:
@@ -2235,43 +2149,61 @@ awk 'BEGIN @{
@end example
@end group
-In this version of @code{getline}, none of the built--in variables are
+In this version of @code{getline}, none of the built-in variables are
changed, and the record is not split into fields.
@end table
-@node Close Input, , , Getline
-@subsection Closing Input Files
-@cindex @code{close} statement for input
+@node Close Input,, Getline, Reading Files
+@section Closing Input Files and Pipes
+@cindex closing input files and pipes
+@findex close
If the same file name or the same shell command is used with
-@code{getline} more than once during the execution of the @code{awk}
+@code{getline} more than once during the execution of an @code{awk}
program, the file is opened (or the command is executed) only the first time.
At that time, the first record of input is read from that file or command.
The next time the same file or command is used in @code{getline}, another
record is read from it, and so on.
-What this implies is that if you want to start reading the same file
-again from the beginning, or if you want to rerun a shell command
-(rather that reading more output from the command), you must take
-special steps. What you can do is use the @code{close} statement:
+This implies that if you want to start reading the same file again from
+the beginning, or if you want to rerun a shell command (rather that
+reading more output from the command), you must take special steps.
+What you can do is use the @code{close} function, as follows:
+
+@example
+close(@var{filename})
+@end example
+
+@noindent
+or
@example
-close (@var{filename})
+close(@var{command})
+@end example
+
+The argument @var{filename} or @var{command} can be any expression. Its
+value must exactly equal the string that was used to open the file or
+start the command---for example, if you open a pipe with this:
+
+@example
+"sort -r names" | getline foo
@end example
@noindent
-This statement closes a file or pipe, represented here by
-@var{filename}. The string value of @var{filename} must be the same
-value as the string used to open the file or pipe to begin with.
+then you must close it with this:
-Once this statement is executed, the next @code{getline} from that file
-or command will reopen the file or rerun the command.
+@example
+close("sort -r names")
+@end example
+
+Once this function call is executed, the next @code{getline} from that
+file or command will reopen the file or rerun the command.
@node Printing, One-liners, Reading Files, Top
@chapter Printing Output
-@cindex Printing, general
-@cindex Output
+@cindex printing
+@cindex output
One of the most common things that actions do is to output or @dfn{print}
some or all of the input. For simple output, use the @code{print}
statement. For fancier formatting use the @code{printf} statement.
@@ -2281,14 +2213,13 @@ Both are described in this chapter.
* Print:: The @code{print} statement.
* Print Examples:: Simple examples of @code{print} statements.
* Output Separators:: The output separators and how to change them.
-
-* Redirection:: How to redirect output to multiple files and pipes.
-* Close Output:: How to close output files and pipes.
-
* Printf:: The @code{printf} statement.
+* Redirection:: How to redirect output to multiple files and pipes.
+* Special Files:: File name interpretation in @code{gawk}. @code{gawk}
+ allows access to inherited file descriptors.
@end menu
-@node Print, Print Examples, , Printing
+@node Print, Print Examples, Printing, Printing
@section The @code{print} Statement
@cindex @code{print} statement
@@ -2318,17 +2249,17 @@ print them---how many columns to use, whether to use exponential
notation or not, and so on. For that, you need the @code{printf}
statement (@pxref{Printf}).
-To print a fixed piece of text, write a string constant as one item,
-such as @w{@code{"Hello there"}}. If you forget to use the double--quote
-characters, your text will be taken as an @code{awk} expression, and
-you will probably get an error. Keep in mind that a space will be printed
-between any two items.
-
The simple statement @samp{print} with no items is equivalent to
@samp{print $0}: it prints the entire current record. To print a blank
line, use @samp{print ""}, where @code{""} is the null, or empty,
string.
+To print a fixed piece of text, use a string constant such as
+@w{@code{"Hello there"}} as one item. If you forget to use the
+double-quote characters, your text will be taken as an @code{awk}
+expression, and you will probably get an error. Keep in mind that a
+space is printed between any two items.
+
Most often, each @code{print} statement makes one line of output. But it
isn't limited to one line. If an item value is a string that contains a
newline, the newline is output along with the rest of the string. A
@@ -2337,6 +2268,21 @@ single @code{print} can make any number of lines this way.
@node Print Examples, Output Separators, Print, Printing
@section Examples of @code{print} Statements
+Here is an example of printing a string that contains embedded newlines:
+
+@example
+awk 'BEGIN @{ print "line one\nline two\nline three" @}'
+@end example
+
+@noindent
+produces output like this:
+
+@example
+line one
+line two
+line three
+@end example
+
Here is an example that prints the first two fields of each input record,
with a space between them:
@@ -2377,7 +2323,7 @@ Mar15
Neither example's output makes much sense to someone unfamiliar with the
file @file{inventory-shipped}. A heading line at the beginning would make
it clearer. Let's add some headings to our table of months (@code{$1}) and
-green crates shipped (@code{$2}). We do this using the BEGIN pattern
+green crates shipped (@code{$2}). We do this using the @code{BEGIN} pattern
(@pxref{BEGIN/END}) to cause the headings to be printed only once:
@c the formatting is strange here because the @{ becomes just a brace.
@@ -2388,7 +2334,7 @@ awk 'BEGIN @{ print "Month Crates"
@end example
@noindent
-Did you already guess what will happen? This program prints the following:
+Did you already guess what happens? This program prints the following:
@group
@example
@@ -2418,25 +2364,25 @@ or three columns can be simple, but more than this and you can get
created (@pxref{Printf}); one of its specialties is lining up columns of
data.
-@node Output Separators, Redirection, Print Examples, Printing
+@node Output Separators, Printf, Print Examples, Printing
@section Output Separators
-@cindex Output field separator, @code{OFS}
+@cindex output field separator, @code{OFS}
@vindex OFS
@vindex ORS
-@cindex Output record separator, @code{ORS}
+@cindex output record separator, @code{ORS}
As mentioned previously, a @code{print} statement contains a list
of items, separated by commas. In the output, the items are normally
separated by single spaces. But they do not have to be spaces; a
single space is only the default. You can specify any string of
-characters to use as the @dfn{output field separator}, by setting the
-special variable @code{OFS}. The initial value of this variable
+characters to use as the @dfn{output field separator} by setting the
+built-in variable @code{OFS}. The initial value of this variable
is the string @w{@code{" "}}.
The output from an entire @code{print} statement is called an
@dfn{output record}. Each @code{print} statement outputs one output
record and then outputs a string called the @dfn{output record separator}.
-The special variable @code{ORS} specifies this string. The initial
+The built-in variable @code{ORS} specifies this string. The initial
value of the variable is the string @code{"\n"} containing a newline
character; thus, normally each @code{print} statement makes a separate line.
@@ -2460,199 +2406,31 @@ If the value of @code{ORS} does not contain a newline, all your output
will be run together on a single line, unless you output newlines some
other way.
-@node Redirection, Printf, Output Separators, Printing
-@section Redirecting Output of @code{print} and @code{printf}
-
-@cindex Output redirection
-@cindex Redirection of output
-@cindex @code{>}
-@cindex @code{>>}
-@cindex @code{|}
-@ignore
-@strong{ADR: This section and the section on closing files and pipes should
-come @emph{after} the section on @code{printf}. @emph{First} describe
-all the options for output, and @emph{then} describe how to redirect
-the output.}
-@end ignore
-
-So far we have been dealing only with output that prints to the standard
-output, usually your terminal. Both @code{print} and @code{printf} can be
-told to send their output to other places. This is called
-@dfn{redirection}.@refill
-
-A redirection appears after the @code{print} or @code{printf} statement.
-Redirections in @code{awk} are written just like redirections in shell
-commands, except that they are written inside the @code{awk} program.
-
-Here are the three forms of output redirection. They are all shown for
-the @code{print} statement, but they work for @code{printf} also.
-
-@table @code
-@item print @var{items} > @var{output-file}
-This type of redirection prints the items onto the output file
-@var{output-file}. The file name @var{output-file} can be any
-expression. Its value is changed to a string and then used as a
-filename (@pxref{Expressions}).@refill
-
-When this type of redirection is used, the @var{output-file} is erased
-before the first output is written to it. Subsequent writes do not
-erase @var{output-file}, but append to it. If @var{output-file} does
-not exist, then it is created.@refill
-
-For example, here is how one @code{awk} program can write a list of
-BBS names to a file @file{name-list} and a list of phone numbers to a
-file @file{phone-list}. Each output file contains one name or number
-per line.
-
-@example
-awk '@{ print $2 > "phone-list"
- print $1 > "name-list" @}' BBS-list
-@end example
-
-@item print @var{items} >> @var{output-file}
-This type of redirection prints the items onto the output file
-@var{output-file}. The difference between this and the
-single--@samp{>} redirection is that the old contents (if any) of
-@var{output-file} are not erased. Instead, the @code{awk} output is
-appended to the file.
-
-@cindex Pipes for output
-@cindex Output, piping
-@item print @var{items} | @var{command}
-It is also possible to send output through a @dfn{pipe} instead of into a
-file. This type of redirection opens a pipe to @var{command} and writes
-the values of @var{items} through this pipe, to another process created
-to execute @var{command}.@refill
-
-The redirection argument @var{command} is actually an @code{awk}
-expression. Its value is converted to a string, whose contents give the
-shell command to be run.
-
-For example, this produces two files, one unsorted list of BBS names
-and one list sorted in reverse alphabetical order:
-
-@example
-awk '@{ print $1 > "names.unsorted"
- print $1 | "sort -r > names.sorted" @}' BBS-list
-@end example
-
-Here the unsorted list is written with an ordinary redirection while
-the sorted list is written by piping through the @code{sort} utility.
-
-Here is an example that uses redirection to mail a message to a mailing
-list @samp{bug-system}. This might be useful when trouble is encountered
-in an @code{awk} script run periodically for system maintenance.
-
-@example
-print "Awk script failed:", $0 | "mail bug-system"
-print "processing record number", FNR, "of", FILENAME | "mail bug-system"
-close ("mail bug-system")
-@end example
-
-We use a @code{close} statement here because it's a good idea to close
-the pipe as soon as all the intended output has been sent to it.
-@xref{Close Output}, for more information on this.
-@end table
-
-Redirecting output using @samp{>}, @samp{>>}, or @samp{|} asks the system
-to open a file or pipe only if the particular @var{file} or @var{command}
-you've specified has not already been written to by your program.@refill
-
-@node Close Output, , , Redirection
-@subsection Closing Output Files and Pipes
-@cindex @code{close} statement for output
-@cindex Closing files and pipes
-
-When a file or pipe is opened, the filename or command associated with
-it is remembered by @code{awk} and subsequent writes to the same file or
-command are appended to the previous writes. The file or pipe stays
-open until @code{awk} exits. This is usually convenient.
-
-Sometimes there is a reason to close an output file or pipe earlier
-than that. To do this, use the @code{close} command, as follows:
-
-@example
-close (@var{filename})
-@end example
-
-@noindent
-or
-
-@example
-close (@var{command})
-@end example
-
-The argument @var{filename} or @var{command} can be any expression.
-Its value must exactly equal the string used to open the file or pipe
-to begin with---for example, if you open a pipe with this:
-
-@example
-print $1 | "sort -r > names.sorted"
-@end example
-
-@noindent
-then you must close it with this:
-
-@example
-close ("sort -r > names.sorted")
-@end example
-
-Here are some reasons why you might need to close an output file:
-
-@itemize @bullet
-@item
-To write a file and read it back later on in the same @code{awk}
-program. Close the file when you are finished writing it; then
-you can start reading it with @code{getline} (@pxref{Getline}).
-
-@item
-To write numerous files, successively, in the same @code{awk}
-program. If you don't close the files, eventually you will exceed the
-system limit on the number of open files in one process. So close
-each one when you are finished writing it.
-
-@item
-To make a command finish. When you redirect output through a pipe,
-the command reading the pipe normally continues to try to read input
-as long as the pipe is open. Often this means the command cannot
-really do its work until the pipe is closed. For example, if you
-redirect output to the @code{mail} program, the message will not
-actually be sent until the pipe is closed.
-
-@item
-To run the same subprogram a second time, with the same arguments.
-This is not the same thing as giving more input to the first run!
-
-For example, suppose you pipe output to the @code{mail} program. If you
-output several lines redirected to this pipe without closing it, they make
-a single message of several lines. By contrast, if you close the pipe
-after each line of output, then each line makes a separate message.
-@end itemize
-
-@node Printf, , Redirection, Printing
+@node Printf, Redirection, Output Separators, Printing
@section Using @code{printf} Statements For Fancier Printing
-@cindex Formatted output
-@cindex Output, formatted
+@cindex formatted output
+@cindex output, formatted
If you want more precise control over the output format than
@code{print} gives you, use @code{printf}. With @code{printf} you can
specify the width to use for each item, and you can specify various
stylistic choices for numbers (such as what radix to use, whether to
print an exponent, whether to print a sign, and how many digits to print
-after the decimal point). You do this by specifying a @dfn{format
-string}.
+after the decimal point). You do this by specifying a string, called
+the @dfn{format string}, which controls how and where to print the other
+arguments.
@menu
* Basic Printf:: Syntax of the @code{printf} statement.
-* Format-Control:: Format-control letters.
-* Modifiers:: Format--specification modifiers.
+* Control Letters:: Format-control letters.
+* Format Modifiers:: Format-specification modifiers.
* Printf Examples:: Several examples.
@end menu
-@node Basic Printf, Format-Control, , Printf
+@node Basic Printf, Control Letters, Printf, Printf
@subsection Introduction to the @code{printf} Statement
-@cindex @code{printf} statement, format of
+@cindex @code{printf} statement, syntax of
The @code{printf} statement looks like this:@refill
@example
@@ -2667,7 +2445,7 @@ relational operator; otherwise it could be confused with a redirection
@samp{!=}, @samp{<}, @samp{>}, @samp{>=}, @samp{<=}, @samp{~} and
@samp{!~} (@pxref{Comparison Ops}).@refill
-@cindex Format string
+@cindex format string
The difference between @code{printf} and @code{print} is the argument
@var{format}. This is an expression whose value is taken as a string; its
job is to say how to output each of the other arguments. It is called
@@ -2685,20 +2463,19 @@ a newline, you must include one in the format. The output separator
variables @code{OFS} and @code{ORS} have no effect on @code{printf}
statements.
-@node Format-Control, Modifiers, Basic Printf, Printf
-@subsection Format--Control Characters
+@node Control Letters, Format Modifiers, Basic Printf, Printf
+@subsection Format-Control Letters
@cindex @code{printf}, format-control characters
+@cindex format specifier
-
-@cindex Format specifier
A format specifier starts with the character @samp{%} and ends with a
-@dfn{format--control letter}; it tells the @code{printf} statement how
+@dfn{format-control letter}; it tells the @code{printf} statement how
to output one item. (If you actually want to output a @samp{%}, write
-@samp{%%}.) The format--control letter specifies what kind of value to
+@samp{%%}.) The format-control letter specifies what kind of value to
print. The rest of the format specifier is made up of optional
@dfn{modifiers} which are parameters such as the field width to use.
-Here is a list of them:
+Here is a list of the format-control letters:
@table @samp
@item c
@@ -2709,6 +2486,9 @@ the first character of the string.
@item d
This prints a decimal integer.
+@item i
+This also prints a decimal integer.
+
@item e
This prints a number in scientific (exponential) notation.
For example,
@@ -2738,46 +2518,78 @@ This prints a string.
@item x
This prints an unsigned hexadecimal integer.
+@item X
+This prints an unsigned hexadecimal integer. However, for the values 10
+through 15, it uses the letters @samp{A} through @samp{F} instead of
+@samp{a} through @samp{f}.
+
@item %
-This isn't really a format--control letter, but it does have a meaning
+This isn't really a format-control letter, but it does have a meaning
when used after a @samp{%}: the sequence @samp{%%} outputs one
@samp{%}. It does not consume an argument.
@end table
-@node Modifiers, Printf Examples, Format-Control, Printf
+@node Format Modifiers, Printf Examples, Control Letters, Printf
@subsection Modifiers for @code{printf} Formats
@cindex @code{printf}, modifiers
-@cindex Modifiers (in format specifiers)
+@cindex modifiers (in format specifiers)
A format specification can also include @dfn{modifiers} that can control
how much of the item's value is printed and how much space it gets. The
-modifiers come between the @samp{%} and the format--control letter. Here
+modifiers come between the @samp{%} and the format-control letter. Here
are the possible modifiers, in the order in which they may appear:
@table @samp
@item -
-The minus sign, used before the width modifier, says to left--justify
+The minus sign, used before the width modifier, says to left-justify
the argument within its specified width. Normally the argument
-is printed right--justified in the specified width.
+is printed right-justified in the specified width. Thus,
+
+@example
+printf "%-4s", "foo"
+@end example
+
+@noindent
+prints @samp{foo }.
@item @var{width}
This is a number representing the desired width of a field. Inserting any
number between the @samp{%} sign and the format control character forces the
field to be expanded to this width. The default way to do this is to
-pad with spaces on the left.
+pad with spaces on the left. For example,
+
+@example
+printf "%4s", "foo"
+@end example
+
+@noindent
+prints @samp{ foo}.
+
+The value of @var{width} is a minimum width, not a maximum. If the item
+value requires more than @var{width} characters, it can be as wide as
+necessary. Thus,
+
+@example
+printf "%4s", "foobar"
+@end example
+
+@noindent
+prints @samp{foobar}. Preceding the @var{width} with a minus sign causes
+the output to be padded with spaces on the right, instead of on the left.
@item .@var{prec}
This is a number that specifies the precision to use when printing.
This specifies the number of digits you want printed to the right of the
-decimal place.
+decimal point. For a string, it specifies the maximum number of
+characters from the string that should be printed.
@end table
The C library @code{printf}'s dynamic @var{width} and @var{prec}
-capability (for example, @code{"%*.*s"}) is not supported. However, it can
-be easily simulated using concatenation to dynamically build the
-format string.
+capability (for example, @code{"%*.*s"}) is not yet supported. However, it can
+easily be simulated using concatenation to dynamically build the
+format string.@refill
-@node Printf Examples, , Modifiers, Printf
+@node Printf Examples, , Format Modifiers, Printf
@subsection Examples of Using @code{printf}
Here is how to use @code{printf} to make an aligned table:
@@ -2789,8 +2601,8 @@ awk '@{ printf "%-10s %s\n", $1, $2 @}' BBS-list
@noindent
prints the names of bulletin boards (@code{$1}) of the file
@file{BBS-list} as a string of 10 characters, left justified. It also
-prints the phone numbers (@code{$2}) afterward on the line. This will
-produce an aligned two--column table of names and phone numbers, like so:@refill
+prints the phone numbers (@code{$2}) afterward on the line. This
+produces an aligned two-column table of names and phone numbers:
@example
aardvark 555-5553
@@ -2806,24 +2618,24 @@ sdace 555-3430
sabafoo 555-2127
@end example
-Did you notice that we did not specify that the phone numbers be
-printed as numbers? They had to be printed as strings because the
-numbers are separated by a dash. This dash would be interpreted as a
-@dfn{minus} sign if we had tried to print the phone numbers as
-numbers. This would have led to some pretty confusing results.
+Did you notice that we did not specify that the phone numbers be printed
+as numbers? They had to be printed as strings because the numbers are
+separated by a dash. This dash would be interpreted as a minus sign if
+we had tried to print the phone numbers as numbers. This would have led
+to some pretty confusing results.
We did not specify a width for the phone numbers because they are the
last things on their lines. We don't need to put spaces after them.
-We could make our table look even nicer by adding headings to the tops of
-the columns. To do this, use the BEGIN pattern (@pxref{BEGIN/END}) to cause
-the header to be printed only once, at the beginning of the @code{awk}
-program:
+We could make our table look even nicer by adding headings to the tops
+of the columns. To do this, use the @code{BEGIN} pattern
+(@pxref{BEGIN/END}) to cause the header to be printed only once, at the
+beginning of the @code{awk} program:
@example
awk 'BEGIN @{ print "Name Number"
print "---- ------" @}
- @{ printf "%-10s %s\n", $1, $2 @}' BBS-list
+ @{ printf "%-10s %s\n", $1, $2 @}' BBS-list
@end example
Did you notice that we mixed @code{print} and @code{printf} statements in
@@ -2839,10 +2651,10 @@ awk 'BEGIN @{ printf "%-10s %s\n", "Name", "Number"
@noindent
By outputting each column heading with the same format specification
used for the elements of the column, we have made sure that the headings
-will be aligned just like the columns.
+are aligned just like the columns.
-The fact that the same format specification is used can be emphasized
-by storing it in a variable, like so:
+The fact that the same format specification is used three times can be
+emphasized by storing it in a variable, like this:
@example
awk 'BEGIN @{ format = "%-10s %s\n"
@@ -2855,10 +2667,266 @@ See if you can use the @code{printf} statement to line up the headings and
table data for our @file{inventory-shipped} example covered earlier in the
section on the @code{print} statement (@pxref{Print}).
+@node Redirection, Special Files, Printf, Printing
+@section Redirecting Output of @code{print} and @code{printf}
+
+@cindex output redirection
+@cindex redirection of output
+So far we have been dealing only with output that prints to the standard
+output, usually your terminal. Both @code{print} and @code{printf} can be
+told to send their output to other places. This is called
+@dfn{redirection}.@refill
+
+A redirection appears after the @code{print} or @code{printf} statement.
+Redirections in @code{awk} are written just like redirections in shell
+commands, except that they are written inside the @code{awk} program.
+
+@menu
+* File/Pipe Redirection:: Redirecting Output to Files and Pipes.
+* Close Output:: How to close output files and pipes.
+@end menu
+
+@node File/Pipe Redirection, Close Output, Redirection, Redirection
+@subsection Redirecting Output to Files and Pipes
+
+Here are the three forms of output redirection. They are all shown for
+the @code{print} statement, but they work identically for @code{printf}
+also.
+
+@table @code
+@item print @var{items} > @var{output-file}
+This type of redirection prints the items onto the output file
+@var{output-file}. The file name @var{output-file} can be any
+expression. Its value is changed to a string and then used as a
+file name (@pxref{Expressions}).@refill
+
+When this type of redirection is used, the @var{output-file} is erased
+before the first output is written to it. Subsequent writes do not
+erase @var{output-file}, but append to it. If @var{output-file} does
+not exist, then it is created.@refill
+
+For example, here is how one @code{awk} program can write a list of
+BBS names to a file @file{name-list} and a list of phone numbers to a
+file @file{phone-list}. Each output file contains one name or number
+per line.
+
+@example
+awk '@{ print $2 > "phone-list"
+ print $1 > "name-list" @}' BBS-list
+@end example
+
+@item print @var{items} >> @var{output-file}
+This type of redirection prints the items onto the output file
+@var{output-file}. The difference between this and the
+single-@samp{>} redirection is that the old contents (if any) of
+@var{output-file} are not erased. Instead, the @code{awk} output is
+appended to the file.
+
+@cindex pipes for output
+@cindex output, piping
+@item print @var{items} | @var{command}
+It is also possible to send output through a @dfn{pipe} instead of into a
+file. This type of redirection opens a pipe to @var{command} and writes
+the values of @var{items} through this pipe, to another process created
+to execute @var{command}.@refill
+
+The redirection argument @var{command} is actually an @code{awk}
+expression. Its value is converted to a string, whose contents give the
+shell command to be run.
+
+For example, this produces two files, one unsorted list of BBS names
+and one list sorted in reverse alphabetical order:
+
+@example
+awk '@{ print $1 > "names.unsorted"
+ print $1 | "sort -r > names.sorted" @}' BBS-list
+@end example
+
+Here the unsorted list is written with an ordinary redirection while
+the sorted list is written by piping through the @code{sort} utility.
+
+Here is an example that uses redirection to mail a message to a mailing
+list @samp{bug-system}. This might be useful when trouble is encountered
+in an @code{awk} script run periodically for system maintenance.
+
+@example
+print "Awk script failed:", $0 | "mail bug-system"
+print "at record number", FNR, "of", FILENAME | "mail bug-system"
+close("mail bug-system")
+@end example
+
+We call the @code{close} function here because it's a good idea to close
+the pipe as soon as all the intended output has been sent to it.
+@xref{Close Output}, for more information on this.
+@end table
+
+Redirecting output using @samp{>}, @samp{>>}, or @samp{|} asks the system
+to open a file or pipe only if the particular @var{file} or @var{command}
+you've specified has not already been written to by your program.@refill
+
+@node Close Output, , File/Pipe Redirection, Redirection
+@subsection Closing Output Files and Pipes
+@cindex closing output files and pipes
+@findex close
+
+When a file or pipe is opened, the file name or command associated with
+it is remembered by @code{awk} and subsequent writes to the same file or
+command are appended to the previous writes. The file or pipe stays
+open until @code{awk} exits. This is usually convenient.
+
+Sometimes there is a reason to close an output file or pipe earlier
+than that. To do this, use the @code{close} function, as follows:
+
+@example
+close(@var{filename})
+@end example
+
+@noindent
+or
+
+@example
+close(@var{command})
+@end example
+
+The argument @var{filename} or @var{command} can be any expression.
+Its value must exactly equal the string used to open the file or pipe
+to begin with---for example, if you open a pipe with this:
+
+@example
+print $1 | "sort -r > names.sorted"
+@end example
+
+@noindent
+then you must close it with this:
+
+@example
+close("sort -r > names.sorted")
+@end example
+
+Here are some reasons why you might need to close an output file:
+
+@itemize @bullet
+@item
+To write a file and read it back later on in the same @code{awk}
+program. Close the file when you are finished writing it; then
+you can start reading it with @code{getline} (@pxref{Getline}).
+
+@item
+To write numerous files, successively, in the same @code{awk}
+program. If you don't close the files, eventually you will exceed the
+system limit on the number of open files in one process. So close
+each one when you are finished writing it.
+
+@item
+To make a command finish. When you redirect output through a pipe,
+the command reading the pipe normally continues to try to read input
+as long as the pipe is open. Often this means the command cannot
+really do its work until the pipe is closed. For example, if you
+redirect output to the @code{mail} program, the message is not
+actually sent until the pipe is closed.
+
+@item
+To run the same program a second time, with the same arguments.
+This is not the same thing as giving more input to the first run!
+
+For example, suppose you pipe output to the @code{mail} program. If you
+output several lines redirected to this pipe without closing it, they make
+a single message of several lines. By contrast, if you close the pipe
+after each line of output, then each line makes a separate message.
+@end itemize
+
+@node Special Files, , Redirection, Printing
+@section Standard I/O Streams
+@cindex standard input
+@cindex standard output
+@cindex standard error output
+@cindex file descriptors
+
+Running programs conventionally have three input and output streams
+already available to them for reading and writing. These are known as
+the @dfn{standard input}, @dfn{standard output}, and @dfn{standard error
+output}. These streams are, by default, terminal input and output, but
+they are often redirected with the shell, via the @samp{<}, @samp{<<},
+@samp{>}, @samp{>>}, @samp{>&} and @samp{|} operators. Standard error
+is used only for writing error messages; the reason we have two separate
+streams, standard output and standard error, is so that they can be
+redirected separately.
+
+@c @cindex differences between @code{gawk} and @code{awk}
+In other implementations of @code{awk}, the only way to write an error
+message to standard error in an @code{awk} program is as follows:
+
+@example
+print "Serious error detected!\n" | "cat 1>&2"
+@end example
+
+@noindent
+This works by opening a pipeline to a shell command which can access the
+standard error stream which it inherits from the @code{awk} process.
+This is far from elegant, and is also inefficient, since it requires a
+separate process. So people writing @code{awk} programs have often
+neglected to do this. Instead, they have sent the error messages to the
+terminal, like this:
+
+@example
+NF != 4 @{
+ printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/tty"
+@}
+@end example
+
+@noindent
+This has the same effect most of the time, but not always: although the
+standard error stream is usually the terminal, it can be redirected, and
+when that happens, writing to the terminal is not correct. In fact, if
+@code{awk} is run from a background job, it may not have a terminal at all.
+Then opening @file{/dev/tty} will fail.
+
+@code{gawk} provides special file names for accessing the three standard
+streams. When you redirect input or output in @code{gawk}, if the file name
+matches one of these special names, then @code{gawk} directly uses the
+stream it stands for.
+
+@cindex @file{/dev/stdin}
+@cindex @file{/dev/stdout}
+@cindex @file{/dev/stderr}
+@cindex @file{/dev/fd/}
+@table @file
+@item /dev/stdin
+The standard input (file descriptor 0).
+
+@item /dev/stdout
+The standard output (file descriptor 1).
+
+@item /dev/stderr
+The standard error output (file descriptor 2).
+
+@item /dev/fd/@var{n}
+The file associated with file descriptor @var{n}. Such a file must have
+been opened by the program initiating the @code{awk} execution (typically
+the shell). Unless you take special pains, only descriptors 0, 1 and 2
+are available.
+@end table
+
+The file names @file{/dev/stdin}, @file{/dev/stdout}, and @file{/dev/stderr}
+are aliases for @file{/dev/fd/0}, @file{/dev/fd/1}, and @file{/dev/fd/2},
+respectively, but they are more self-explanatory.
+
+The proper way to write an error message in a @code{gawk} program
+is to use @file{/dev/stderr}, like this:
+
+@example
+NF != 4 @{
+ printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/stderr"
+@}
+@end example
+
+Recognition of these special file names is disabled if @code{gawk} is in
+compatibility mode (@pxref{Command Line}).
+
@node One-liners, Patterns, Printing, Top
@chapter Useful ``One-liners''
-@cindex One-liners
+@cindex one-liners
Useful @code{awk} programs are often short, just a line or two. Here is a
collection of useful, short programs to get you started. Some of these
programs contain constructs that haven't been covered yet. The description
@@ -2867,7 +2935,7 @@ read the rest of the manual to become an @code{awk} expert!
@table @code
@item awk '@{ num_fields = num_fields + NF @}
-@itemx @code{ END @{ print num_fields @}'}
+@itemx @ @ @ @ @ END @{ print num_fields @}'
This program prints the total number of fields in all input lines.
@item awk 'length($0) > 80'
@@ -2881,111 +2949,88 @@ easy way to delete blank lines from a file (or rather, to create a new
file similar to the old file but from which the blank lines have been
deleted).
-
@item awk '@{ if (NF > 0) print @}'
This program also prints every line that has at least one field. Here we
allow the rule to match every line, then decide in the action whether
to print.
-@item awk 'BEGIN @{ for (i = 1; i <= 7; i++)
-@itemx @code{ print int(101 * rand()) @}'}
+@item awk@ 'BEGIN@ @{@ for (i = 1; i <= 7; i++)
+@itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ print int(101 * rand()) @}'
This program prints 7 random numbers from 0 to 100, inclusive.
@item ls -l @var{files} | awk '@{ x += $4 @} ; END @{ print "total bytes: " x @}'
This program prints the total number of bytes used by @var{files}.
-@item expand @var{file} | awk '@{ if (x < length()) x = length() @}
-@itemx @code{ END @{ print "maximum line length is " x @}'}
+@item expand@ @var{file}@ |@ awk@ '@{ if (x < length()) x = length() @}
+@itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ END @{ print "maximum line length is " x @}'
This program prints the maximum line length of @var{file}. The input
is piped through the @code{expand} program to change tabs into spaces,
-so the widths compared are actually the right--margin columns.
+so the widths compared are actually the right-margin columns.
@end table
@node Patterns, Actions, One-liners, Top
@chapter Patterns
+@cindex pattern, definition of
-@cindex Patterns, definition of
-@cindex Patterns, types of
-Patterns control the execution of rules: a rule is executed when its
-pattern matches the input record. The @code{awk} language provides
-several special patterns that are described in the sections that
-follow. Patterns include:@refill
+Patterns in @code{awk} control the execution of rules: a rule is
+executed when its pattern matches the current input record. This
+chapter tells all about how to write patterns.
-@ignore
-@strong{I think the ordering here needs to be rearranged. @code{BEGIN}
-and @code{END} first, then @var{null}, /@var{regexp}/, @var{condexp},
-@var{condexp bool condexp}, @var{exp1} ? @var{exp2} : @var{exp3}, and
-finally the range pattern.}
-@end ignore
+@menu
+* Kinds of Patterns:: A list of all kinds of patterns.
+ The following subsections describe them in detail.
-@table @asis
-@item @var{null}
-The empty pattern, which matches every input record. (@xref{Empty, , The
-Empty Pattern}.)
+* Empty:: The empty pattern, which matches every record.
-@item /@var{regular expression}/
-A regular expression as a pattern. It matches when the text of the
-input record fits the regular expression. (@xref{Regexp, , Regular
-Expressions as Patterns}.)
+* Regexp:: Regular expressions such as @samp{/foo/}.
-@item @var{condexp}
-A single comparison expression. It matches when it is true.
-(@xref{Comparison Patterns, , Comparison Expressions as Patterns}.)
+* Comparison Patterns:: Comparison expressions such as @code{$1 > 10}.
-@item @code{BEGIN}
-@itemx @code{END}
-Special patterns to supply start--up or clean--up information to
-@code{awk}. (@xref{BEGIN/END, , Specifying Record Ranges With
-Patterns}.)
+* Boolean Patterns:: Combining comparison expressions.
-@item @var{pat1}, @var{pat2}
-A pair of patterns separated by a comma, specifying a range of records.
-(@xref{Ranges, , Specifying Record Ranges With Patterns}.)
+* Expression Patterns:: Any expression can be used as a pattern.
-@item @var{condexp1} @var{boolean} @var{condexp2}
-A @dfn{compound} pattern, which combines expressions with the operators
-@samp{and}, @code{&&}, and @samp{or}, @code{||}. (@xref{Boolean, ,
-Boolean Operators and Patterns}.)
-
-@item ! @var{condexp}
-The pattern @var{condexp} is evaluated. Then the @code{!} performs a
-boolean ``not'' or logical negation operation; if the input line matches
-the pattern in @var{condexp} then the associated action is @emph{not}
-executed. If the input line did not match that pattern, then the action
-@emph{is} executed. (@xref{Boolean, , Boolean Operators and Patterns}.)
-
-@item (@var{expr})
-Parentheses may be used to control how operators nest.
-
-@item @var{pat1} ? @var{pat2} : @var{pat3}
-The first pattern is evaluated. If it is true, the input line is tested
-against the second pattern, otherwise it is tested against the third.
-(@xref{Conditional Patterns, , Conditional Patterns}.)
-@end table
+* Ranges:: Using pairs of patterns to specify record ranges.
-@menu
-The following subsections describe these forms in detail:
+* BEGIN/END:: Specifying initialization and cleanup rules.
+@end menu
-* Empty:: The empty pattern, which matches every record.
+@node Kinds of Patterns, Empty, Patterns, Patterns
+@section Kinds of Patterns
+@cindex patterns, types of
-* Regexp:: Regular expressions such as @samp{/foo/}.
+Here is a summary of the types of patterns supported in @code{awk}.
-* Comparison Patterns:: Comparison expressions such as @samp{$1 > 10}.
+@table @code
+@item /@var{regular expression}/
+A regular expression as a pattern. It matches when the text of the
+input record fits the regular expression. (@xref{Regexp, , Regular
+Expressions as Patterns}.)
-* Boolean:: Combining comparison expressions.
+@item @var{expression}
+A single expression. It matches when its value, converted to a number,
+is nonzero (if a number) or nonnull (if a string). (@xref{Expression
+Patterns}.)
-* Ranges:: Using pairs of patterns to specify record ranges.
+@item @var{pat1}, @var{pat2}
+A pair of patterns separated by a comma, specifying a range of records.
+(@xref{Ranges, , Specifying Record Ranges With Patterns}.)
-* BEGIN/END:: Specifying initialization and cleanup rules.
+@item BEGIN
+@itemx END
+Special patterns to supply start-up or clean-up information to
+@code{awk}. (@xref{BEGIN/END}.)
-* Conditional Patterns:: Patterns such as @samp{pat1 ? pat2 : pat3}.
-@end menu
+@item @var{null}
+The empty pattern matches every input record. (@xref{Empty, , The Empty
+Pattern}.)
+@end table
-@node Empty, Regexp, , Patterns
+@node Empty, Regexp, Kinds of Patterns, Patterns
@section The Empty Pattern
-@cindex Empty pattern
-@cindex Pattern, empty
+@cindex empty pattern
+@cindex pattern, empty
An empty pattern is considered to match @emph{every} input record. For
example, the program:@refill
@@ -2998,40 +3043,45 @@ prints just the first field of every record.
@node Regexp, Comparison Patterns, Empty, Patterns
@section Regular Expressions as Patterns
-@cindex Pattern, regular expressions
-@cindex Regexp
-@cindex Regular expressions as patterns
+@cindex pattern, regular expressions
+@cindex regexp
+@cindex regular expressions as patterns
-A @dfn{regular expression}, or @dfn{regexp}, is a way of describing
-classes of strings. When enclosed in slashes (@code{/}), it makes
-an @code{awk} pattern that matches every input record that contains
-a match for the regexp.
+A @dfn{regular expression}, or @dfn{regexp}, is a way of describing a
+class of strings. A regular expression enclosed in slashes (@samp{/})
+is an @code{awk} pattern that matches every input record whose text
+belongs to that class.
The simplest regular expression is a sequence of letters, numbers, or
both. Such a regexp matches any string that contains that sequence.
Thus, the regexp @samp{foo} matches any string containing @samp{foo}.
-(More complicated regexps let you specify classes of similar strings.)
+Therefore, the pattern @code{/foo/} matches any input record containing
+@samp{foo}. Other kinds of regexps let you specify more complicated
+classes of strings.
@menu
* Usage: Regexp Usage. How regexps are used in patterns.
* Operators: Regexp Operators. How to write a regexp.
+* Case-sensitivity:: How to do case-insensitive matching.
@end menu
-@node Regexp Usage, Regexp Operators, , Regexp
-@subsection How to use Regular Expressions
+@node Regexp Usage, Regexp Operators, Regexp, Regexp
+@subsection How to Use Regular Expressions
-When you enclose @samp{foo} in slashes, you get a pattern that matches
-a record that contains @samp{foo}. For example, this prints the second
-field of each record that contains @samp{foo} anywhere:
+A regular expression can be used as a pattern by enclosing it in
+slashes. Then the regular expression is matched against the entire text
+of each record. (Normally, it only needs to match some part of the text
+in order to succeed.) For example, this prints the second field of each
+record that contains @samp{foo} anywhere:
@example
awk '/foo/ @{ print $2 @}' BBS-list
@end example
-@cindex Regular expression matching operators
-@cindex String-matching operators
-@cindex Operators, string-matching
-@cindex Operators, regular expression matching
+@cindex regular expression matching operators
+@cindex string-matching operators
+@cindex operators, string-matching
+@cindex operators, regular expression matching
@cindex regexp search operators
Regular expressions can also be used in comparison expressions. Then
you can specify the string to match against; it need not be the entire
@@ -3040,9 +3090,10 @@ patterns or in @code{if} and @code{while} statements.
@table @code
@item @var{exp} ~ /@var{regexp}/
-This is true if the expression @var{exp} (taken as a character string) is
-matched by @var{regexp}. The following example matches, or selects, all
-input records with the letter @samp{J} in the first field:@refill
+This is true if the expression @var{exp} (taken as a character string)
+is matched by @var{regexp}. The following example matches, or selects,
+all input records with the upper-case letter @samp{J} somewhere in the
+first field:@refill
@example
awk '$1 ~ /J/' inventory-shipped
@@ -3055,59 +3106,48 @@ awk '@{ if ($1 ~ /J/) print @}' inventory-shipped
@end example
@item @var{exp} !~ /@var{regexp}/
-This is true if the expression @var{exp} (taken as a character string) is
-@emph{not} matched by @var{regexp}. The following example matches, or
-selects, all input records whose first field @emph{does not} contain the
-letter @samp{J}:@refill
+This is true if the expression @var{exp} (taken as a character string)
+is @emph{not} matched by @var{regexp}. The following example matches,
+or selects, all input records whose first field @emph{does not} contain
+the upper-case letter @samp{J}:@refill
@example
awk '$1 !~ /J/' inventory-shipped
@end example
@end table
-@cindex Computed Regular Expressions
-@cindex Regular Expressions, Computed
-@cindex Dynamic Regular Expressions
-@cindex Regular Expressions, Dynamic
-The right hand side of a @code{~} or @code{!~} operator need not be
-a constant regexp (i.e. a string of characters between @samp{/}s). It can
-also be @dfn{computed}, or @dfn{dynamic}. For example:
+@cindex computed regular expressions
+@cindex regular expressions, computed
+@cindex dynamic regular expressions
+The right hand side of a @samp{~} or @samp{!~} operator need not be a
+constant regexp (i.e., a string of characters between slashes). It may
+be any expression. The expression is evaluated, and converted if
+necessary to a string; the contents of the string are used as the
+regexp. A regexp that is computed in this way is called a @dfn{dynamic
+regexp}. For example:
@example
-identifier = "[A-Za-z_][A-Za-z_0-9]+"
-$0 ~ identifier
+identifier_regexp = "[A-Za-z_][A-Za-z_0-9]+"
+$0 ~ identifier_regexp
@end example
@noindent
-sets @code{identifier} to a regexp that describes @code{awk} variable
-names, and tests if the input record matches this regexp.
+sets @code{identifier_regexp} to a regexp that describes @code{awk}
+variable names, and tests if the input record matches this regexp.
-A dynamic regexp may actually be any expression. The expression is
-evaluated, and the result is treated as a string that describes a
-regular expression.
-
-@node Regexp Operators, , Regexp Usage, Regexp
+@node Regexp Operators, Case-sensitivity, Regexp Usage, Regexp
@subsection Regular Expression Operators
-@cindex Metacharacters
-@cindex Regular expression, metacharacters
+@cindex metacharacters
+@cindex regular expression metacharacters
You can combine regular expressions with the following characters,
called @dfn{regular expression operators}, or @dfn{metacharacters}, to
-increase the power and versatility of regular expressions. This is
-a table of metacharacters:
-
-@table @code
-@item \
-This is used to suppress the special meaning of a character when
-matching. For example:
+increase the power and versatility of regular expressions.
-@example
-\$
-@end example
-
-@noindent
-matches the character @samp{$}.
+Here is a table of metacharacters. All characters not listed in the
+table stand for themselves.
+@table @code
@item ^
This matches the beginning of the string or the beginning of a line
within the string. For example:
@@ -3121,15 +3161,15 @@ matches the @samp{@@chapter} at the beginning of a string, and can be used
to identify chapter beginnings in Texinfo source files.
@item $
-This is similar to @code{^}, but it matches only at the end of a string
+This is similar to @samp{^}, but it matches only at the end of a string
or the end of a line within the string. For example:
@example
-/p$/
+p$
@end example
@noindent
-as a pattern matches a record that ends with a @samp{p}.
+matches a record that ends with a @samp{p}.
@item .
This matches any single character except a newline. For example:
@@ -3140,11 +3180,12 @@ This matches any single character except a newline. For example:
@noindent
matches any single character followed by a @samp{P} in a string. Using
-concatenation we can make regular expressions like @samp{U.A}, which matches
-any three--character string that begins with @samp{U} and ends with @samp{A}.
+concatenation we can make regular expressions like @samp{U.A}, which
+matches any three-character sequence that begins with @samp{U} and ends
+with @samp{A}.
@item [@dots{}]
-This is called a @dfn{character set}. It matches any one of a group of
+This is called a @dfn{character set}. It matches any one of the
characters that are enclosed in the square brackets. For example:
@example
@@ -3164,28 +3205,50 @@ example:@refill
@end example
@noindent
-matches any string that contains a digit.
+matches any digit.
-Note that special patterns have to be followed to match the characters,
-@samp{]}, @samp{-}, and @samp{^} when they are enclosed in the square
-brackets. To match a @samp{]}, make it the first character in the set.
-For example:
+To include the character @samp{\}, @samp{]}, @samp{-} or @samp{^} in a
+character set, put a @samp{\} in front of it. For example:
@example
-[]d]
+[d\]]
@end example
@noindent
matches either @samp{]}, or @samp{d}.@refill
-To match @samp{-}, write it as @samp{---}, which is a range containing only
-@samp{-}. You may also make the @samp{-} be the first or last character
-in the set. To match @samp{^}, make it any character except the first one of
-a set.
+This treatment of @samp{\} is compatible with other @code{awk}
+implementations but incompatible with the proposed POSIX specification
+for @code{awk}. The current draft specifies the use of the same syntax
+used in @code{egrep}.
+
+We may change @code{gawk} to fit the standard, once we are sure it will
+no longer change. For the meanwhile, the @samp{-a} option specifies the
+traditional @code{awk} syntax described above (which is also the
+default), while the @samp{-e} option specifies @code{egrep} syntax.
+@xref{Options}.
+
+In @code{egrep} syntax, backslash is not syntactically special within
+square brackets. This means that special tricks have to be used to
+represent the characters @samp{]}, @samp{-} and @samp{^} as members of a
+character set.
+
+To match @samp{-}, write it as @samp{---}, which is a range containing
+only @samp{-}. You may also give @samp{-} as the first or last
+character in the set. To match @samp{^}, put it anywhere except as the
+first character of a set. To match a @samp{]}, make it the first
+character in the set. For example:
+
+@example
+[]d^]
+@end example
+
+@noindent
+matches either @samp{]}, @samp{d} or @samp{^}.@refill
@item [^ @dots{}]
-This is the @dfn{complemented character set}. The first character after
-the @samp{[} @emph{must} be a @samp{^}. This matches any characters
+This is a @dfn{complemented character set}. The first character after
+the @samp{[} @emph{must} be a @samp{^}. It matches any characters
@emph{except} those in the square brackets. For example:
@example
@@ -3193,7 +3256,7 @@ the @samp{[} @emph{must} be a @samp{^}. This matches any characters
@end example
@noindent
-matches any characters that are not digits.
+matches any character that is not a digit.
@item |
This is the @dfn{alternation operator} and it is used to specify
@@ -3207,6 +3270,7 @@ alternatives. For example:
matches any string that matches either @samp{^P} or @samp{[0-9]}. This
means it matches any string that contains a digit or starts with @samp{P}.
+The alternation applies to the largest possible regexps on either side.
@item (@dots{})
Parentheses are used for grouping in regular expressions as in
arithmetic. They can be used to concatenate regular expressions
@@ -3221,24 +3285,24 @@ ph*
@end example
@noindent
-applies the @code{*} symbol to the preceding @samp{h} and looks for matches
-to one @samp{p} followed by any number of @samp{h}'s. This will also match
-just @samp{p} if no @samp{h}'s are present.
+applies the @samp{*} symbol to the preceding @samp{h} and looks for matches
+to one @samp{p} followed by any number of @samp{h}s. This will also match
+just @samp{p} if no @samp{h}s are present.
-The @code{*} means repeat the @emph{smallest} possible preceding expression
-in order to find a match. The @code{awk} language processes a @code{*} by
-matching as many repetitions as can be found. For example:
+The @samp{*} repeats the @emph{smallest} possible preceding expression.
+(Use parentheses if you wish to repeat a larger expression.) It finds
+as many repetitions as possible. For example:
@example
awk '/\(c[ad][ad]*r x\)/ @{ print @}' sample
@end example
@noindent
-matches every record in the input containing a string of the form
+prints every record in the input containing a string of the form
@samp{(car x)}, @samp{(cdr x)}, @samp{(cadr x)}, and so on.@refill
@item +
-This symbol is similar to @code{*}, but the preceding expression must be
+This symbol is similar to @samp{*}, but the preceding expression must be
matched at least once. This means that:
@example
@@ -3246,8 +3310,8 @@ wh+y
@end example
@noindent
-would match @samp{why} and @samp{whhy} but not @samp{wy}, whereas @samp{wh*y}
-would match all three of these strings. And this is a simpler
+would match @samp{why} and @samp{whhy} but not @samp{wy}, whereas
+@samp{wh*y} would match all three of these strings. This is a simpler
way of writing the last @samp{*} example:
@example
@@ -3255,7 +3319,7 @@ awk '/\(c[ad]+r x\)/ @{ print @}' sample
@end example
@item ?
-This symbol is similar to @code{*}, but the preceding expression can be
+This symbol is similar to @samp{*}, but the preceding expression can be
matched once or not at all. For example:
@example
@@ -3264,29 +3328,94 @@ fe?d
@noindent
will match @samp{fed} or @samp{fd}, but nothing else.@refill
+
+@item \
+This is used to suppress the special meaning of a character when
+matching. For example:
+
+@example
+\$
+@end example
+
+@noindent
+matches the character @samp{$}.
+
+The escape sequences used for string constants (@pxref{Constants}) are
+valid in regular expressions as well; they are also introduced by a
+@samp{\}.
@end table
-In regular expressions, the @code{*}, @code{+}, and @code{?} operators have
-the highest precedence, followed by concatenation, and finally by @code{|}.
+In regular expressions, the @samp{*}, @samp{+}, and @samp{?} operators have
+the highest precedence, followed by concatenation, and finally by @samp{|}.
As in arithmetic, parentheses can change how operators are grouped.@refill
-Any other character stands for itself. However, it is important to note
-that case in regular expressions @emph{is} significant, both when matching
-ordinary (i.e. non--metacharacter) characters, and inside character sets.
-Thus a @samp{w} in a regular expression matches only a lower case @samp{w}
-and not either an uppercase or lowercase @samp{w}. When you want to
-do a case--independent match, you have to use a character set: @samp{[Ww]}.
+@node Case-sensitivity,, Regexp Operators, Regexp
+@subsection Case-sensitivity in Matching
+
+Case is normally significant in regular expressions, both when matching
+ordinary characters (i.e., not metacharacters), and inside character
+sets. Thus a @samp{w} in a regular expression matches only a lower case
+@samp{w} and not an upper case @samp{W}.
+
+The simplest way to do a case-independent match is to use a character
+set: @samp{[Ww]}. However, this can be cumbersome if you need to use it
+often; and it can make the regular expressions harder for humans to
+read. There are two other alternatives that you might prefer.
+
+One way to do a case-insensitive match at a particular point in the
+program is to convert the data to a single case, using the
+@code{tolower} or @code{toupper} built-in string functions (which we
+haven't discussed yet; @pxref{String Functions}). For example:
+
+@example
+tolower($1) ~ /foo/ @{ @dots{} @}
+@end example
+
+@noindent
+converts the first field to lower case before matching against it.
+
+Another method is to set the variable @code{IGNORECASE} to a nonzero
+value (@pxref{Built-in Variables}). When @code{IGNORECASE} is not zero,
+@emph{all} regexp operations ignore case. Changing the value of
+@code{IGNORECASE} dynamically controls the case sensitivity of your
+program as it runs. Case is significant by default because
+@code{IGNORECASE} (like most variables) is initialized to zero.
+
+@example
+x = "aB"
+if (x ~ /ab/) @dots{} # this test will fail
+
+IGNORECASE = 1
+if (x ~ /ab/) @dots{} # now it will succeed
+@end example
+
+You cannot generally use @code{IGNORECASE} to make certain rules
+case-insensitive and other rules case-sensitive, because there is no way
+to set @code{IGNORECASE} just for the pattern of a particular rule. To
+do this, you must use character sets or @code{tolower}. However, one
+thing you can do only with @code{IGNORECASE} is turn case-sensitivity on
+or off dynamically for all the rules at once.
+
+@code{IGNORECASE} can be set on the command line, or in a @code{BEGIN}
+rule. Setting @code{IGNORECASE} from the command line is a way to make
+a program case-insensitive without having to edit it.
+
+The value of @code{IGNORECASE} has no effect if @code{gawk} is in
+compatibility mode (@pxref{Command Line}). Case is always significant
+in compatibility mode.
-@node Comparison Patterns, Ranges, Regexp, Patterns
+@node Comparison Patterns, Boolean Patterns, Regexp, Patterns
@section Comparison Expressions as Patterns
-@cindex Comparison expressions as patterns
-@cindex Pattern, comparison expressions
-@cindex Relational operators
-@cindex Operators, relational
+@cindex comparison expressions as patterns
+@cindex pattern, comparison expressions
+@cindex relational operators
+@cindex operators, relational
-@dfn{Comparison patterns} use @dfn{relational operators} to compare
-strings or numbers. The relational operators are the same as in C.
-Here is a table of them:
+@dfn{Comparison patterns} test relationships such as equality between
+two strings or numbers. They are a special case of expression patterns
+(@pxref{Expression Patterns}). They are written with @dfn{relational
+operators}, which are a superset of those in C. Here is a table of
+them:
@table @code
@item @var{x} < @var{y}
@@ -3306,18 +3435,26 @@ True if @var{x} is equal to @var{y}.
@item @var{x} != @var{y}
True if @var{x} is not equal to @var{y}.
-@end table
-Comparison expressions can be used as patterns to control whether a
-rule is executed. The expression is evaluated for each input record
-read, and the pattern is considered matched if the condition is
-@dfn{true}.
+@item @var{x} ~ @var{y}
+True if @var{x} matches the regular expression described by @var{y}.
+
+@item @var{x} !~ @var{y}
+True if @var{x} does not match the regular expression described by @var{y}.
+@end table
The operands of a relational operator are compared as numbers if they
are both numbers. Otherwise they are converted to, and compared as,
strings (@pxref{Conversion}). Strings are compared by comparing the
-first character of each, then the second character of each, and so on.
-Thus, @code{"10"} is less than @code{"9"}.
+first character of each, then the second character of each, and so on,
+until there is a difference. If the two strings are equal until the
+shorter one runs out, the shorter one is considered to be less than the
+longer one. Thus, @code{"10"} is less than @code{"9"}.
+
+The left operand of the @samp{~} and @samp{!~} operators is a string.
+The right operand is either a constant regular expression enclosed in
+slashes (@code{/@var{regexp}/}), or any expression, whose string value
+is used as a dynamic regular expression (@pxref{Regexp Usage}).
The following example prints the second field of each input record
whose first field is precisely @samp{foo}.
@@ -3334,31 +3471,113 @@ accept any record with a first field that contains @samp{foo}:
awk '$1 ~ "foo" @{ print $2 @}' BBS-list
@end example
-@node Ranges, BEGIN/END, Comparison Patterns, Patterns
+@noindent
+or, equivalently, this one:
+
+@example
+awk '$1 ~ /foo/ @{ print $2 @}' BBS-list
+@end example
+
+@node Boolean Patterns, Expression Patterns, Comparison Patterns, Patterns
+@section Boolean Operators and Patterns
+@cindex patterns, boolean
+@cindex boolean patterns
+
+A @dfn{boolean pattern} is an expression which combines other patterns
+using the @dfn{boolean operators} ``or'' (@samp{||}), ``and''
+(@samp{&&}), and ``not'' (@samp{!}). Whether the boolean pattern
+matches an input record depends on whether its subpatterns match.
+
+For example, the following command prints all records in the input file
+@file{BBS-list} that contain both @samp{2400} and @samp{foo}.@refill
+
+@example
+awk '/2400/ && /foo/' BBS-list
+@end example
+
+The following command prints all records in the input file
+@file{BBS-list} that contain @emph{either} @samp{2400} or @samp{foo}, or
+both.@refill
+
+@example
+awk '/2400/ || /foo/' BBS-list
+@end example
+
+The following command prints all records in the input file
+@file{BBS-list} that do @emph{not} contain the string @samp{foo}.
+
+@example
+awk '! /foo/' BBS-list
+@end example
+
+Note that boolean patterns are a special case of expression patterns
+(@pxref{Expression Patterns}); they are expressions that use the boolean
+operators. For complete information on the boolean operators, see
+@ref{Boolean Ops}.
+
+The subpatterns of a boolean pattern can be constant regular
+expressions, comparisons, or any other @code{gawk} expressions. Range
+patterns are not expressions, so they cannot appear inside boolean
+patterns. Likewise, the special patterns @code{BEGIN} and @code{END},
+which never match any input record, are not expressions and cannot
+appear inside boolean patterns.
+
+@node Expression Patterns, Ranges, Boolean Patterns, Patterns
+@section Expressions as Patterns
+
+Any @code{awk} expression is valid also as a pattern in @code{gawk}.
+Then the pattern ``matches'' if the expression's value is nonzero (if a
+number) or nonnull (if a string).
+
+The expression is reevaluated each time the rule is tested against a new
+input record. If the expression uses fields such as @code{$1}, the
+value depends directly on the new input record's text; otherwise, it
+depends only on what has happened so far in the execution of the
+@code{awk} program, but that may still be useful.
+
+Comparison patterns are actually a special case of this. For
+example, the expression @code{$5 == "foo"} has the value 1 when the
+value of @code{$5} equals @code{"foo"}, and 0 otherwise; therefore, this
+expression as a pattern matches when the two values are equal.
+
+Boolean patterns are also special cases of expression patterns.
+
+A constant regexp as a pattern is also a special case of an expression
+pattern. @code{/foo/} as an expression has the value 1 if @samp{foo}
+appears in the current input record; thus, as a pattern, @code{/foo/}
+matches any record containing @samp{foo}.
+
+Other implementations of @code{awk} are less general than @code{gawk}:
+they allow comparison expressions, and boolean combinations thereof
+(optionally with parentheses), but not necessarily other kinds of
+expressions.
+
+@node Ranges, BEGIN/END, Expression Patterns, Patterns
@section Specifying Record Ranges With Patterns
-@cindex Range pattern
+@cindex range pattern
@cindex patterns, range
-A @dfn{range pattern} is made of two patterns separated by a comma:
-@samp{@var{begpat}, @var{endpat}}. It matches ranges of consecutive
-input records. The first pattern @var{begpat} controls where the
-range begins, and the second one @var{endpat} controls where it ends.
-
-They work as follows: @var{begpat} is matched against every input
-record; when a record matches @var{begpat}, the range pattern becomes
-@dfn{turned on}. The range pattern matches this record. As long as it
-stays turned on, it automatically matches every input record read. But
-meanwhile, @var{endpat} is matched against every input record, and when
-it matches, the range pattern is turned off again for the following
-record. Now we go back to checking @var{begpat} against each record.
-For example:@refill
+A @dfn{range pattern} is made of two patterns separated by a comma, of
+the form @code{@var{begpat}, @var{endpat}}. It matches ranges of
+consecutive input records. The first pattern @var{begpat} controls
+where the range begins, and the second one @var{endpat} controls where
+it ends. For example,@refill
@example
awk '$1 == "on", $1 == "off"'
@end example
@noindent
-prints every record between on/off pairs, inclusive.
+prints every record between @samp{on}/@samp{off} pairs, inclusive.
+
+In more detail, a range pattern starts out by matching @var{begpat}
+against every input record; when a record matches @var{begpat}, the
+range pattern becomes @dfn{turned on}. The range pattern matches this
+record. As long as it stays turned on, it automatically matches every
+input record read. But meanwhile, it also matches @var{endpat} against
+every input record, and when that succeeds, the range pattern is turned
+off again for the following record. Now it goes back to checking
+@var{begpat} against each record.
The record that turns on the range pattern and the one that turns it
off both match the range pattern. If you don't want to operate on
@@ -3369,200 +3588,141 @@ It is possible for a pattern to be turned both on and off by the same
record, if both conditions are satisfied by that record. Then the action is
executed for just that record.
-@node BEGIN/END, Boolean, Ranges, Patterns
+@node BEGIN/END,, Ranges, Patterns
@section @code{BEGIN} and @code{END} Special Patterns
-@cindex @code{BEGIN}, special pattern
-@cindex Patterns, @code{BEGIN}
-@cindex @code{END}, special pattern
-@cindex Patterns, @code{END}
+@cindex @code{BEGIN} special pattern
+@cindex patterns, @code{BEGIN}
+@cindex @code{END} special pattern
+@cindex patterns, @code{END}
@code{BEGIN} and @code{END} are special patterns. They are not used to
-match input records. Rather, they are used for supplying start--up or
-clean--up information to your @code{awk} script. A @code{BEGIN} rule is
+match input records. Rather, they are used for supplying start-up or
+clean-up information to your @code{awk} script. A @code{BEGIN} rule is
executed, once, before the first input record has been read. An @code{END}
rule is executed, once, after all the input has been read. For
example:@refill
+@group
@example
-awk 'BEGIN @{ print "Analysis of ``foo'' program" @}
+awk 'BEGIN @{ print "Analysis of `foo'" @}
/foo/ @{ ++foobar @}
- END @{ print "``foo'' appears " foobar " times." @}' BBS-list
+ END @{ print "`foo' appears " foobar " times." @}' BBS-list
@end example
+@end group
+
+This program finds out how many times the string @samp{foo} appears in
+the input file @file{BBS-list}. The @code{BEGIN} rule prints a title
+for the report. There is no need to use the @code{BEGIN} rule to
+initialize the counter @code{foobar} to zero, as @code{awk} does this
+for us automatically (@pxref{Variables}).
-This program finds out how many times the string @samp{foo} appears in the
-input file @file{BBS-list}. The @code{BEGIN} pattern prints out a title
-for the report. There is no need to use the @code{BEGIN} pattern to
-initialize the counter @code{foobar} to zero, as @code{awk} does this for
-us automatically (@pxref{Variables}).
-The second rule increments the variable @code{foobar}
-every time a record containing the pattern @samp{foo} is read. The last
-rule prints out the value of @code{foobar} at the end of the run.@refill
+The second rule increments the variable @code{foobar} every time a
+record containing the pattern @samp{foo} is read. The @code{END} rule
+prints the value of @code{foobar} at the end of the run.@refill
-The special patterns @code{BEGIN} and @code{END} do not combine with
-other kinds of patterns.
+The special patterns @code{BEGIN} and @code{END} cannot be used in ranges
+or with boolean operators.
An @code{awk} program may have multiple @code{BEGIN} and/or @code{END}
-rules. The contents of multiple @code{BEGIN} or @code{END} rules are
-treated as if they had been enclosed in a single rule, in the order
-that the rules are encountered in the @code{awk} program. (This feature
-was introduced with the new version of @code{awk}.)
-
-Multiple @code{BEGIN} and @code{END} sections are also useful
-for writing library functions that need to do initialization and/or cleanup
-of their own. Note that the order in which library functions are named
-on the command line will affect the order in which their @code{BEGIN}
-and @code{END} rules will be executed. Therefore you have to be careful
-how you write your library functions. (@xref{Command Line}, for more
-information on using library functions.)
+rules. They are executed in the order they appear, all the @code{BEGIN}
+rules at start-up and all the @code{END} rules at termination.
+
+Multiple @code{BEGIN} and @code{END} sections are useful for writing
+library functions, since each library can have its own @code{BEGIN} or
+@code{END} rule to do its own initialization and/or cleanup. Note that
+the order in which library functions are named on the command line
+controls the order in which their @code{BEGIN} and @code{END} rules are
+executed. Therefore you have to be careful to write such rules in
+library files so that it doesn't matter what order they are executed in.
+@xref{Command Line}, for more information on using library functions.
If an @code{awk} program only has a @code{BEGIN} rule, and no other
-rules, then the program will exit after the @code{BEGIN} rule has been
-run. Older versions of @code{awk} used to read their input until end of
-file was seen. However, if an @code{END} rule exists as well, then the
-input will be read, even if there are no other rules in the program.
+rules, then the program exits after the @code{BEGIN} rule has been run.
+(Older versions of @code{awk} used to keep reading and ignoring input
+until end of file was seen.) However, if an @code{END} rule exists as
+well, then the input will be read, even if there are no other rules in
+the program. This is necessary in case the @code{END} rule checks the
+@code{NR} variable.
@code{BEGIN} and @code{END} rules must have actions; there is no default
action for these rules since there is no current record when they run.
-@node Boolean, Conditional Patterns, BEGIN/END, Patterns
-@section Boolean Operators and Patterns
-@cindex Patterns, boolean
-@cindex Boolean patterns
-
-A boolean pattern is a combination of other patterns using the boolean
-operators ``or'' (@samp{||}), ``and'' (@samp{&&}), and ``not'' (@samp{!}),
-along with parentheses to control nesting. Whether the boolean pattern
-matches an input record is computed from whether its subpatterns match.
-
-The subpatterns of a boolean pattern can be regular expressions,
-matching expressions, comparisons, or other boolean combinations of
-such. Range patterns cannot appear inside boolean operators, since they
-don't make sense for classifying a single record, and neither can the
-special patterns @code{BEGIN} and @code{END}, which never match any
-input record.
-
-Here are descriptions of the three boolean operators.
-
-@table @code
-@item @var{pat1} && @var{pat2}
-Matches if both @var{pat1} and @var{pat2} match by themselves. For
-example, the following command prints all records in the input file
-@file{BBS-list} that contain both @samp{2400} and @samp{foo}.@refill
-
-@example
-awk '/2400/ && /foo/' BBS-list
-@end example
-
-Whether @var{pat2} matches is tested only if @var{pat1} succeeds. This
-can make a difference when @var{pat2} contains expressions that have
-side effects: in the case of @samp{/foo/ && ($2 == bar++)}, the variable
-@code{bar} is not incremented if there is no @samp{foo} in the record.@refill
-
-@item @var{pat1} || @var{pat2}
-Matches if at least one of @var{pat1} and @var{pat2} matches the current
-input record. For example, the following command prints all records in
-the input file @file{BBS-list} that contain @emph{either} @samp{2400} or
-@samp{foo}, or both.@refill
-
-@example
-awk '/2400/ || /foo/' BBS-list
-@end example
+@node Actions, Expressions, Patterns, Top
+@chapter Actions: Overview
+@cindex action, definition of
+@cindex curly braces
+@cindex action, curly braces
+@cindex action, separating statements
-Whether @var{pat2} matches is tested only if @var{pat1} fails to match.
-This can make a difference when @var{pat2} contains expressions that
-have side effects.
+An @code{awk} @dfn{program} or @dfn{script} consists of a series of
+@dfn{rules} and function definitions, interspersed. (Functions are
+described later; see @ref{User-defined}.)
-@item !@var{pat}
-Matches if @var{pat} does not match. For example, the following command
-prints all records in the input file @file{BBS-list} that do @emph{not}
-contain the string @samp{foo}.
+A rule contains a pattern and an @dfn{action}, either of which may be
+omitted. The purpose of the action is to tell @code{awk} what to do
+once a match for the pattern is found. Thus, the entire program
+looks somewhat like this:
@example
-awk '! /foo/' BBS-list
+@r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]}
+@r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]}
+@dots{}
+function @var{name} (@var{args}) @{ @dots{} @}
+@dots{}
@end example
-@end table
-
-Note that boolean patterns are built from other patterns just as boolean
-expressions are built from other expressions (@pxref{Boolean Ops}). Any
-boolean expression is also a valid boolean pattern. But the converse is
-not true: simple regular expression patterns such as @samp{/foo/} are not
-allowed in boolean expressions. Regular expressions can appear in boolean
-expressions only in conjunction with the matching operators, @samp{~}
-and @samp{!~}.
-@node Conditional Patterns, , Boolean, Patterns
-@section Conditional Patterns
-@cindex Conditional Patterns
-@cindex Patterns, Conditional
-@cindex Ternary Operator
-@cindex Operator, Ternary
+An action consists of one or more @code{awk} @dfn{statements}, enclosed
+in curly braces (@samp{@{} and @samp{@}}). Each statement specifies one
+thing to be done. The statements are separated by newlines or
+semicolons.
-Patterns may use a @dfn{conditional expression} much like the conditional
-expression of the C language. This takes the form:
+The curly braces around an action must be used even if the action
+contains only one statement, or even if it contains no statements at
+all. However, if you omit the action entirely, omit the curly braces as
+well. (An omitted action is equivalent to @samp{@{ print $0 @}}.)
-@example
-@var{pat1} ? @var{pat2} : @var{pat3}
-@end example
+Here are the kinds of statement supported in @code{awk}:
-The first pattern is evaluated. If it evaluates to @var{true}, then the
-input record is tested against @var{pat2}. Otherwise it is tested
-against @var{pat3}. The conditional pattern matches if @var{pat2} or
-@var{pat3} (whichever one is selected) matches.@refill
+@itemize @bullet
+@item
+Expressions, which can call functions or assign values to variables
+(@pxref{Expressions}). Executing this kind of statement simply computes
+the value of the expression and then ignores it. This is useful when
+the expression has side effects (@pxref{Assignment Ops}).
-@node Actions, Expressions, Patterns, Top
-@chapter Actions: The Basics
-@cindex Action, general
-@cindex Curly braces
-@cindex Action, curly braces
-@cindex Action, separating statements
-
-The @dfn{action} part of an @code{awk} rule tells @code{awk} what to do
-once a match for the pattern is found. An action consists of one or more
-@code{awk} @dfn{statements}, enclosed in curly braces (@samp{@{} and
-@samp{@}}). The curly braces must be used even if the action contains only
-one statement, or even if it contains no statements at all. Action statements
-are separated by newlines or semicolons.@refill
-
-Besides the print statements already covered (@pxref{Printing}), there are
-four kinds of action statements: expressions, control statements, compound
-statements, and function definitions.@refill
+@item
+Control statements, which specify the control flow of @code{awk}
+programs. The @code{awk} language gives you C-like constructs
+(@code{if}, @code{for}, @code{while}, and so on) as well as a few
+special ones (@pxref{Statements}).@refill
-@itemize @bullet
@item
-@cindex Expressions
-@dfn{Expressions} include assignments, arithmetic, function calls, and more
-(@pxref{Expressions}).@refill
+Compound statements, which consist of one or more statements enclosed in
+curly braces. A compound statement is used in order to put several
+statements together in the body of an @code{if}, @code{while}, @code{do}
+or @code{for} statement.
@item
-@cindex Statements
-@dfn{Control statements} specify the control flow of @code{awk} programs. The
-@code{awk} language gives you C--like constructs (@code{if}, @code{for},
-@code{while}, and so on) as well as a few special ones
-(@pxref{Statements}).@refill
+Input control, using the @code{getline} function (@pxref{Getline}),
+and the @code{next} statement (@pxref{Next Statement}).
@item
-@cindex Compound statements
-A @dfn{compound statement} is just one or more @code{awk} statements
-enclosed in curly braces. This way you can group several statements
-to form the body of an @code{if} or similar statement.
+Output statements, @code{print} and @code{printf}. @xref{Printing}.
@item
-@cindex Function definitions
-You can define @dfn{user--defined functions} for use elsewhere in the
-@code{awk} program (@pxref{User-defined}).
+Deletion statements, for deleting array elements. @xref{Delete}.
@end itemize
@iftex
-The next two chapters will cover in detail expressions and control statements,
-respectively.
-We will then detour for a chapter to talk about arrays.
-@c (@strong{This is poor organization!!!})
-Then the following two chapters will deal with compound statements and
-user--defined functions, respectively.@refill
+The next two chapters cover in detail expressions and control
+statements, respectively. We go on to treat arrays, and built-in
+functions, both of which are used in expressions. Then we proceed
+to discuss how to define your own functions.
@end iftex
@node Expressions, Statements, Actions, Top
@chapter Actions: Expressions
+@cindex expression
Expressions are the basic building block of @code{awk} actions. An
expression evaluates to a value, which you can print, test, store in a
@@ -3571,48 +3731,47 @@ variable or pass to a function.
But, beyond that, an expression can assign a new value to a variable
or a field, with an assignment operator.
-An expression can serve as a statement on its own. Most other action
-statements are made up of various combinations of expressions. As in
-other languages, expressions in @code{awk} include variables, array
-references, constants, and function calls, as well as combinations of
-these with various operators.
+An expression can serve as a statement on its own. Most other kinds of
+statement contain one or more expressions which specify data to be
+operated on. As in other languages, expressions in @code{awk} include
+variables, array references, constants, and function calls, as well as
+combinations of these with various operators.
@menu
-* Constants:: String and numeric constants.
-* Variables:: Variables give names to values for future use.
-* Fields:: Field references such as @code{$1} are also expressions.
-* Arrays:: Array element references are expressions.
-
+* Constants:: String, numeric, and regexp constants.
+* Variables:: Variables give names to values for later use.
* Arithmetic Ops:: Arithmetic operations (@samp{+}, @samp{-}, etc.)
* Concatenation:: Concatenating strings.
* Comparison Ops:: Comparison of numbers and strings with @samp{<}, etc.
* Boolean Ops:: Combining comparison expressions using boolean operators
- @samp{||} (``or''), @samp{&&} (``and'') and @samp{!} (``not'').
+ @samp{||} (``or''), @samp{&&} (``and'') and @samp{!} (``not'').
* Assignment Ops:: Changing the value of a variable or a field.
* Increment Ops:: Incrementing the numeric value of a variable.
* Conversion:: The conversion of strings to numbers and vice versa.
* Conditional Exp:: Conditional expressions select between two subexpressions
- under control of a third subexpression.
+ under control of a third subexpression.
* Function Calls:: A function call is an expression.
+* Precedence:: How various operators nest.
@end menu
-@node Constants, Variables, , Expressions
+@node Constants, Variables, Expressions, Expressions
@section Constant Expressions
-@cindex Constants, types of
-@cindex String constants
-@cindex String value
+@cindex constants, types of
+@cindex string constants
-There are two types of constants: numeric constants and string constants.
+The simplest type of expression is the @dfn{constant}, which always has
+the same value. There are three types of constant: numeric constants,
+string constants, and regular expression constants.
-@cindex Numerical constant
-@cindex Numerical value
-The @dfn{numeric constant} is a number. This number can be an integer, a
-decimal fraction, or a number in scientific (exponential) notation. Note that
-all numeric values are represented within @code{awk} in double--precision
-floating point. Here are some examples of numeric constants, which all
-have the same value:
+@cindex numeric constant
+@cindex numeric value
+A @dfn{numeric constant} stands for a number. This number can be an
+integer, a decimal fraction, or a number in scientific (exponential)
+notation. Note that all numeric values are represented within
+@code{awk} in double-precision floating point. Here are some examples
+of numeric constants, which all have the same value:
@example
105
@@ -3621,62 +3780,90 @@ have the same value:
@end example
A string constant consists of a sequence of characters enclosed in
-double--quote marks. For example:
+double-quote marks. For example:
@example
"parrot"
@end example
@noindent
-@cindex Differences between @code{gawk} and @code{awk}
-represents the string constant @samp{parrot}. Strings in @code{gawk} can
-be of any length and they can contain all the possible 8--bit ASCII
-characters including ASCII NUL. Other @code{awk} implementations may
-have difficulty with some character codes.@refill
+@c @cindex differences between @code{gawk} and @code{awk}
+represents the string whose contents are @samp{parrot}. Strings in
+@code{gawk} can be of any length and they can contain all the possible
+8-bit ASCII characters including ASCII NUL. Other @code{awk}
+implementations may have difficulty with some character codes.@refill
-@cindex Escape sequence notation
-Some characters cannot be included literally in a string. You represent
-them instead with @dfn{escape sequences}, which are character sequences
-beginning with a backslash (@samp{\}).
+@cindex escape sequence notation
+Some characters cannot be included literally in a string constant. You
+represent them instead with @dfn{escape sequences}, which are character
+sequences beginning with a backslash (@samp{\}).
-One use of the backslash is to include double--quote characters in a string.
-Since a plain double--quote would end the string, you must use @samp{\"}.
-Backslash itself is another character that can't be included normally;
-you write @samp{\\} to put one backslash in the string.
+One use of an escape sequence is to include a double-quote character in
+a string constant. Since a plain double-quote would end the string, you
+must use @samp{\"} to represent a single double-quote character as a
+part of the string. Backslash itself is another character that can't be
+included normally; you write @samp{\\} to put one backslash in the
+string. Thus, the string whose contents are the two characters
+@samp{"\} must be written @code{"\"\\"}.
Another use of backslash is to represent unprintable characters
-such as newline. While there is nothing to stop you from writing these
-characters directly in an @code{awk} program, they may look ugly.
+such as newline. While there is nothing to stop you from writing most
+of these characters directly in a string constant, they may look ugly.
+
+Here is a table of all the escape sequences used in @code{awk}:
@table @code
+@item \\
+Represents a literal backslash, @samp{\}.
+
+@item \a
+Represents the ``alert'' character, control-g, ASCII code 7.
+
@item \b
-Represents a backspaced, @samp{@ctrl{H}}.
+Represents a backspace, control-h, ASCII code 8.
@item \f
-Represents a formfeed, @samp{@ctrl{L}}.
+Represents a formfeed, control-l, ASCII code 12.
@item \n
-Represents a newline, @samp{@ctrl{J}}.
+Represents a newline, control-j, ASCII code 10.
@item \r
-Represents a carriage return, @samp{@ctrl{M}}.
+Represents a carriage return, control-m, ASCII code 13.
@item \t
-Represents a horizontal tab, @samp{@ctrl{I}}.
+Represents a horizontal tab, control-i, ASCII code 9.
@item \v
-Represents a vertical tab, @samp{@ctrl{K}}.
+Represents a vertical tab, control-k, ASCII code 11.
@item \@var{nnn}
-Represents the octal value @var{nnn}, where @var{nnn} is one to three digits
-between 0 and 7. For example, the code for the ASCII ESC (escape) character
-is @samp{\033}.@refill
+Represents the octal value @var{nnn}, where @var{nnn} are one to three
+digits between 0 and 7. For example, the code for the ASCII ESC
+(escape) character is @samp{\033}.@refill
+
+@item \x@var{hh@dots{}}
+Represents the hexadecimal value @var{hh}, where @var{hh} are hexadecimal
+digits (@samp{0} through @samp{9} and either @samp{A} through @samp{F} or
+@samp{a} through @samp{f}). Like the same construct in ANSI C, the escape
+sequence continues until the first non-hexadecimal digit is seen. However,
+using more than two hexadecimal digits produces undefined results.@refill
@end table
+A constant regexp is a regular expression description enclosed in
+slashes, such as @code{/^beginning and end$/}. Most regexps used in
+@code{awk} programs are constant, but the @samp{~} and @samp{!~}
+operators can also match computed or ``dynamic'' regexps (@pxref{Regexp
+Usage}).
+
+Constant regexps are useful only with the @samp{~} and @samp{!~} operators;
+you cannot assign them to variables or print them. They are not truly
+expressions in the usual sense.
+
@node Variables, Arithmetic Ops, Constants, Expressions
@section Variables
-@cindex Variables, user-defined
-@cindex User-defined variables
+@cindex variables, user-defined
+@cindex user-defined variables
Variables let you give names to values and refer to them later. You have
already seen variables in many of the examples. The name of a variable
@@ -3689,31 +3876,89 @@ variable's current value. Variables are given new values with
@dfn{assignment operators} and @dfn{increment operators}.
@xref{Assignment Ops}.
-@cindex Built-in variables
-@cindex Variables, built-in
-A few variables have special built--in meanings, such as @code{FS}, the
-field separator, and @code{NF}, the number of fields in the current input
-record. @xref{Special}, for a list of them. Special variables can
-be used and assigned just like all other variables, but their values
-are also used or changed automatically by @code{awk}. Each special
-variable's name is made entirely of upper case letters.
+A few variables have special built-in meanings, such as @code{FS}, the
+field separator, and @code{NF}, the number of fields in the current
+input record. @xref{Built-in Variables}, for a list of them. These
+built-in variables can be used and assigned just like all other
+variables, but their values are also used or changed automatically by
+@code{awk}. Each built-in variable's name is made entirely of upper case
+letters.
Variables in @code{awk} can be assigned either numeric values or string
values. By default, variables are initialized to the null string, which
-has the numeric value zero. So there is no need to ``initialize''
-each variable explicitly in @code{awk}, the way you would need to do
-in C or most other traditional programming languages.
+is effectively zero if converted to a number. So there is no need to
+``initialize'' each variable explicitly in @code{awk}, the way you would
+need to do in C or most other traditional programming languages.
+
+@menu
+* Assignment Options:: Setting variables on the command line and a summary
+ of command line syntax. This is an advanced method
+ of input.
+@end menu
+
+@node Assignment Options,, Variables, Variables
+@subsection Assigning Variables on the Command Line
+
+You can set any @code{awk} variable by including a @dfn{variable assignment}
+among the arguments on the command line when you invoke @code{awk}
+(@pxref{Command Line}). Such an assignment has this form:
+
+@example
+@var{variable}=@var{text}
+@end example
+
+@noindent
+With it, you can set a variable either at the beginning of the
+@code{awk} run or in between input files.
+
+If you precede the assignment with the @samp{-v} option, like this:
+
+@example
+-v @var{variable}=@var{text}
+@end example
+
+@noindent
+then the variable is set at the very beginning, before even the
+@code{BEGIN} rules are run. The @samp{-v} option and its assignment
+must precede all the file name arguments.
+
+Otherwise, the variable assignment is performed at a time determined by
+its position among the input file arguments: after the processing of the
+preceding input file argument. For example:
+
+@example
+awk '@{ print $n @}' n=4 inventory-shipped n=2 BBS-list
+@end example
+
+@noindent
+prints the value of field number @code{n} for all input records. Before
+the first file is read, the command line sets the variable @code{n}
+equal to 4. This causes the fourth field to be printed in lines from
+the file @file{inventory-shipped}. After the first file has finished,
+but before the second file is started, @code{n} is set to 2, so that the
+second field is printed in lines from @file{BBS-list}.
+
+Command line arguments are made available for explicit examination by
+the @code{awk} program in an array named @code{ARGV} (@pxref{Built-in
+Variables}).
@node Arithmetic Ops, Concatenation, Variables, Expressions
@section Arithmetic Operators
+@cindex arithmetic operators
+@cindex operators, arithmetic
+@cindex addition
+@cindex subtraction
+@cindex multiplication
+@cindex division
+@cindex remainder
+@cindex quotient
+@cindex exponentiation
-@cindex Arithmetic operators
-@cindex Operators, arithmetic
The @code{awk} language uses the common arithmetic operators when
evaluating expressions. All of these arithmetic operators follow normal
precedence rules, and work as you would expect them to. This example
-divides field 3 by field 4, adds field 2, stores the result into field
-1, and prints the results:
+divides field three by field four, adds field two, stores the result
+into field one, and prints the resulting altered input record:
@example
awk '@{ $1 = $2 + $3 / $4; print @}' inventory-shipped
@@ -3731,37 +3976,38 @@ Subtraction.
@item - @var{x}
Negation.
-@item @var{x} / @var{y}
-Division. Since all numbers in @code{awk} are double--precision
-floating point, the result is not rounded to an integer: @samp{3 / 4}
-has the value 0.75.
-
@item @var{x} * @var{y}
Multiplication.
+@item @var{x} / @var{y}
+Division. Since all numbers in @code{awk} are double-precision
+floating point, the result is not rounded to an integer: @code{3 / 4}
+has the value 0.75.
+
@item @var{x} % @var{y}
-@cindex Mod function, semantics of
-@cindex Differences between @code{gawk} and @code{awk}
-@c @strong{How are gawk and awk different here?}
+@c @cindex differences between @code{gawk} and @code{awk}
Remainder. The quotient is rounded toward zero to an integer,
multiplied by @var{y} and this result is subtracted from @var{x}.
-This operation is sometimes known as ``trunc--mod''. The following
+This operation is sometimes known as ``trunc-mod''. The following
relation always holds:
-@display
-@code{b * int(a / b) + (a % b) == a}
-@end display
+@example
+b * int(a / b) + (a % b) == a
+@end example
One undesirable effect of this definition of remainder is that
-@var{x} % @var{y} is negative if @var{x} is negative. Thus,
+@code{@var{x} % @var{y}} is negative if @var{x} is negative. Thus,
@example
-17 % 8 = -1
@end example
+In other @code{awk} implementations, the signedness of the remainder
+may be machine dependent.
+
@item @var{x} ^ @var{y}
@itemx @var{x} ** @var{y}
-Exponentiation: @var{x} raised to the @var{y} power. @samp{2 ^ 3} has
+Exponentiation: @var{x} raised to the @var{y} power. @code{2 ^ 3} has
the value 8. The character sequence @samp{**} is equivalent to
@samp{^}.
@end table
@@ -3769,9 +4015,9 @@ the value 8. The character sequence @samp{**} is equivalent to
@node Concatenation, Comparison Ops, Arithmetic Ops, Expressions
@section String Concatenation
-@cindex String operators
-@cindex Operators, string
-@cindex Concatenation
+@cindex string operators
+@cindex operators, string
+@cindex concatenation
There is only one string operation: concatenation. It does not have a
specific operator to represent it. Instead, concatenation is performed by
writing expressions next to one another, with no operator. For example:
@@ -3787,8 +4033,8 @@ produces, for the first record in @file{BBS-list}:
Field number one: aardvark
@end example
-If you hadn't put the space after the @samp{:}, the line would have run
-together. For example:
+Without the space in the string constant after the @samp{:}, the line
+would run together. For example:
@example
awk '@{ print "Field number one:" $1 @}' BBS-list
@@ -3801,16 +4047,46 @@ produces, for the first record in @file{BBS-list}:
Field number one:aardvark
@end example
+Since string concatenation does not have an explicit operator, it is
+often necessary to insure that it happens where you want it to by
+enclosing the items to be concatenated in parentheses. For example, the
+following code fragment does not concatenate @code{file} and @code{name}
+as you might expect:
+
+@example
+file = "file"
+name = "name"
+print "something meaningful" > file name
+@end example
+
+@noindent
+It is necessary to use the following:
+
+@example
+print "something meaningful" > (file name)
+@end example
+
+We recommend you use parentheses around concatenation in all but the
+most common contexts (such as in the right-hand operand of @samp{=}).
+
+@ignore
+@code{gawk} actually now allows a concatenation on the right hand
+side of a @code{>} redirection, but other @code{awk}s don't. So for
+now we won't mention that fact.
+@end ignore
+
@node Comparison Ops, Boolean Ops, Concatenation, Expressions
@section Comparison Expressions
-@cindex Comparison expressions
-@cindex Expressions, comparison
-@cindex Relational operators
-@cindex Operators, relational
+@cindex comparison expressions
+@cindex expressions, comparison
+@cindex relational operators
+@cindex operators, relational
+@cindex regexp operators
-@dfn{Comparison expressions} use @dfn{relational operators} to compare
-strings or numbers. The relational operators are the same as in C.
-Here is a table of them:
+@dfn{Comparison expressions} compare strings or numbers for
+relationships such as equality. They are written using @dfn{relational
+operators}, which are a superset of those in C. Here is a table of
+them:
@table @code
@item @var{x} < @var{y}
@@ -3831,11 +4107,11 @@ True if @var{x} is equal to @var{y}.
@item @var{x} != @var{y}
True if @var{x} is not equal to @var{y}.
-@item @var{x} ~ @var{regexp}
-True if regexp @var{regexp} matches the string @var{x}.
+@item @var{x} ~ @var{y}
+True if the string @var{x} matches the regexp denoted by @var{y}.
-@item @var{x} !~ @var{regexp}
-True if regexp @var{regexp} does not match the string @var{x}.
+@item @var{x} !~ @var{y}
+True if the string @var{x} does not match the regexp denoted by @var{y}.
@item @var{subscript} in @var{array}
True if array @var{array} has an element with the subscript @var{subscript}.
@@ -3866,30 +4142,59 @@ $1 ~ /foo/
@noindent
has the value 1 if the first field contains @samp{foo}.
+The right hand operand of the @samp{~} and @samp{!~} operators may be
+either a constant regexp (@code{/@dots{}/}), or it may be an ordinary
+expression, in which case the value of the expression as a string is a
+dynamic regexp (@pxref{Regexp Usage}).
+
+@cindex regexp as expression
+In very recent implementations of @code{awk}, a constant regular
+expression in slashes by itself is also an expression. The regexp
+@code{/@var{regexp}/} is an abbreviation for this comparison expression:
+
+@example
+$0 ~ /@var{regexp}/
+@end example
+
+In some contexts it may be necessary to write parentheses around the
+regexp to avoid confusing the @code{gawk} parser. For example,
+@code{(/x/ - /y/) > threshold} is not allowed, but @code{((/x/) - (/y/))
+> threshold} parses properly.
+
+One special place where @code{/foo/} is @emph{not} an abbreviation for
+@code{$0 ~ /foo/} is when it is the right-hand operand of @samp{~} or
+@samp{!~}!
+
@node Boolean Ops, Assignment Ops, Comparison Ops, Expressions
-@section Boolean Operators
-@cindex Expressions, boolean
-@cindex Boolean expressions
-@cindex Operators, boolean
-@cindex Boolean operators
-
-A boolean expression is combination of comparison expressions or matching
-expressions, using the boolean operators ``or'' (@samp{||}), ``and''
-(@samp{&&}), and ``not'' (@samp{!}), along with parentheses to control
-nesting. The truth of the boolean expression is computed by combining the
-truth values of the component expressions.
+@section Boolean Expressions
+@cindex expressions, boolean
+@cindex boolean expressions
+@cindex operators, boolean
+@cindex boolean operators
+@cindex logical operations
+@cindex and operator
+@cindex or operator
+@cindex not operator
+
+A @dfn{boolean expression} is combination of comparison expressions or
+matching expressions, using the @dfn{boolean operators} ``or''
+(@samp{||}), ``and'' (@samp{&&}), and ``not'' (@samp{!}), along with
+parentheses to control nesting. The truth of the boolean expression is
+computed by combining the truth values of the component expressions.
Boolean expressions can be used wherever comparison and matching
expressions can be used. They can be used in @code{if} and @code{while}
-statements. They have numeric values (1 if true, 0 if false).
+statements. They have numeric values (1 if true, 0 if false), which
+come into place if the result of the boolean expression is stored in a
+variable, or used in arithmetic.
In addition, every boolean expression is also a valid boolean pattern, so
you can use it as a pattern to control the execution of rules.
Here are descriptions of the three boolean operators, with an example of
-each. It may be instructive to compare these examples with the analogous
-examples of boolean patterns (@pxref{Boolean}), which use the same boolean
-operators in patterns instead of expressions.
+each. It may be instructive to compare these examples with the
+analogous examples of boolean patterns (@pxref{Boolean Patterns}), which
+use the same boolean operators in patterns instead of expressions.
@table @code
@item @var{boolean1} && @var{boolean2}
@@ -3903,7 +4208,7 @@ if ($0 ~ /2400/ && $0 ~ /foo/) print
The subexpression @var{boolean2} is evaluated only if @var{boolean1}
is true. This can make a difference when @var{boolean2} contains
-expressions that have side effects: in the case of @samp{$0 ~ /foo/ &&
+expressions that have side effects: in the case of @code{$0 ~ /foo/ &&
($2 == bar++)}, the variable @code{bar} is not incremented if there is
no @samp{foo} in the record.
@@ -3918,7 +4223,7 @@ awk '@{ if ($0 ~ /2400/ || $0 ~ /foo/) print @}' BBS-list
@end example
The subexpression @var{boolean2} is evaluated only if @var{boolean1}
-is true. This can make a difference when @var{boolean2} contains
+is false. This can make a difference when @var{boolean2} contains
expressions that have side effects.
@item !@var{boolean}
@@ -3932,10 +4237,11 @@ awk '@{ if (! ($0 ~ /foo/)) print @}' BBS-list
@end table
@node Assignment Ops, Increment Ops, Boolean Ops, Expressions
-@section Assignment Operators
+@section Assignment Expressions
+@cindex assignment operators
+@cindex operators, assignment
+@cindex expressions, assignment
-@cindex Assignment operators
-@cindex Operators, assignment
An @dfn{assignment} is an expression that stores a new value into a
variable. For example, let's assign the value 1 to the variable
@code{z}:@refill
@@ -3947,19 +4253,6 @@ z = 1
After this expression is executed, the variable @code{z} has the value 1.
Whatever old value @code{z} had before the assignment is forgotten.
-The @code{=} sign is called an @dfn{assignment operator}. It is the
-simplest assignment operator because the value of the right--hand
-operand is stored unchanged.
-
-@cindex Lvalue
-The left--hand operand of an assignment can be a variable
-(@pxref{Variables}), a field (@pxref{Changing Fields}) or an array
-element (@pxref{Arrays}). These are all called @dfn{lvalues}, which
-means they can appear on the left side of an assignment operator. The
-right--hand operand may be any expression; it produces the new value
-which the assignment stores in the specified variable, field or array
-element.
-
Assignments can store string values also. For example, this would store
the value @code{"this food is good"} in the variable @code{message}:
@@ -3972,6 +4265,27 @@ message = "this " thing " is " predicate
@noindent
(This also illustrates concatenation of strings.)
+The @samp{=} sign is called an @dfn{assignment operator}. It is the
+simplest assignment operator because the value of the right-hand
+operand is stored unchanged.
+
+@cindex side effect
+Most operators (addition, concatenation, and so on) have no effect
+except to compute a value. If you ignore the value, you might as well
+not use the operator. An assignment operator is different; it does
+produce a value, but even if you ignore the value, the assignment still
+makes itself felt through the alteration of the variable. We call this
+a @dfn{side effect}.
+
+@cindex lvalue
+The left-hand operand of an assignment need not be a variable
+(@pxref{Variables}); it can also be a field (@pxref{Changing Fields}) or
+an array element (@pxref{Arrays}). These are all called @dfn{lvalues},
+which means they can appear on the left-hand side of an assignment operator.
+The right-hand operand may be any expression; it produces the new value
+which the assignment stores in the specified variable, field or array
+element.
+
It is important to note that variables do @emph{not} have permanent types.
The type of a variable is simply the type of whatever value it happens
to hold at the moment. In the following program fragment, the variable
@@ -3989,7 +4303,7 @@ When the second assignment gives @code{foo} a string value, the fact that
it previously had a numeric value is forgotten.
An assignment is an expression, so it has a value: the same value that
-is assigned. Thus, @samp{z = 1} as an expression has the value 1.
+is assigned. Thus, @code{z = 1} as an expression has the value 1.
One consequence of this is that you can write multiple assignments together:
@example
@@ -3998,19 +4312,19 @@ x = y = z = 0
@noindent
stores the value 0 in all three variables. It does this because the
-value of @samp{z = 0}, which is 0, is stored into @code{y}, and then
-the value of @samp{y = z = 0}, which is 0, is stored into @code{x}.
+value of @code{z = 0}, which is 0, is stored into @code{y}, and then
+the value of @code{y = z = 0}, which is 0, is stored into @code{x}.
You can use an assignment anywhere an expression is called for. For
-example, it is valid to write @samp{x != (y = 1)} to set @code{y} to 1
+example, it is valid to write @code{x != (y = 1)} to set @code{y} to 1
and then test whether @code{x} equals 1. But this style tends to make
-programs hard to read; except in a one--shot program, you should
+programs hard to read; except in a one-shot program, you should
rewrite it to get rid of such nesting of assignments. This is never very
hard.
-Aside from @code{=}, there are several other assignment operators that
+Aside from @samp{=}, there are several other assignment operators that
do arithmetic with the old value of the variable. For example, the
-operator @code{+=} computes a new value by adding the right--hand value
+operator @samp{+=} computes a new value by adding the right-hand value
to the old value of the variable. Thus, the following assignment adds
5 to the value of @code{foo}:
@@ -4029,7 +4343,7 @@ foo = foo + 5
Use whichever one makes the meaning of your program clearer.
Here is a table of the arithmetic assignment operators. In each
-case, the right--hand operand is an expression whose value is converted
+case, the right-hand operand is an expression whose value is converted
to a number.
@table @code
@@ -4057,39 +4371,39 @@ Raises @var{lvalue} to the power @var{power}.
@node Increment Ops, Conversion, Assignment Ops, Expressions
@section Increment Operators
-@cindex Increment operators
-@cindex Operators, increment
+@cindex increment operators
+@cindex operators, increment
@dfn{Increment operators} increase or decrease the value of a variable
by 1. You could do the same thing with an assignment operator, so
the increment operators add no power to the @code{awk} language; but they
are convenient abbreviations for something very common.
-The operator to add 1 is written @code{++}. There are two ways to use
-this operator: pre--incrementation and post--incrementation.
+The operator to add 1 is written @samp{++}. It can be used to increment
+a variable either before or after taking its value.
-To pre--increment a variable @var{v}, write @code{++@var{v}}. This adds
+To pre-increment a variable @var{v}, write @code{++@var{v}}. This adds
1 to the value of @var{v} and that new value is also the value of this
expression. The assignment expression @code{@var{v} += 1} is completely
equivalent.
-Writing the @code{++} after the variable specifies post--increment. This
+Writing the @samp{++} after the variable specifies post-increment. This
increments the variable value just the same; the difference is that the
value of the increment expression itself is the variable's @emph{old}
value. Thus, if @code{foo} has value 4, then the expression @code{foo++}
has the value 4, but it changes the value of @code{foo} to 5.
-The post--increment @code{foo++} is nearly equivalent to writing @samp{(foo
+The post-increment @code{foo++} is nearly equivalent to writing @code{(foo
+= 1) - 1}. It is not perfectly equivalent because all numbers in
@code{awk} are floating point: in floating point, @code{foo + 1 - 1} does
-not necessarily equal @code{foo}. But the difference will be minute as
+not necessarily equal @code{foo}. But the difference is minute as
long as you stick to numbers that are fairly small (less than a trillion).
Any lvalue can be incremented. Fields and array elements are incremented
just like variables.
-The decrement operator @code{--} works just like @code{++} except that
-it subtracts 1 instead of adding. Like @code{++}, it can be used before
-the lvalue to pre--decrement or after it to post--decrement.
+The decrement operator @samp{--} works just like @samp{++} except that
+it subtracts 1 instead of adding. Like @samp{++}, it can be used before
+the lvalue to pre-decrement or after it to post-decrement.
Here is a summary of increment and decrement expressions.
@@ -4108,20 +4422,20 @@ decrements @var{lvalue} and delivers the value that results.
@item @var{lvalue}--
Like @code{@var{lvalue}++}, but instead of adding, it subtracts. It
-decrements @var{lvalue}. The value of the expression is the @emph{old}
+decrements @var{lvalue}. The value of the expression is the @emph{old}
value of @var{lvalue}.
@end table
@node Conversion, Conditional Exp, Increment Ops, Expressions
@section Conversion of Strings and Numbers
-@cindex Conversion of strings and numbers
-Strings are converted to numbers, and numbers to strings, if the context of
-your @code{awk} statement demands it. For example, if the values of
-@code{foo} or @code{bar} in the expression @code{foo + bar} happen to be
-strings, they are converted to numbers before the addition is performed.
-If numeric values appear in string concatenation, they are converted
-to strings. Consider this:@refill
+@cindex conversion of strings and numbers
+Strings are converted to numbers, and numbers to strings, if the context
+of the @code{awk} program demands it. For example, if the value of
+either @code{foo} or @code{bar} in the expression @code{foo + bar}
+happens to be a string, it is converted to a number before the addition
+is performed. If numeric values appear in string concatenation, they
+are converted to strings. Consider this:@refill
@example
two = 2; three = 3
@@ -4129,29 +4443,31 @@ print (two three) + 4
@end example
@noindent
-This eventually prints the (numeric) value @samp{27}. The numeric
-variables @code{two} and @code{three} are converted to strings and concatenated
-together, and the resulting string is converted back to a number before
-adding @samp{4}. The resulting numeric value @samp{27} is printed.
+This eventually prints the (numeric) value 27. The numeric values of
+the variables @code{two} and @code{three} are converted to strings and
+concatenated together, and the resulting string is converted back to the
+number 23, to which 4 is then added.
If, for some reason, you need to force a number to be converted to a
string, concatenate the null string with that number. To force a string
-to be converted to a number, add zero to that string. Strings that
-can't be interpreted as valid numbers are given the numeric value
-zero.@refill
+to be converted to a number, add zero to that string.
+
+Strings are converted to numbers by interpreting them as numerals:
+@code{"2.5"} converts to 2.5, and @code{"1e3"} converts to 1000.
+Strings that can't be interpreted as valid numbers are converted to
+zero.
@vindex OFMT
The exact manner in which numbers are converted into strings is controlled
-by the @code{awk} special variable @code{OFMT} (@pxref{Special}).
+by the @code{awk} built-in variable @code{OFMT} (@pxref{Built-in Variables}).
Numbers are converted using a special
version of the @code{sprintf} function (@pxref{Built-in}) with @code{OFMT}
as the format specifier.@refill
@code{OFMT}'s default value is @code{"%.6g"}, which prints a value with
-at least six significant digits. You might want to change it to specify
-more precision, if your version of @code{awk} uses double precision
-arithmetic. Double precision on most modern machines gives you 16 or 17
-decimal digits of precision.@refill
+at least six significant digits. For some applications you will want to
+change it to specify more precision. Double precision on most modern
+machines gives you 16 or 17 decimal digits of precision.
Strange results can happen if you set @code{OFMT} to a string that doesn't
tell @code{sprintf} how to format floating point numbers in a useful way.
@@ -4160,8 +4476,8 @@ converted to the same constant string.@refill
@node Conditional Exp, Function Calls, Conversion, Expressions
@section Conditional Expressions
-@cindex Conditional expression
-@cindex Expression, conditional
+@cindex conditional expression
+@cindex expression, conditional
A @dfn{conditional expression} is a special kind of expression with
three operands. It allows you to use one expression's value to select
@@ -4198,13 +4514,13 @@ x == y ? a[i++] : b[i++]
@noindent
This is guaranteed to increment @code{i} exactly once, because each time
-one or the other of the two increment expressions will be executed
-and the other will not be.
+one or the other of the two increment expressions is executed,
+and the other is not.
-@node Function Calls, , Conditional Exp, Expressions
+@node Function Calls, Precedence, Conditional Exp, Expressions
@section Function Calls
-@cindex Function call
-@cindex Calling a function
+@cindex function call
+@cindex calling a function
A @dfn{function} is a name for a particular calculation. Because it has
a name, you can ask for it by name at any point in the program. For
@@ -4212,40 +4528,45 @@ example, the function @code{sqrt} computes the square root of a number.
A fixed set of functions are @dfn{built in}, which means they are
available in every @code{awk} program. The @code{sqrt} function is one
-of these. @xref{Built-in}, for a list of built--in functions and their
+of these. @xref{Built-in}, for a list of built-in functions and their
descriptions. In addition, you can define your own functions in the
program for use elsewhere in the same program. @xref{User-defined},
for how to do this.
-@cindex Arguments in function call
+@cindex arguments in function call
The way to use a function is with a @dfn{function call} expression,
which consists of the function name followed by a list of
@dfn{arguments} in parentheses. The arguments are expressions which
give the raw materials for the calculation that the function will do.
When there is more than one argument, they are separated by commas. If
there are no arguments, write just @samp{()} after the function name.
+Here are some examples:
+
+@example
+sqrt(x**2 + y**2) # @r{One argument}
+atan2(y, x) # @r{Two arguments}
+rand() # @r{No arguments}
+@end example
@strong{Do not put any space between the function name and the
-open--parenthesis!} A user--defined function name looks just like the name of
+open-parenthesis!} A user-defined function name looks just like the name of
a variable, and space would make the expression look like concatenation
of a variable with an expression inside parentheses. Space before the
-parenthesis is harmless with built--in functions, but it is best not to get
-into the habit of using space, lest you do likewise for a user--defined
+parenthesis is harmless with built-in functions, but it is best not to get
+into the habit of using space, lest you do likewise for a user-defined
function one day by mistake.
-Each function needs a particular number of arguments. For example, the
-@code{sqrt} function must be called with a single argument, like this:
+Each function expects a particular number of arguments. For example, the
+@code{sqrt} function must be called with a single argument, the number
+to take the square root of:
@example
sqrt(@var{argument})
@end example
-@noindent
-The argument is the number to take the square root of.
-
-Some of the built--in functions allow you to omit the final argument.
-If you do so, they will use a reasonable default. @xref{Built-in},
-for full details. If arguments are omitted in calls to user--defined
+Some of the built-in functions allow you to omit the final argument.
+If you do so, they use a reasonable default. @xref{Built-in},
+for full details. If arguments are omitted in calls to user-defined
functions, then those arguments are treated as local variables,
initialized to the null string (@pxref{User-defined}).
@@ -4262,78 +4583,188 @@ square root of each one:
awk '@{ print "The square root of", $1, "is", sqrt($1) @}'
@end example
+@node Precedence,, Function Calls, Expressions
+@section Operator Precedence: How Operators Nest
+@cindex precedence
+@cindex operator precedence
+
+@dfn{Operator precedence} determines how operators are grouped, when
+different operators appear close by in one expression. For example,
+@samp{*} has higher precedence than @samp{+}; thus, @code{a + b * c}
+means to multiply @code{b} and @code{c}, and then add @code{a} to the
+product.
+
+You can overrule the precedence of the operators by writing parentheses
+yourself. You can think of the precedence rules as saying where the
+parentheses are assumed if you do not write parentheses yourself. In
+fact, it is wise always to use parentheses whenever you have an unusual
+combination of operators, because other people who read the program may
+not remember what the precedence is in this case. You might forget,
+too; then you could make a mistake. Explicit parentheses will prevent
+any such mistake.
+
+When operators of equal precedence are used together, the leftmost
+operator groups first, except for the assignment, conditional and
+and exponentiation operators, which group in the opposite order.
+Thus, @code{a - b + c} groups as @code{(a - b) + c};
+@code{a = b = c} groups as @code{a = (b = c)}.
+
+The precedence of prefix unary operators does not matter as long as only
+unary operators are involved, because there is only one way to parse
+them---innermost first. Thus, @code{$++i} means @code{$(++i)} and
+@code{++$x} means @code{++($x)}. However, when another operator follows
+the operand, then the precedence of the unary operators can matter.
+Thus, @code{$x**2} means @code{($x)**2}, but @code{-x**2} means
+@code{-(x**2)}, because @samp{-} has lower precedence than @samp{**}
+while @samp{$} has higher precedence.
+
+Here is a table of the operators of @code{awk}, in order of increasing
+precedence:
+
+@table @asis
+@item assignment
+@samp{=}, @samp{+=}, @samp{-=}, @samp{*=}, @samp{/=}, @samp{%=},
+@samp{^=}, @samp{**=}. These operators group right-to-left.
+
+@item conditional
+@samp{?:}. These operators group right-to-left.
+
+@item logical ``or''.
+@samp{||}.
+
+@item logical ``and''.
+@samp{&&}.
+
+@item array membership
+@code{in}.
+
+@item matching
+@samp{~}, @samp{!~}.
+
+@item relational, and redirection
+The relational operators and the redirections have the same precedence
+level. Characters such as @samp{>} serve both as relationals and as
+redirections; the context distinguishes between the two meanings.
+
+The relational operators are @samp{<}, @samp{<=}, @samp{==}, @samp{!=},
+@samp{>=} and @samp{>}.
+
+The I/O redirection operators are @samp{<}, @samp{>}, @samp{>>} and
+@samp{|}.
+
+Note that I/O redirection operators in @code{print} and @code{printf}
+statements belong to the statement level, not to expressions. The
+redirection does not produce an expression which could be the operand of
+another operator. As a result, it does not make sense to use a
+redirection operator near another operator of lower precedence, without
+parentheses. Such combinations, for example @samp{print foo > a ? b :
+c}, result in syntax errors.
+
+@item concatentation
+No special token is used to indicate concatenation.
+The operands are simply written side by side.
+@c This is supposedly being fixed
+@ignore
+Concatenation has the same precedence as relational and redirection
+operators. These operators nest left to right. Thus, @code{4 5 > 6}
+concatenates first, yielding 1, while @code{6 < 4 5} compares first, and
+yields @code{"05"}.
+@end ignore
+
+@item add, subtract
+@samp{+}, @samp{-}.
+
+@item multiply, divide, mod
+@samp{*}, @samp{/}, @samp{%}.
+
+@item unary plus, minus, ``not''
+@samp{+}, @samp{-}, @samp{!}.
+
+@item exponentiation
+@samp{^}, @samp{**}. These operators group right-to-left.
+
+@item increment, decrement
+@samp{++}, @samp{--}.
+
+@item field
+@samp{$}.
+@end table
+
@node Statements, Arrays, Expressions, Top
-@chapter Actions: Statements
-@cindex Statements
+@chapter Actions: Control Statements
+@cindex control statement
@dfn{Control statements} such as @code{if}, @code{while}, and so on
control the flow of execution in @code{awk} programs. Most of the
control statements in @code{awk} are patterned on similar statements in
C.
-The simplest kind of statement is an expression. The other kinds of
-statements start with special keywords such as @code{if} and
-@code{while}, to distinguish them from simple expressions.
+All the control statements start with special keywords such as @code{if}
+and @code{while}, to distinguish them from simple expressions.
-In all the examples in this chapter, @var{body} can be either a single
-statement or a group of statements. Groups of statements are enclosed
-in braces, and separated by newlines or semicolons.@refill
+Many control statements contain other statements; for example, the
+@code{if} statement contains another statement which may or may not be
+executed. The contained statement is called the @dfn{body}. If you
+want to include more than one statement in the body, group them into a
+single compound statement with curly braces, separating them with
+newlines or semicolons.
@menu
-* Expressions:: One kind of statement simply computes an expression.
+* If Statement:: Conditionally execute some @code{awk} statements.
-* If:: Conditionally execute some @code{awk} statements.
+* While Statement:: Loop until some condition is satisfied.
-* While:: Loop until some condition is satisfied.
+* Do Statement:: Do specified action while looping until some
+ condition is satisfied.
-* Do:: Do specified action while looping until some
- condition is satisfied.
+* For Statement:: Another looping statement, that provides
+ initialization and increment clauses.
-* For:: Another looping statement, that provides
- initialization and increment clauses.
+* Break Statement:: Immediately exit the innermost enclosing loop.
-* Break:: Immediately exit the innermost enclosing loop.
+* Continue Statement:: Skip to the end of the innermost enclosing loop.
-* Continue:: Skip to the end of the innermost enclosing loop.
+* Next Statement:: Stop processing the current input record.
-* Next:: Stop processing the current input record.
-
-* Exit:: Stop execution of @code{awk}.
+* Exit Statement:: Stop execution of @code{awk}.
@end menu
-@node If, While, , Statements
+@node If Statement, While Statement, Statements, Statements
@section The @code{if} Statement
@cindex @code{if} statement
-The @code{if}-@code{else} statement is @code{awk}'s decision--making
-statement. The @code{else} part of the statement is optional.@refill
+The @code{if}-@code{else} statement is @code{awk}'s decision-making
+statement. It looks like this:@refill
-@display
-@code{if (@var{condition}) @var{body1} else @var{body2}}
-@end display
+@example
+if (@var{condition}) @var{then-body} @r{[}else @var{else-body}@r{]}
+@end example
@noindent
Here @var{condition} is an expression that controls what the rest of the
-statement will do. If @var{condition} is true, @var{body1} is executed;
-otherwise, @var{body2} is executed (assuming that the @code{else} clause
-is present). The condition is considered true if it is nonzero or
-nonnull.
+statement will do. If @var{condition} is true, @var{then-body} is
+executed; otherwise, @var{else-body} is executed (assuming that the
+@code{else} clause is present). The @code{else} part of the statement is
+optional. The condition is considered false if its value is zero or
+the null string, true otherwise.@refill
Here is an example:
@example
-awk '@{ if (x % 2 == 0)
- print "x is even"
- else
- print "x is odd" @}'
+if (x % 2 == 0)
+ print "x is even"
+else
+ print "x is odd"
@end example
-In this example, if the statement containing @code{x} is found to be true
-(that is, x is divisible by 2), then the first @code{print} statement is
-executed, otherwise the second @code{print} statement is performed.@refill
+In this example, if the expression @code{x % 2 == 0} is true (that is,
+the value of @code{x} is divisible by 2), then the first @code{print}
+statement is executed, otherwise the second @code{print} statement is
+performed.@refill
-If the @code{else} appears on the same line as @var{body1}, and @var{body1}
-is a single statement, then a semicolon must separate @var{body1} from
+If the @code{else} appears on the same line as @var{then-body}, and
+@var{then-body} is not a compound statement (i.e., not surrounded by
+curly braces), then a semicolon must separate @var{then-body} from
@code{else}. To illustrate this, let's rewrite the previous example:
@group
@@ -4344,20 +4775,20 @@ awk '@{ if (x % 2 == 0) print "x is even"; else
@end group
@noindent
-If you forget the @samp{;}, @code{awk} won't be able to parse it, and
-you will get a syntax error.
+If you forget the @samp{;}, @code{awk} won't be able to parse the
+statement, and you will get a syntax error.
We would not actually write this example this way, because a human
reader might fail to see the @code{else} if it were not the first thing
on its line.
-@node While, Do, If, Statements
+@node While Statement, Do Statement, If Statement, Statements
@section The @code{while} Statement
@cindex @code{while} statement
-@cindex Loop
-@cindex Body of a loop
+@cindex loop
+@cindex body of a loop
-In programming, a loop means a part of a program that is (or at least can
+In programming, a @dfn{loop} means a part of a program that is (or at least can
be) executed two or more times in succession.
The @code{while} statement is the simplest looping statement in
@@ -4375,11 +4806,15 @@ and @var{condition} is an expression that controls how long the loop
keeps running.
The first thing the @code{while} statement does is test @var{condition}.
-If @var{condition} is true, it executes the statement @var{body}. After
-@var{body} has been executed, @var{condition} is tested again and this
-process is repeated until @var{condition} is no longer true. If
-@var{condition} is initially false, the body of the loop is never
-executed.@refill
+If @var{condition} is true, it executes the statement @var{body}.
+(Truth, as usual in @code{awk}, means that the value of @var{condition}
+is not zero and not a null string.) After @var{body} has been executed,
+@var{condition} is tested again, and if it is still true, @var{body} is
+executed again. This process repeats until @var{condition} is no longer
+true. If @var{condition} is initially false, the body of the loop is
+never executed.@refill
+
+This example prints the first three fields of each record, one per line.
@example
awk '@{ i = 1
@@ -4391,21 +4826,23 @@ awk '@{ i = 1
@end example
@noindent
-This example prints the first three input fields, one per line.
+Here the body of the loop is a compound statement enclosed in braces,
+containing two statements.
The loop works like this: first, the value of @code{i} is set to 1.
Then, the @code{while} tests whether @code{i} is less than or equal to
three. This is the case when @code{i} equals one, so the @code{i}-th
field is printed. Then the @code{i++} increments the value of @code{i}
-and the loop repeats.
+and the loop repeats. The loop terminates when @code{i} reaches 4.
-When @code{i} reaches 4, the loop exits. Here @var{body} is a compound
-statement enclosed in braces. As you can see, a newline is not required
-between the condition and the body; but using one makes the program clearer
-unless the body is a compound statement or is very simple.
+As you can see, a newline is not required between the condition and the
+body; but using one makes the program clearer unless the body is a
+compound statement or is very simple. The newline after the open-brace
+that begins the compound statement is not required either, but the
+program would be hard to read without it.
-@node Do, For, While, Statements
-@section The @code{do}--@code{while} Statement
+@node Do Statement, For Statement, While Statement, Statements
+@section The @code{do}-@code{while} Statement
The @code{do} loop is a variation of the @code{while} looping statement.
The @code{do} loop executes the @var{body} once, then repeats @var{body}
@@ -4430,7 +4867,7 @@ while (@var{condition})
@end example
@noindent
-This statement will not execute @var{body} even once if @var{condition}
+This statement does not execute @var{body} even once if @var{condition}
is false to begin with.
Here is an example of a @code{do} statement:
@@ -4445,12 +4882,12 @@ awk '@{ i = 1
@end example
@noindent
-prints each input record ten times. It isn't a very
-realistic example, since in this case an ordinary @code{while} would do
-just as well. But this is normal; there is only occasionally a real
-use for a @code{do} statement.@refill
+prints each input record ten times. It isn't a very realistic example,
+since in this case an ordinary @code{while} would do just as well. But
+this reflects actual experience; there is only occasionally a real use
+for a @code{do} statement.@refill
-@node For, Break, Do, Statements
+@node For Statement, Break Statement, Do Statement, Statements
@section The @code{for} Statement
@cindex @code{for} statement
@@ -4496,19 +4933,19 @@ this context, but it is not supported in @code{awk}.
Most often, @var{increment} is an increment expression, as in the
example above. But this is not required; it can be any expression
-whatever. For example, this statement prints odd numbers from 1 to 100:
+whatever. For example, this statement prints all the powers of 2
+between 1 and 100:
@example
-# print odd numbers from 1 to 100
-for (i = 1; i <= 100; i += 2)
+for (i = 1; i <= 100; i *= 2)
print i
@end example
-Any of the three expressions following @code{for} may be omitted if you
-don't want it to do anything. Thus, @w{@samp{for (;x > 0;)}} is equivalent
-to @w{@samp{while (x > 0)}}.
-If the @var{condition} part is empty, it is treated as @var{true},
-effectively yielding an infinite loop.@refill
+Any of the three expressions in the parentheses following @code{for} may
+be omitted if there is nothing to be done there. Thus, @w{@samp{for (;x
+> 0;)}} is equivalent to @w{@samp{while (x > 0)}}. If the
+@var{condition} is omitted, it is treated as @var{true}, effectively
+yielding an infinite loop.@refill
In most cases, a @code{for} loop is an abbreviation for a @code{while}
loop, as shown here:
@@ -4522,39 +4959,39 @@ while (@var{condition}) @{
@end example
@noindent
-(The only exception is when the @code{continue} statement
-(@pxref{Continue}) is used inside the loop; changing a @code{for} statement
-to a @code{while} statement in this way can change the effect of the
-@code{continue} statement inside the loop.)@refill
-
-The @code{awk} language has a @code{for} statement in addition to a
-@code{while} statement because often a @code{for} loop is both less work to
-type and more natural to think of. Counting the number of iterations is
-very common in loops. It can be easier to think of this counting as part
-of looping rather than as something to do inside the loop.
-
-The next section has more complicated examples of @code{for} loops.
+The only exception is when the @code{continue} statement
+(@pxref{Continue Statement}) is used inside the loop; changing a
+@code{for} statement to a @code{while} statement in this way can change
+the effect of the @code{continue} statement inside the loop.
There is an alternate version of the @code{for} loop, for iterating over
all the indices of an array:
@example
for (i in array)
- @var{process} array[i]
+ @var{do something with} array[i]
@end example
@noindent
@xref{Arrays}, for more information on this version of the @code{for} loop.
-@node Break, Continue, For, Statements
+The @code{awk} language has a @code{for} statement in addition to a
+@code{while} statement because often a @code{for} loop is both less work to
+type and more natural to think of. Counting the number of iterations is
+very common in loops. It can be easier to think of this counting as part
+of looping rather than as something to do inside the loop.
+
+The next section has more complicated examples of @code{for} loops.
+
+@node Break Statement, Continue Statement, For Statement, Statements
@section The @code{break} Statement
@cindex @code{break} statement
-@cindex Loops, breaking out of
+@cindex loops, exiting
-The @code{break} statement jumps out of the innermost @code{for}, @code{while},
-or @code{do}--@code{while} loop that encloses it.
-The following example finds the
-smallest divisor of any number, and also identifies prime numbers:@refill
+The @code{break} statement jumps out of the innermost @code{for},
+@code{while}, or @code{do}-@code{while} loop that encloses it. The
+following example finds the smallest divisor of any integer, and also
+identifies prime numbers:@refill
@example
awk '# find smallest divisor of num
@@ -4569,10 +5006,10 @@ awk '# find smallest divisor of num
@end example
When the remainder is zero in the first @code{if} statement, @code{awk}
-immediately @dfn{breaks} out of the containing @code{for} loop. This means
+immediately @dfn{breaks out} of the containing @code{for} loop. This means
that @code{awk} proceeds immediately to the statement following the loop
and continues processing. (This is very different from the @code{exit}
-statement (@pxref{Exit}) which stops the entire @code{awk}
+statement (@pxref{Exit Statement}) which stops the entire @code{awk}
program.)@refill
Here is another program equivalent to the previous one. It illustrates how
@@ -4595,12 +5032,12 @@ awk '# find smallest divisor of num
@}'
@end example
-@node Continue, Next, Break, Statements
+@node Continue Statement, Next Statement, Break Statement, Statements
@section The @code{continue} Statement
@cindex @code{continue} statement
The @code{continue} statement, like @code{break}, is used only inside
-@code{for}, @code{while}, and @code{do}--@code{while} loops. It skips
+@code{for}, @code{while}, and @code{do}-@code{while} loops. It skips
over the rest of the loop body, causing the next cycle around the loop
to begin immediately. Contrast this with @code{break}, which jumps out
of the loop altogether. Here is an example:@refill
@@ -4621,22 +5058,23 @@ END @{
@}
@end example
-If any of the input records contain the string @samp{ignore}, this example
-skips the print statement and continues back to the first statement in the
-loop.
+If one of the input records contains the string @samp{ignore}, this
+example skips the print statement for that record, and continues back to
+the first statement in the loop.
This isn't a practical example of @code{continue}, since it would be
just as easy to write the loop like this:
@example
for (x in names)
- if (x !~ /ignore/)
- print x
+ if (names[x] !~ /ignore/)
+ print names[x]
@end example
-The @code{continue} statement causes @code{awk} to skip the rest of what is
-inside a @code{for} loop, but it resumes execution with the increment part
-of the @code{for} loop. The following program illustrates this fact:@refill
+The @code{continue} statement in a @code{for} loop directs @code{awk} to
+skip the rest of the body of the loop, and resume execution with the
+increment-expression of the @code{for} statement. The following program
+illustrates this fact:@refill
@example
awk 'BEGIN @{
@@ -4652,9 +5090,26 @@ awk 'BEGIN @{
@noindent
This program prints all the numbers from 0 to 20, except for 5, for
which the @code{printf} is skipped. Since the increment @code{x++}
-is not skipped, @code{x} does not remain stuck at 5.
+is not skipped, @code{x} does not remain stuck at 5. Contrast the
+@code{for} loop above with the @code{while} loop:
+
+@example
+awk 'BEGIN @{
+ x = 0
+ while (x <= 20) @{
+ if (x == 5)
+ continue
+ printf ("%d ", x)
+ x++
+ @}
+ print ""
+@}'
+@end example
-@node Next, Exit, Continue, Statements
+@noindent
+This program loops forever once @code{x} gets to 5.
+
+@node Next Statement, Exit Statement, Continue Statement, Statements
@section The @code{next} Statement
@cindex @code{next} statement
@@ -4669,29 +5124,32 @@ immediately, but it does not alter the flow of control in any way. So
the rest of the current action executes with a new input record.
At the grossest level, @code{awk} program execution is a loop that reads
-an input record and then tests each rule pattern against it. If you
+an input record and then tests each rule's pattern against it. If you
think of this loop as a @code{for} statement whose body contains the
rules, then the @code{next} statement is analogous to a @code{continue}
-statement: it skips to the end of the body of the loop, and executes the
-increment (which reads another record).
+statement: it skips to the end of the body of this implicit loop, and
+executes the increment (which reads another record).
For example, if your @code{awk} program works only on records with four
-fields, and you don't want it to fail when given bad input, you might use
-the following rule near the beginning of the program:
+fields, and you don't want it to fail when given bad input, you might
+use this rule near the beginning of the program:
@example
NF != 4 @{
- printf ("line %d skipped: doesn't have 4 fields", FNR) > "/dev/tty"
+ printf("line %d skipped: doesn't have 4 fields", FNR) > "/dev/stderr"
next
@}
@end example
@noindent
-so that the following rules will not see the bad record. The error message
-is redirected to @file{/dev/tty} (the terminal), so that it won't get lost
-amid the rest of the program's regular output.
+so that the following rules will not see the bad record. The error
+message is redirected to the standard error output stream, as error
+messages should be. @xref{Special Files}.
+
+The @code{next} statement is not allowed in a @code{BEGIN} or @code{END}
+rule.
-@node Exit, , Next, Statements
+@node Exit Statement, , Next Statement, Statements
@section The @code{exit} Statement
@cindex @code{exit} statement
@@ -4699,10 +5157,10 @@ The @code{exit} statement causes @code{awk} to immediately stop
executing the current rule and to stop processing input; any remaining input
is ignored.@refill
-If an @code{exit} statement is executed from a @code{BEGIN} rule
-the program stops processing everything immediately.
-No input records will be read. However, if an @code{END} rule is
-present, it will be executed (@pxref{BEGIN/END}).@refill
+If an @code{exit} statement is executed from a @code{BEGIN} rule the
+program stops processing everything immediately. No input records are
+read. However, if an @code{END} rule is present, it is executed
+(@pxref{BEGIN/END}).
If @code{exit} is used as part of an @code{END} rule, it causes
the program to stop immediately.
@@ -4727,25 +5185,23 @@ example of this:@refill
@example
BEGIN @{
if (("date" | getline date_now) < 0) @{
- print "Can't get system date"
+ print "Can't get system date" > "/dev/stderr"
exit 4
@}
@}
@end example
@node Arrays, Built-in, Statements, Top
-@chapter Actions: Using Arrays in @code{awk}
+@chapter Arrays in @code{awk}
An @dfn{array} is a table of various values, called @dfn{elements}. The
-elements of an array are distinguished by their @dfn{indices}. Names
-of arrays in @code{awk} are strings of alphanumeric characters and
-underscores, just like regular variables.
-
-You cannot use the same identifier as both a variable and as an array
-name in one @code{awk} program.
+elements of an array are distinguished by their @dfn{indices}. Indices
+may be either numbers or strings. Each array has a name, which looks
+like a variable name, but must not be in use as a variable name in the
+same @code{awk} program.
@menu
-* Intro: Array Intro. Basic facts abou arrays in @code{awk}.
+* Intro: Array Intro. Basic facts about arrays in @code{awk}.
* Reference to Elements:: How to examine one element of an array.
* Assigning Elements:: How to change an element of an array.
* Example: Array Example. Sample program explained.
@@ -4755,23 +5211,25 @@ name in one @code{awk} program.
* Delete:: The @code{delete} statement removes an element from an array.
-* Multi-dimensional:: Emulating multi--dimensional arrays in @code{awk}.
-* Multi-scanning:: Scanning multi--dimensional arrays.
+* Multi-dimensional:: Emulating multi-dimensional arrays in @code{awk}.
+* Multi-scanning:: Scanning multi-dimensional arrays.
@end menu
-@node Array Intro, Reference to Elements, , Arrays
+@node Array Intro, Reference to Elements, Arrays, Arrays
@section Introduction to Arrays
-@cindex Arrays
-The @code{awk} language has one--dimensional @dfn{arrays} for storing groups
-of related strings or numbers. Each array must have a name; valid array
-names are the same as valid variable names, and they do conflict with
-variable names: you can't have both an array and a variable with the same
-name at any point in an @code{awk} program.
+@cindex arrays
+The @code{awk} language has one-dimensional @dfn{arrays} for storing groups
+of related strings or numbers.
+
+Every @code{awk} array must have a name. Array names have the same
+syntax as variable names; any valid variable name would also be a valid
+array name. But you cannot use one name in both ways (as an array and
+as a variable) in one @code{awk} program.
Arrays in @code{awk} superficially resemble arrays in other programming
languages; but there are fundamental differences. In @code{awk}, you
-don't need to declare the size of an array before you start to use it.
+don't need to specify the size of an array before you start to use it.
What's more, in @code{awk} any number or even a string may be used as an
array index.
@@ -4784,12 +5242,9 @@ actually stored at the beginning of the block of memory. Index 1
specifies the second element, which is stored in memory right after the
first element, and so on. It is impossible to add more elements to the
array, because it has room for only as many elements as you declared.
-(Some languages have arrays whose first index is 1, others require that
-you specify both the first and last index when you declare the array.
-In such a language, an array could be indexed, for example, from -3 to
-17.) A contiguous array of four elements might look like this,
-conceptually, if the element values are 8, @code{"foo"}, @code{""} and
-30:@refill
+
+A contiguous array of four elements might look like this, conceptually,
+if the element values are 8, @code{"foo"}, @code{""} and 30:@refill
@example
+---------+---------+--------+---------+
@@ -4803,8 +5258,8 @@ Only the values are stored; the indices are implicit from the order of
the values. 8 is the value at index 0, because 8 appears in the
position with 0 elements before it.
-@cindex Arrays, definition of
-@cindex Associative arrays
+@cindex arrays, definition of
+@cindex associative arrays
Arrays in @code{awk} are different: they are @dfn{associative}. This means
that each array is a collection of pairs: an index, and its corresponding
array element value:
@@ -4833,9 +5288,8 @@ whose value is @w{@code{"number ten"}}. The result is this:
@end example
@noindent
-Now the array is @dfn{sparse} (i.e. some indices are missing): it has
-elements number 4 and 10, but doesn't have an element 5, 6, 7, 8, or
-9.@refill
+Now the array is @dfn{sparse} (i.e., some indices are missing): it has
+elements 4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.@refill
Another consequence of associative arrays is that the indices don't
have to be positive integers. Any number, or even a string, can be
@@ -4850,19 +5304,19 @@ English into French:
@end example
@noindent
-Here we decided to translate the number 1 in both spelled--out and
-numeral form---thus illustrating that a single array can have both
+Here we decided to translate the number 1 in both spelled-out and
+numeric form---thus illustrating that a single array can have both
numbers and strings as indices.
-When @code{awk} creates an array for you, e.g. with the @code{split}
-built--in function (@pxref{String Functions}), that array's indices
-start at the number one.
+When @code{awk} creates an array for you, e.g., with the @code{split}
+built-in function (@pxref{String Functions}), that array's indices
+are consecutive integers starting at 1.
@node Reference to Elements, Assigning Elements, Array Intro, Arrays
@section Referring to an Array Element
-@cindex Array reference
-@cindex Element of array
-@cindex Reference to array
+@cindex array reference
+@cindex element of array
+@cindex reference to array
The principal way of using an array is to refer to one of its elements.
An array reference is an expression which looks like this:
@@ -4873,11 +5327,11 @@ An array reference is an expression which looks like this:
@noindent
Here @var{array} is the name of an array. The expression @var{index} is
-the index of the element of the array that you want. The value of the
-array reference is the current value of that array element.
+the index of the element of the array that you want.
-For example, @samp{foo[4.3]} is an expression for the element of array
-@code{foo} at index 4.3.
+The value of the array reference is the current value of that array
+element. For example, @code{foo[4.3]} is an expression for the element
+of array @code{foo} at index 4.3.
If you refer to an array element that has no recorded value, the value
of the reference is @code{""}, the null string. This includes elements
@@ -4886,7 +5340,7 @@ deleted (@pxref{Delete}). Such a reference automatically creates that
array element, with the null string as its value. (In some cases,
this is unfortunate, because it might waste memory inside @code{awk}).
-@cindex Arrays, determining presence of elements
+@cindex arrays, determining presence of elements
You can find out if an element exists in an array at a certain index with
the expression:
@@ -4897,12 +5351,11 @@ the expression:
@noindent
This expression tests whether or not the particular index exists,
without the side effect of creating that element if it is not present.
-The expression has the value 1 (true) if
-@code{@var{array}[@var{subscript}]} exists, and 0 (false) if it does not
-exist.@refill
+The expression has the value 1 (true) if @code{@var{array}[@var{index}]}
+exists, and 0 (false) if it does not exist.@refill
-For example, to find out whether the array @code{frequencies} contains the
-subscript @code{"2"}, you would ask:@refill
+For example, to test whether the array @code{frequencies} contains the
+index @code{"2"}, you could write this statement:@refill
@example
if ("2" in frequencies) print "Subscript \"2\" is present."
@@ -4910,9 +5363,9 @@ if ("2" in frequencies) print "Subscript \"2\" is present."
Note that this is @emph{not} a test of whether or not the array
@code{frequencies} contains an element whose @emph{value} is @code{"2"}.
-(There is no way to that except to scan all the elements.) Also, this
+(There is no way to do that except to scan all the elements.) Also, this
@emph{does not} create @code{frequencies["2"]}, while the following
-(incorrect) alternative would:@refill
+(incorrect) alternative would do so:@refill
@example
if (frequencies["2"] != "") print "Subscript \"2\" is present."
@@ -4920,8 +5373,8 @@ if (frequencies["2"] != "") print "Subscript \"2\" is present."
@node Assigning Elements, Array Example, Reference to Elements, Arrays
@section Assigning Array Elements
-@cindex Array assignment
-@cindex Element assignment
+@cindex array assignment
+@cindex element assignment
Array elements are lvalues: they can be assigned values just like
@code{awk} variables:
@@ -4944,14 +5397,10 @@ number, and prints them out in order of line number. The line numbers are
not in order, however, when they are first read: they are scrambled. This
program sorts the lines by making an array using the line numbers as
subscripts. It then prints out the lines in sorted order of their numbers.
-It is a very simple program, and will get confused if it encounters repeated
+It is a very simple program, and gets confused if it encounters repeated
numbers, gaps, or lines that don't begin with a number.@refill
@example
-BEGIN @{
- max=0
-@}
-
@{
if ($1 > max)
max = $1
@@ -4964,16 +5413,18 @@ END @{
@}
@end example
+@ignore
The first rule just initializes the variable @code{max}. (This is not
strictly necessary, since an uninitialized variable has the null string
as its value, and the null string is effectively zero when used in
a context where a number is required.)
+@end ignore
-The second rule keeps track of the largest line number seen so far;
+The first rule keeps track of the largest line number seen so far;
it also stores each line into the array @code{arr}, at an index that
is the line's number.
-The third rule runs after all the input has been read, to print out
+The second rule runs after all the input has been read, to print out
all the lines.
When this program is run with the following input:
@@ -4997,13 +5448,27 @@ its output is this:
5 I am the Five man
@end example
+If a line number is repeated, the last line with a given number overrides
+the others.
+
+Gaps in the line numbers can be handled with an easy improvement to the
+program's @code{END} rule:
+
+@example
+END @{
+ for (x = 1; x <= max; x++)
+ if (x in arr)
+ print arr[x]
+@}
+@end example
+
@node Scanning an Array, Delete, Array Example, Arrays
@section Scanning All Elements of an Array
@cindex @code{for (x in @dots{})}
-@cindex Arrays, special @code{for} statement
-@cindex Scanning an array
+@cindex arrays, special @code{for} statement
+@cindex scanning an array
-In programs that use arrays, often you need a loop that will execute
+In programs that use arrays, often you need a loop that executes
once for each element of an array. In other languages, where arrays are
contiguous and indices are limited to positive integers, this is
easy: the largest index is one less than the length of the array, and you can
@@ -5028,7 +5493,7 @@ least once) in the input, by storing a 1 into the array @code{used} with
the word as index. The second rule scans the elements of @code{used} to
find all the distinct words that appear in the input. It prints each
word that is more than 10 characters long, and also prints the number of
-such words. @xref{Built-in}, for more information on the built--in
+such words. @xref{Built-in}, for more information on the built-in
function @code{length}.
@example
@@ -5064,9 +5529,9 @@ strange results. It is best to avoid such things.@refill
@node Delete, Multi-dimensional, Scanning an Array, Arrays
@section The @code{delete} Statement
@cindex @code{delete} statement
-@cindex Deleting elements of arrays
-@cindex Removing elements of arrays
-@cindex Arrays, deleting an element
+@cindex deleting elements of arrays
+@cindex removing elements of arrays
+@cindex arrays, deleting an element
You can remove an individual element of an array using the @code{delete}
statement:
@@ -5082,15 +5547,14 @@ can no longer be obtained.
Here is an example of deleting elements in an array:
@example
-awk '@{ for (i in frequencies)
- delete frequencies[i]
-@}'
+for (i in frequencies)
+ delete frequencies[i]
@end example
@noindent
This example removes all the elements from the array @code{frequencies}.
-If you delete an element, the @code{for} statement to scan the array
+If you delete an element, a subsequent @code{for} statement to scan the array
will not report that element, and the @code{in} operator to check for
the presence of that element will return 0:
@@ -5101,53 +5565,55 @@ if (4 in foo)
@end example
@node Multi-dimensional, Multi-scanning, Delete, Arrays
-@section Multi--dimensional arrays
+@section Multi-dimensional Arrays
-@cindex Subscripts, multi-dimensional in arrays
-@cindex Arrays, multi-dimensional subscripts
-A multi--dimensional array is an array in which an element is identified
+@cindex subscripts, multi-dimensional in arrays
+@cindex arrays, multi-dimensional subscripts
+@cindex multi-dimensional subscripts
+A multi-dimensional array is an array in which an element is identified
by a sequence of indices, not a single index. For example, a
-two--dimensional array requires two indices. The usual way (in most
+two-dimensional array requires two indices. The usual way (in most
languages, including @code{awk}) to refer to an element of a
-two--dimensional array named @code{grid} is with @code{grid[x,y]}.
+two-dimensional array named @code{grid} is with
+@code{grid[@var{x},@var{y}]}.
@vindex SUBSEP
-Multi--dimensional arrays are supported in @code{awk} through
+Multi-dimensional arrays are supported in @code{awk} through
concatenation of indices into one string. What happens is that
@code{awk} converts the indices into strings (@pxref{Conversion}) and
concatenates them together, with a separator between them. This creates
a single string that describes the values of the separate indices. The
combined string is used as a single index into an ordinary,
-one--dimensional array. The separator used is the value of the special
+one-dimensional array. The separator used is the value of the built-in
variable @code{SUBSEP}.
-For example, suppose the value of @code{SUBSEP} is @code{","} and the
-expression @samp{foo[5,12]="value"} is executed. The numbers 5 and 12
-will be concatenated with a comma between them, yielding @code{"5,12"};
-thus, the array element @code{foo["5,12"]} will be set to
-@code{"value"}.
+For example, suppose we evaluate the expression @code{foo[5,12]="value"}
+when the value of @code{SUBSEP} is @code{"@@"}. The numbers 5 and 12 are
+concatenated with a comma between them, yielding @code{"5@@12"}; thus,
+the array element @code{foo["5@@12"]} is set to @code{"value"}.
Once the element's value is stored, @code{awk} has no record of whether
it was stored with a single index or a sequence of indices. The two
expressions @code{foo[5,12]} and @w{@code{foo[5 SUBSEP 12]}} always have
the same value.
-The default value of @code{SUBSEP} is not a comma; it is the string
-@code{"\034"}, which contains a nonprinting character that is unlikely
-to appear in an @code{awk} program or in the input data.
+The default value of @code{SUBSEP} is actually the string @code{"\034"},
+which contains a nonprinting character that is unlikely to appear in an
+@code{awk} program or in the input data.
The usefulness of choosing an unlikely character comes from the fact
that index values that contain a string matching @code{SUBSEP} lead to
-combined strings that are ambiguous. Suppose that @code{SUBSEP} is a
-comma; then @w{@code{foo["a,b", "c"]}} and @w{@code{foo["a", "b,c"]}} will be
-indistinguishable because both are actually stored as
-@code{foo["a,b,c"]}. Because @code{SUBSEP} is @code{"\034"}, such
-confusion can actually happen only when an index contains the character
-@code{"\034"}, which is a rare event.
-
-You can test whether a particular index--sequence exists in a
-``multi--dimensional'' array with the same operator @code{in} used for single
-dimensional arrays. Instead of a single index as the left--hand operand,
+combined strings that are ambiguous. Suppose that @code{SUBSEP} were
+@code{"@@"}; then @w{@code{foo["a@@b", "c"]}} and @w{@code{foo["a",
+"b@@c"]}} would be indistinguishable because both would actually be
+stored as @code{foo["a@@b@@c"]}. Because @code{SUBSEP} is
+@code{"\034"}, such confusion can actually happen only when an index
+contains the character with ASCII code 034, which is a rare
+event.@refill
+
+You can test whether a particular index-sequence exists in a
+``multi-dimensional'' array with the same operator @code{in} used for single
+dimensional arrays. Instead of a single index as the left-hand operand,
write the whole sequence of indices, separated by commas, in
parentheses:@refill
@@ -5155,17 +5621,13 @@ parentheses:@refill
(@var{subscript1}, @var{subscript2}, @dots{}) in @var{array}
@end example
-The following example treats its input as a two--dimensional array of
+The following example treats its input as a two-dimensional array of
fields; it rotates this array 90 degrees clockwise and prints the
result. It assumes that all lines have the same number of
elements.
@example
-awk 'BEGIN @{
- max_nf = max_nr = 0
-@}
-
-@{
+awk '@{
if (max_nf < NF)
max_nf = NF
max_nr = NR
@@ -5204,23 +5666,23 @@ it produces:
3 2 1 6
@end example
-@node Multi-scanning, , Multi-dimensional, Arrays
-@section Scanning Multi--dimensional Arrays
+@node Multi-scanning, , Multi-dimensional, Arrays
+@section Scanning Multi-dimensional Arrays
There is no special @code{for} statement for scanning a
-``multi--dimensional'' array; there cannot be one, because in truth there
-are no multi--dimensional arrays or elements; there is only a
-multi--dimensional @emph{way of accessing} an array.
+``multi-dimensional'' array; there cannot be one, because in truth there
+are no multi-dimensional arrays or elements; there is only a
+multi-dimensional @emph{way of accessing} an array.
However, if your program has an array that is always accessed as
-multi--dimensional, you can get the effect of scanning it by combining
+multi-dimensional, you can get the effect of scanning it by combining
the scanning @code{for} statement (@pxref{Scanning an Array}) with the
-@code{split} built--in function (@pxref{String Functions}). It works
+@code{split} built-in function (@pxref{String Functions}). It works
like this:
@example
for (combined in @var{array}) @{
- split (combined, separate, SUBSEP)
+ split(combined, separate, SUBSEP)
@dots{}
@}
@end example
@@ -5228,7 +5690,7 @@ for (combined in @var{array}) @{
@noindent
This finds each concatenated, combined index in the array, and splits it
into the individual indices by breaking it apart where the value of
-@code{SUBSEP} appears. The split--out indices become the elements of
+@code{SUBSEP} appears. The split-out indices become the elements of
the array @code{separate}.
Thus, suppose you have previously stored in @code{@var{array}[1,
@@ -5236,11 +5698,11 @@ Thus, suppose you have previously stored in @code{@var{array}[1,
@var{array}. (Recall that the default value of @code{SUBSEP} contains
the character with code 034.) Sooner or later the @code{for} statement
will find that index and do an iteration with @code{combined} set to
-@code{"1\034foo"}. Then the @code{split} function will be called as
+@code{"1\034foo"}. Then the @code{split} function is called as
follows:
@example
-split ("1\034foo", separate, "\034")
+split("1\034foo", separate, "\034")
@end example
@noindent
@@ -5249,38 +5711,18 @@ to @code{"foo"}. Presto, the original sequence of separate indices has
been recovered.
@node Built-in, User-defined, Arrays, Top
-@chapter Built--in functions
+@chapter Built-in Functions
-@cindex Built-in functions, list of
-@dfn{Built--in} functions are functions always available for your
-@code{awk} program to call. This chapter defines all the built--in
-functions that exist; some of them are mentioned in other sections, but
-they are summarized here for your convenience. (You can also define
+@cindex built-in functions
+@dfn{Built-in} functions are functions that are always available for
+your @code{awk} program to call. This chapter defines all the built-in
+functions in @code{awk}; some of them are mentioned in other sections,
+but they are summarized here for your convenience. (You can also define
new functions yourself. @xref{User-defined}.)
-In most cases, any extra arguments given to built--in functions are ignored.
-The defaults for omitted arguments vary from function to function and are
-described under the individual functions.
-
-The name of a built--in function need not be followed immediately by
-the opening left parenthesis of the arguments; whitespace is allowed.
-However, it is wise to write no space there, since user--defined
-functions do not allow space.
-
-When a function is called, expressions that create the function's actual
-parameters are evaluated completely before the function call is performed.
-For example, in the code fragment:
-
-@example
-i = 4
-j = myfunc(i++)
-@end example
-
-@noindent
-the variable @code{i} will be set to 5 before @code{myfunc} is called
-with a value of 4 for its actual parameter.
-
@menu
+* Calling Built-in:: How to call built-in functions.
+
* Numeric Functions:: Functions that work with numbers,
including @code{int}, @code{sin} and @code{rand}.
@@ -5290,25 +5732,41 @@ with a value of 4 for its actual parameter.
* I/O Functions:: Functions for files and shell commands
@end menu
-@node Numeric Functions, String Functions, , Built-in
-@section Numeric Built--in Functions
+@node Calling Built-in, Numeric Functions, Built-in, Built-in
+@section Calling Built-in Functions
+
+To call a built-in function, write the name of the function followed
+by arguments in parentheses. For example, @code{atan2(y + z, 1)}
+is a call to the function @code{atan2}, with two arguments.
+
+Whitespace is ignored between the built-in function name and the
+open-parenthesis, but we recommend that you avoid using whitespace
+there. User-defined functions do not permit whitespace in this way, and
+you will find it easier to avoid mistakes by following a simple
+convention which always works: no whitespace after a function name.
-The general syntax of the numeric built--in functions is the same for
-each. Here is an example of that syntax:@refill
+Each built-in function accepts a certain number of arguments. In most
+cases, any extra arguments given to built-in functions are ignored. The
+defaults for omitted arguments vary from function to function and are
+described under the individual functions.
+
+When a function is called, expressions that create the function's actual
+parameters are evaluated completely before the function call is performed.
+For example, in the code fragment:
@example
-awk '# Read input records containing a pair of points: x0, y0, x1, y1.
- # Print the points and the distance between them.
- @{ printf "%f %f %f %f %f\n", $1, $2, $3, $4,
- sqrt(($2-$1) * ($2-$1) + ($4-$3) * ($4-$3)) @}'
+i = 4
+j = sqrt(i++)
@end example
@noindent
-This calculates the square root of a calculation that uses the values
-of the fields. It then prints the first four fields of the input
-record and the result of the square root calculation.
+the variable @code{i} is set to 5 before @code{sqrt} is called
+with a value of 4 for its actual parameter.
+
+@node Numeric Functions, String Functions, Calling Built-in, Built-in
+@section Numeric Built-in Functions
-Here is the full list of numeric built--in functions:
+Here is a full list of built-in functions that work with numbers:
@table @code
@item int(@var{x})
@@ -5316,16 +5774,16 @@ This gives you the integer part of @var{x}, truncated toward 0. This
produces the nearest integer to @var{x}, located between @var{x} and 0.
For example, @code{int(3)} is 3, @code{int(3.9)} is 3, @code{int(-3.9)}
-is -3, and @code{int(-3)} is -3 as well.@refill
+is @minus{}3, and @code{int(-3)} is @minus{}3 as well.@refill
@item sqrt(@var{x})
This gives you the positive square root of @var{x}. It reports an error
-if @var{x} is negative.@refill
+if @var{x} is negative. Thus, @code{sqrt(4)} is 2.@refill
@item exp(@var{x})
-This gives you the exponential of @var{x}, or reports an error if @var{x} is
-out of range. The range of values @var{x} can have depends on your
-machine's floating point representation.@refill
+This gives you the exponential of @var{x}, or reports an error if
+@var{x} is out of range. The range of values @var{x} can have depends
+on your machine's floating point representation.@refill
@item log(@var{x})
This gives you the natural logarithm of @var{x}, if @var{x} is positive;
@@ -5338,14 +5796,15 @@ This gives you the sine of @var{x}, with @var{x} in radians.
This gives you the cosine of @var{x}, with @var{x} in radians.
@item atan2(@var{y}, @var{x})
-This gives you the arctangent of @var{y/x}, with both in radians.
+This gives you the arctangent of @code{@var{y} / @var{x}}, with the
+quotient understood in radians.
@item rand()
-This gives you a random number. The values of @w{@code{rand()}} are
-uniformly--distributed between 0 and 1. The value is never 0 and never
+This gives you a random number. The values of @code{rand} are
+uniformly-distributed between 0 and 1. The value is never 0 and never
1.
-Often you want random integers instead. Here is a user--defined function
+Often you want random integers instead. Here is a user-defined function
you can use to obtain a random nonnegative integer less than @var{n}:
@example
@@ -5355,9 +5814,9 @@ function randint(n) @{
@end example
@noindent
-The multiplication produces a random real number at least 0, and less
+The multiplication produces a random real number greater than 0 and less
than @var{n}. We then make it an integer (using @code{int}) between 0
-and @code{@var{n}@minus{}1}.
+and @code{@var{n} @minus{} 1}.
Here is an example where a similar function is used to produce
random integers between 1 and @var{n}:
@@ -5367,15 +5826,15 @@ awk '
# Function to roll a simulated die.
function roll(n) @{ return 1 + int(rand() * n) @}
-# Roll 3 six--sided dice and print total number of points.
+# Roll 3 six-sided dice and print total number of points.
@{
printf("%d points\n", roll(6)+roll(6)+roll(6))
@}'
@end example
-@emph{Note} that @w{@code{rand()}} starts generating numbers from the same
+@strong{Note:} @code{rand} starts generating numbers from the same
point, or @dfn{seed}, each time you run @code{awk}. This means that
-the same program will produce the same results each time you run it.
+a program will produce the same results each time you run it.
The numbers are random within one @code{awk} run, but predictable
from run to run. This is convenient for debugging, but if you want
a program to do different things each time it is used, you must change
@@ -5383,7 +5842,7 @@ the seed to a value that will be different in each run. To do this,
use @code{srand}.
@item srand(@var{x})
-The function @code{srand(@var{x})} sets the starting point, or @dfn{seed},
+The function @code{srand} sets the starting point, or @dfn{seed},
for generating random numbers to the value @var{x}.
Each seed value leads to a particular sequence of ``random'' numbers.
@@ -5394,13 +5853,16 @@ If you omit the argument @var{x}, as in @code{srand()}, then the current
date and time of day are used for a seed. This is the way to get random
numbers that are truly unpredictable.
-The return value of @code{srand()} is the previous seed. This makes it
+The return value of @code{srand} is the previous seed. This makes it
easy to keep track of the seeds for use in consistently reproducing
sequences of random numbers.
@end table
@node String Functions, I/O Functions, Numeric Functions, Built-in
-@section Built--in Functions for String Manipulation
+@section Built-in Functions for String Manipulation
+
+ The functions in this section look at the text of one or more
+strings.
@table @code
@item index(@var{in}, @var{find})
@@ -5420,11 +5882,13 @@ prints @samp{3}. If @var{find} is not found, @code{index} returns 0.
@findex length
This gives you the number of characters in @var{string}. If
@var{string} is a number, the length of the digit string representing
-that number is returned. For example, @code{length("abcde")} is 5.
-Whereas, @code{length(15 * 35)} works out to 3. How? Well, 15 * 35 =
+that number is returned. For example, @code{length("abcde")} is 5. By
+contrast, @code{length(15 * 35)} works out to 3. How? Well, 15 * 35 =
525, and 525 is then converted to the string @samp{"525"}, which has
three characters.
+If no argument is supplied, @code{length} returns the length of @code{$0}.
+
@item match(@var{string}, @var{regexp})
@findex match
The @code{match} function searches the string, @var{string}, for the
@@ -5435,10 +5899,10 @@ where that substring begins (1, if it starts at the beginning of
@vindex RSTART
@vindex RLENGTH
-The @code{match} function sets the special variable @code{RSTART} to
-the index. It also sets the special variable @code{RLENGTH} to the
+The @code{match} function sets the built-in variable @code{RSTART} to
+the index. It also sets the built-in variable @code{RLENGTH} to the
length of the matched substring. If no match is found, @code{RSTART}
-is set to 0, and @code{RLENGTH} to -1.
+is set to 0, and @code{RLENGTH} to @minus{}1.
For example:
@@ -5467,7 +5931,7 @@ But none of it would doobar
FIND Melvin
JF+KM
This line is property of The Reality Engineering Co.
-This file was created by Melvin.
+This file created by Melvin.
@end example
@noindent
@@ -5475,19 +5939,18 @@ This file was created by Melvin.
@example
Match of fo*bar found at 18 in My program was a foobar
-Match of Melvin found at 26 in This file was created by Melvin.
+Match of Melvin found at 26 in This file created by Melvin.
@end example
-@item split(@var{string}, @var{array}, @var{field_separator})
+@item split(@var{string}, @var{array}, @var{fieldsep})
@findex split
-This divides @var{string} up into pieces separated by
-@var{field_separator}, and stores the pieces in @var{array}. The
-first piece is stored in @code{@var{array}[1]}, the second piece in
-@code{@var{array}[2]}, and so forth. The string value of the third
-argument, @var{field_separator}, is used as a regexp to search for to
-find the places to split @var{string}. If the @var{field_separator}
-is omitted, the value of @code{FS} is used. @code{split} returns the
-number of elements created.@refill
+This divides @var{string} up into pieces separated by @var{fieldsep},
+and stores the pieces in @var{array}. The first piece is stored in
+@code{@var{array}[1]}, the second piece in @code{@var{array}[2]}, and so
+forth. The string value of the third argument, @var{fieldsep}, is used
+as a regexp to search for to find the places to split @var{string}. If
+the @var{fieldsep} is omitted, the value of @code{FS} is used.
+@code{split} returns the number of elements created.@refill
The @code{split} function, then, splits strings into pieces in a
manner similar to the way input lines are split into fields. For example:
@@ -5522,16 +5985,16 @@ sprintf("pi = %.2f (approx.)", 22/7)
@noindent
returns the string @w{@code{"pi = 3.14 (approx.)"}}.
-@item sub(@var{regexp}, @var{replacement_string}, @var{target_variable})
+@item sub(@var{regexp}, @var{replacement}, @var{target})
@findex sub
-The @code{sub} function alters the value of @var{target_variable}.
+The @code{sub} function alters the value of @var{target}.
It searches this value, which should be a string, for the
leftmost substring matched by the regular expression, @var{regexp},
extending this match as far as possible. Then the entire string is
-changed by replacing the matched text with @var{replacement_string}.
-The modified string becomes the new value of @var{target_variable}.
+changed by replacing the matched text with @var{replacement}.
+The modified string becomes the new value of @var{target}.
-This function is peculiar because @var{target_variable} is not simply
+This function is peculiar because @var{target} is not simply
used to compute a value, and not just any expression will do: it
must be a variable, field or array reference, so that @code{sub} can
store a modified value there. If this argument is omitted, then the
@@ -5551,42 +6014,51 @@ leftmost, longest occurrence of @samp{at} with @samp{ith}.
The @code{sub} function returns the number of substitutions made (either
one or zero).
-The special character, @samp{&}, in the replacement string,
-@var{replacement_string}, stands for the precise substring that was
-matched by @var{regexp}. (If the regexp can match more than one string,
-then this precise substring may vary.) For example:@refill
+If the special character @samp{&} appears in @var{replacement}, it
+stands for the precise substring that was matched by @var{regexp}. (If
+the regexp can match more than one string, then this precise substring
+may vary.) For example:@refill
@example
awk '@{ sub(/candidate/, "& and his wife"); print @}'
@end example
@noindent
-will change the first occurrence of ``candidate'' to ``candidate and
-his wife'' on each input line.
+changes the first occurrence of @samp{candidate} to @samp{candidate
+and his wife} on each input line.
-@noindent
-The effect of this special character can be turned off by preceding
-it with a backslash (@samp{\&}). To include a backslash in the
-replacement string, it too must be preceded with a (second) backslash.
+The effect of this special character can be turned off by putting a
+backslash before it in the string. As usual, to insert one backslash in
+the string, you must write two backslashes. Therefore, write @samp{\\&}
+in a string constant to include a literal @samp{&} in the replacement.
+For example, here is how to replace the first @samp{|} on each line with
+an @samp{&}:@refill
-Note: if you use @code{sub} with a third argument that is not a variable,
-field or array element reference, then it will still search for the pattern
-and return 0 or 1, but the modified string is thrown away because there
-is no place to put it. For example:
+@example
+awk '@{ sub(/\|/, "\\&"); print @}'
+@end example
+
+@strong{Note:} as mentioned above, the third argument to @code{sub} must
+be an lvalue. Some versions of @code{awk} allow the third argument to
+be an expression which is not an lvalue. In such a case, @code{sub}
+would still search for the pattern and return 0 or 1, but the result of
+the substitution (if any) would be thrown away because there is no place
+to put it. Such versions of @code{awk} accept expressions like
+this:@refill
@example
sub(/USA/, "United States", "the USA and Canada")
@end example
-will indeed produce a string @w{@code{"the United States and Canada"}},
-but there will be no way to use that string!
+@noindent
+But that is considered erroneous in @code{gawk}.
-@item gsub(@var{regexp}, @var{replacement_string}, @var{target_variable})
+@item gsub(@var{regexp}, @var{replacement}, @var{target})
@findex gsub
This is similar to the @code{sub} function, except @code{gsub} replaces
-@emph{all} of the longest, leftmost, @emph{non--overlapping} matching
-substrings it can find. The ``g'' in @code{gsub} stands for @dfn{global},
-which means replace @emph{everywhere}. For example:@refill
+@emph{all} of the longest, leftmost, @emph{nonoverlapping} matching
+substrings it can find. The @samp{g} in @code{gsub} stands for
+``global'', which means replace everywhere. For example:@refill
@example
awk '@{ gsub(/Britain/, "United Kingdom"); print @}'
@@ -5597,44 +6069,57 @@ replaces all occurrences of the string @samp{Britain} with @samp{United
Kingdom} for all input records.@refill
The @code{gsub} function returns the number of substitutions made. If
-the variable to be searched and altered, @var{target_variable}, is
+the variable to be searched and altered, @var{target}, is
omitted, then the entire input record, @code{$0}, is used.@refill
-The characters @samp{&} and @samp{\} are special in @code{gsub}
-as they are in @code{sub} (see immediately above).
+As in @code{sub}, the characters @samp{&} and @samp{\} are special, and
+the third argument must be an lvalue.
@item substr(@var{string}, @var{start}, @var{length})
@findex substr
-This returns a @var{length}--character--long substring of @var{string},
+This returns a @var{length}-character-long substring of @var{string},
starting at character number @var{start}. The first character of a
string is character number one. For example,
-@code{substr("washington", 5, 3)} returns @samp{"ing"}.@refill
+@code{substr("washington", 5, 3)} returns @code{"ing"}.@refill
If @var{length} is not present, this function returns the whole suffix of
@var{string} that begins at character number @var{start}. For example,
-@code{substr("washington", 5)} returns @samp{"ington"}.
+@code{substr("washington", 5)} returns @code{"ington"}.
+
+@item tolower(@var{string})
+@findex tolower
+This returns a copy of @var{string}, with each upper-case character
+in the string replaced with its corresponding lower-case character.
+Nonalphabetic characters are left unchanged. For example,
+@code{tolower("MiXeD cAsE 123")} returns @code{"mixed case 123"}.
+
+@item toupper(@var{string})
+@findex toupper
+This returns a copy of @var{string}, with each lower-case character
+in the string replaced with its corresponding upper-case character.
+Nonalphabetic characters are left unchanged. For example,
+@code{toupper("MiXeD cAsE 123")} returns @code{"MIXED CASE 123"}.
@end table
-@node I/O Functions, , String Functions, Built-in
-@section Built--in Functions for I/O to Files and Commands
+@node I/O Functions, , String Functions, Built-in
+@section Built-in Functions For Input/Output
@table @code
@item close(@var{filename})
-Close the file @var{filename}. The argument may alternatively be
-a shell command that was used for redirecting to or from a pipe; then the
-pipe is closed.
+Close the file @var{filename}, for input or output. The argument may
+alternatively be a shell command that was used for redirecting to or
+from a pipe; then the pipe is closed.
@xref{Close Input}, regarding closing input files and pipes.
@xref{Close Output}, regarding closing output files and pipes.
@item system(@var{command})
@findex system
-@cindex Interaction of @code{awk} with other programs
-The system function allows the user to execute operating system commands and
-then return to the @code{awk} program. The @code{system} function executes
-the command given by the string value of @var{command}. It returns, as its
-value, the status returned by the command that was executed. This is known
-as returning the @dfn{exit status}.
+@cindex interaction of @code{awk} with other programs
+The system function allows the user to execute operating system commands
+and then return to the @code{awk} program. The @code{system} function
+executes the command given by the string @var{command}. It returns, as
+its value, the status returned by the command that was executed.
For example, if the following fragment of code is put in your @code{awk}
program:
@@ -5647,23 +6132,25 @@ END @{
@noindent
the system operator will be sent mail when the @code{awk} program
-finishes processing input and begins its end--of--input processing.
+finishes processing input and begins its end-of-input processing.
Note that much the same result can be obtained by redirecting
-@code{print} or @code{printf} into a pipe.
-However, if your @code{awk} program is interactive, this function is
-useful for cranking up large self--contained programs, such as a shell
-or an editor.@refill
+@code{print} or @code{printf} into a pipe. However, if your @code{awk}
+program is interactive, @code{system} is useful for cranking up large
+self-contained programs, such as a shell or an editor.@refill
+
+Some operating systems cannot implement the @code{system} function.
+@code{system} causes a fatal error if it is not supported.
@end table
-@node User-defined, Special, Built-in, Top
-@chapter User--defined Functions
+@node User-defined, Built-in Variables, Built-in, Top
+@chapter User-defined Functions
-@cindex User-defined functions
-@cindex Functions, user-defined
+@cindex user-defined functions
+@cindex functions, user-defined
Complicated @code{awk} programs can often be simplified by defining
-your own functions. User--defined functions can be called just like
-built--in ones (@pxref{Function Calls}), but it is up to you to define
+your own functions. User-defined functions can be called just like
+built-in ones (@pxref{Function Calls}), but it is up to you to define
them---to tell @code{awk} what they should do.
@menu
@@ -5673,8 +6160,15 @@ them---to tell @code{awk} what they should do.
* Return Statement:: Specifying the value a function returns.
@end menu
-@node Definition Syntax, Function Example, , User-defined
+@node Definition Syntax, Function Example, User-defined, User-defined
@section Syntax of Function Definitions
+@cindex defining functions
+@cindex function definition
+
+Definitions of functions can appear anywhere between the rules of the
+@code{awk} program. Thus, the general form of an @code{awk} program is
+extended to include sequences of rules @emph{and} user-defined function
+definitions.
The definition of a function named @var{name} looks like this:
@@ -5684,49 +6178,65 @@ function @var{name} (@var{parameter-list}) @{
@}
@end example
-A valid function name is like a valid variable name: a sequence of
-letters, digits and underscores, not starting with a digit.
+@noindent
+The keyword @code{function} may be abbreviated @code{func}.
+
+@var{name} is the name of the function to be defined. A valid function
+name is like a valid variable name: a sequence of letters, digits and
+underscores, not starting with a digit.
+
+@var{parameter-list} is a list of the function's arguments and local
+variable names, separated by commas. When the function is called,
+the argument names are used to hold the argument values given in
+the call. The local variables are initialized to the null string.
-Such function definitions can appear anywhere between the rules
-of the @code{awk} program. The general format of an @code{awk}
-program, then, is now modified to include sequences of rules @emph{and}
-user--defined function definitions.
+The @var{body-of-function} consists of @code{awk} statements. It is the
+most important part of the definition, because it says what the function
+should actually @emph{do}. The argument names exist to give the body a
+way to talk about the arguments; local variables, to give the body
+places to keep temporary values.
-The function definition need not precede all the uses of the function.
-This is because @code{awk} reads the entire program before starting to
-execute any of it.
+Argument names are not distinguished syntactically from local variable
+names; instead, the number of arguments supplied when the function is
+called determines how many argument variables there are. Thus, if three
+argument values are given, the first three names in @var{parameter-list}
+are arguments, and the rest are local variables.
-The @var{parameter-list} is a list of the function's @dfn{local}
-variable names, separated by commas. Within the body of the function,
-local variables refer to arguments with which the function is called.
-If the function is called with fewer arguments than it has local
-variables, this is not an error; the extra local variables are simply
-set as the null string.
+It follows that if the number of arguments is not the same in all calls
+to the function, some of the names in @var{parameter-list} may be
+arguments on some occasions and local variables on others. Another
+way to think of this is that omitted arguments default to the
+null string.
-The local variable values hide or @dfn{shadow} any variables of the same
-names used in the rest of the program. The shadowed variables are not
-accessible in the function definition, because there is no way to name
-them while their names have been taken away for the local variables.
-All other variables used in the @code{awk} program can be referenced
-or set normally in the function definition.
+Usually when you write a function you know how many names you intend to
+use for arguments and how many you intend to use as locals. By
+convention, you should write an extra space between the arguments and
+the locals, so that other people can follow how your function is
+supposed to be used.
-The local variables last only as long as the function is executing.
-Once the function finishes, the shadowed variables come back.
+During execution of the function body, the arguments and local variable
+values hide or @dfn{shadow} any variables of the same names used in the
+rest of the program. The shadowed variables are not accessible in the
+function definition, because there is no way to name them while their
+names have been taken away for the local variables. All other variables
+used in the @code{awk} program can be referenced or set normally in the
+function definition.
-The @var{body-of-function} part of the definition is the most important
-part, because this is what says what the function should actually @emph{do}.
-The local variables exist to give the body a way to talk about the arguments.
+The arguments and local variables last only as long as the function body
+is executing. Once the body finishes, the shadowed variables come back.
-Functions may be @dfn{recursive}, i.e., they can call themselves, either
-directly, or indirectly (via calling a second function that calls the first
-again).
+The function body can contain expressions which call functions. They
+can even call this function, either directly or by way of another
+function. When this happens, we say the function is @dfn{recursive}.
-The keyword @samp{function} may also be written @samp{func}.
+There is no need in @code{awk} to put the definition of a function
+before all uses of the function. This is because @code{awk} reads the
+entire program before starting to execute any of it.
@node Function Example, Function Caveats, Definition Syntax, User-defined
@section Function Definition Example
-Here is an example of a user--defined function, called @code{myprint}, that
+Here is an example of a user-defined function, called @code{myprint}, that
takes a number and prints it in a specific format.
@example
@@ -5737,11 +6247,11 @@ function myprint(num)
@end example
@noindent
-To illustrate, let's use the following @code{awk} rule to use, or
-@dfn{call}, our @code{myprint} function:
+To illustrate, here is an @code{awk} rule which uses our @code{myprint}
+function:
@example
-$3 > 0 @{ myprint($3) @}'
+$3 > 0 @{ myprint($3) @}
@end example
@noindent
@@ -5755,7 +6265,7 @@ contain a positive number in our input. Therefore, when given:
@end example
@noindent
-this program, using our function to format the results, will print:
+this program, using our function to format the results, prints:
@example
5.6
@@ -5778,18 +6288,35 @@ function rev (str, len) @{
@end example
@node Function Caveats, Return Statement, Function Example, User-defined
-@section Caveats of Function Calling
+@section Calling User-defined Functions
+
+@dfn{Calling a function} means causing the function to run and do its job.
+A function call is an expression, and its value is the value returned by
+the function.
-@emph{Note} that there cannot be any blanks between the function name and
-the left parenthesis of the argument list, when calling a function.
-This is so @code{awk} can tell you are not trying to concatenate the value
-of a variable with the value of an expression inside the parentheses.
+A function call consists of the function name followed by the arguments
+in parentheses. What you write in the call for the arguments are
+@code{awk} expressions; each time the call is executed, these
+expressions are evaluated, and the values are the actual arguments. For
+example, here is a call to @code{foo} with three arguments:
+@example
+foo(x y, "lose", 4 * z)
+@end example
+
+@strong{Note:} whitespace characters (spaces and tabs) are not allowed
+between the function name and the open-parenthesis of the argument list.
+If you write whitespace by mistake, @code{awk} might think that you mean
+to concatenate a variable with an expression in parentheses. However, it
+notices that you used a function name and not a variable name, and reports
+an error.
+
+@cindex call by value
When a function is called, it is given a @emph{copy} of the values of
-its arguments. This is called @dfn{passing by value}. The caller may
-use a variable as the expression for the argument, but the called
-function does not know this: all it knows is what value the argument
-had. For example, if you write this code:
+its arguments. This is called @dfn{call by value}. The caller may use
+a variable as the expression for the argument, but the called function
+does not know this: all it knows is what value the argument had. For
+example, if you write this code:
@example
foo = "bar"
@@ -5817,13 +6344,14 @@ function myfunc (win) @{
to change its first argument variable @code{win}, this @emph{does not}
change the value of @code{foo} in the caller. The role of @code{foo} in
calling @code{myfunc} ended when its value, @code{"bar"}, was computed.
-If @code{win} also exists outside of @code{myfunc}, this definition
-will not change it---that value is shadowed during the execution of
-@code{myfunc} and cannot be seen or changed from there.
+If @code{win} also exists outside of @code{myfunc}, the function body
+cannot alter this outer value, because it is shadowed during the
+execution of @code{myfunc} and cannot be seen or changed from there.
+@cindex call by reference
However, when arrays are the parameters to functions, they are @emph{not}
copied. Instead, the array itself is made available for direct manipulation
-by the function. This is usually called @dfn{passing by reference}.
+by the function. This is usually called @dfn{call by reference}.
Changes made to an array parameter inside the body of a function @emph{are}
visible outside that function. @emph{This can be very dangerous if you don't
watch what you are doing.} For example:@refill
@@ -5841,21 +6369,21 @@ BEGIN @{
@end example
@noindent
-will print @samp{a[1] = 1, a[2] = two, a[3] = 3}, because the call to
+prints @samp{a[1] = 1, a[2] = two, a[3] = 3}, because calling
@code{changeit} stores @code{"two"} in the second element of @code{a}.
-@node Return Statement, , Function Caveats, User-defined
-@section The @code{return} statement
+@node Return Statement, , Function Caveats, User-defined
+@section The @code{return} Statement
@cindex @code{return} statement
-The body of a user--defined function can contain a @code{return} statement.
+The body of a user-defined function can contain a @code{return} statement.
This statement returns control to the rest of the @code{awk} program. It
can also be used to return a value for use in the rest of the @code{awk}
-program. It looks like:@refill
+program. It looks like this:@refill
-@display
-@code{return @var{expression}}
-@end display
+@example
+return @var{expression}
+@end example
The @var{expression} part is optional. If it is omitted, then the returned
value is undefined and, therefore, unpredictable.
@@ -5864,7 +6392,7 @@ A @code{return} statement with no value expression is assumed at the end of
every function definition. So if control reaches the end of the function
definition, then the function returns an unpredictable value.
-Here is an example of a user--defined function that returns a value
+Here is an example of a user-defined function that returns a value
for the largest number among the elements of an array:@refill
@example
@@ -5881,15 +6409,14 @@ function maxelt (vec, i, ret) @{
You call @code{maxelt} with one argument, an array name. The local
variables @code{i} and @code{ret} are not intended to be arguments;
while there is nothing to stop you from passing two or three arguments
-to @code{maxelt}, the results would be strange.
+to @code{maxelt}, the results would be strange. The extra space before
+@code{i} in the function parameter list is to indicate that @code{i} and
+@code{ret} are not supposed to be arguments. This is a convention which
+you should follow when you define functions.
-When writing a function definition, it is conventional to separate the
-parameters from the local variables with extra spaces, as shown above
-in the definition of @code{maxelt}.
-
-Here is a program that uses, or calls, our @code{maxelt} function. This
-program loads an array, calls @code{maxelt}, and then reports the maximum
-number in that array:@refill
+Here is a program that uses our @code{maxelt} function. It loads an
+array, calls @code{maxelt}, and then reports the maximum number in that
+array:@refill
@example
awk '
@@ -5932,30 +6459,33 @@ our program tells us (predictably) that:
@noindent
is the largest number in our array.
-@node Special, Sample Program , User-defined, Top
-@chapter Special Variables
+@node Built-in Variables, Command Line, User-defined, Top
+@chapter Built-in Variables
+@cindex built-in variables
Most @code{awk} variables are available for you to use for your own
-purposes; they will never change except when your program assigns them, and
-will never affect anything except when your program examines them.
+purposes; they never change except when your program assigns them, and
+never affect anything except when your program examines them.
-A few variables have special meanings. Some of them @code{awk} examines
-automatically, so that they enable you to tell @code{awk} how to do
-certain things. Others are set automatically by @code{awk}, so that they
-carry information from the internal workings of @code{awk} to your program.
+A few variables have special built-in meanings. Some of them @code{awk}
+examines automatically, so that they enable you to tell @code{awk} how
+to do certain things. Others are set automatically by @code{awk}, so
+that they carry information from the internal workings of @code{awk} to
+your program.
-Most of these variables are also documented in the chapters where their
-areas of activity are described.
+This chapter documents all the built-in variables of @code{gawk}. Most
+of them are also documented in the chapters where their areas of
+activity are described.
@menu
-* User-modified:: Special variables that you change to control @code{awk}.
+* User-modified:: Built-in variables that you change to control @code{awk}.
-* Auto-set:: Special variables where @code{awk} gives you information.
+* Auto-set:: Built-in variables where @code{awk} gives you information.
@end menu
-@node User-modified, Auto-set, , Special
-@section Special Variables That Control @code{awk}
-@cindex Special variables, user modifiable
+@node User-modified, Auto-set, Built-in Variables, Built-in Variables
+@section Built-in Variables That Control @code{awk}
+@cindex built-in variables, user modifiable
This is a list of the variables which you can change to control how
@code{awk} does certain things.
@@ -5981,6 +6511,21 @@ You can set the value of @code{FS} on the command line using the
awk -F, '@var{program}' @var{input-files}
@end example
+@item IGNORECASE
+@c @vindex IGNORECASE
+If @code{IGNORECASE} is nonzero, then @emph{all} regular expression
+matching is done in a case-independent fashion. In particular, regexp
+matching with @samp{~} and @samp{!~}, and the @code{gsub} @code{index},
+@code{match}, @code{split} and @code{sub} functions all ignore case when
+doing their particular regexp operations. @strong{Note:} since field
+splitting with the value of the @code{FS} variable is also a regular
+expression operation, that too is done with case ignored.
+@xref{Case-sensitivity}.
+
+If @code{gawk} is in compatibility mode (@pxref{Command Line}), then
+@code{IGNORECASE} has no special meaning, and regexp operations are
+always case-sensitive.@refill
+
@item OFMT
@c @vindex OFMT
This string is used by @code{awk} to control conversion of numbers to
@@ -5996,27 +6541,27 @@ default value is @w{@code{" "}}, a string consisting of a single space.
@item ORS
@c @vindex ORS
-This is the output record separator (@pxref{Output Separators}). It
-is output at the end of every @code{print} statement. Its default
-value is the newline character, often represented in @code{awk}
-programs as @samp{\n}.
+This is the output record separator. It is output at the end of every
+@code{print} statement. Its default value is a string containing a
+single newline character, which could be written as @code{"\n"}.
+(@xref{Output Separators}).@refill
@item RS
@c @vindex RS
-This is @code{awk}'s record separator (@pxref{Records}). Its default
-value is a string containing a single newline character, which means
-that an input record consists of a single line of text.@refill
+This is @code{awk}'s record separator. Its default value is a string
+containing a single newline character, which means that an input record
+consists of a single line of text. (@xref{Records}.)@refill
@item SUBSEP
@c @vindex SUBSEP
-@code{SUBSEP} is a subscript separator (@pxref{Multi-dimensional}). It
-has the default value of @code{"\034"}, and is used to separate the
-parts of the name of a multi--dimensional array. Thus, if you access
-@code{foo[12,3]}, it really accesses @code{foo["12\0343"]}.@refill
+@code{SUBSEP} is a subscript separator. It has the default value of
+@code{"\034"}, and is used to separate the parts of the name of a
+multi-dimensional array. Thus, if you access @code{foo[12,3]}, it
+really accesses @code{foo["12\0343"]}. (@xref{Multi-dimensional}).@refill
@end table
-@node Auto-set, , User-modified, Special
-@section Special Variables That Convey Information to You
+@node Auto-set, , User-modified, Built-in Variables
+@section Built-in Variables That Convey Information to You
This is a list of the variables that are set automatically by @code{awk}
on certain occasions so as to provide information for your program.
@@ -6026,10 +6571,10 @@ on certain occasions so as to provide information for your program.
@itemx ARGV
@c @vindex ARGC
@c @vindex ARGV
-The command--line arguments available to @code{awk} are stored in an
-array called @code{ARGV}. @code{ARGC} is the number of command--line
-arguments present. @code{ARGV} is indexed from zero to @w{@code{ARGC} - 1}.
-For example:
+The command-line arguments available to @code{awk} are stored in an
+array called @code{ARGV}. @code{ARGC} is the number of command-line
+arguments present. @code{ARGV} is indexed from zero to @w{@code{ARGC - 1}}.
+@xref{Command Line}. For example:
@example
awk '@{ print ARGV[$1] @}' inventory-shipped BBS-list
@@ -6038,21 +6583,20 @@ awk '@{ print ARGV[$1] @}' inventory-shipped BBS-list
@noindent
In this example, @code{ARGV[0]} contains @code{"awk"}, @code{ARGV[1]}
contains @code{"inventory-shipped"}, and @code{ARGV[2]} contains
-@code{"BBS-list"}. @code{ARGC} is 3, one more than the index of the
-last element in @code{ARGV} since the elements are numbered from zero.
-
-Notice that the @code{awk} program is not treated as an argument. The
-@samp{-f} @file{@var{filename}} option, and the @samp{-F} option,
-are also not treated as arguments for this purpose.
+@code{"BBS-list"}. The value of @code{ARGC} is 3, one more than the
+index of the last element in @code{ARGV} since the elements are numbered
+from zero.@refill
-Variable assignments on the command line @emph{are} treated as arguments,
-and do show up in the @code{ARGV} array.
+Notice that the @code{awk} program is not entered in @code{ARGV}. The
+other special command line options, with their arguments, are also not
+entered. But variable assignments on the command line @emph{are}
+treated as arguments, and do show up in the @code{ARGV} array.
-Your program can alter @code{ARGC} the elements of @code{ARGV}. Each
-time @code{awk} reaches the end of an input file, it uses the next
+Your program can alter @code{ARGC} and the elements of @code{ARGV}.
+Each time @code{awk} reaches the end of an input file, it uses the next
element of @code{ARGV} as the name of the next input file. By storing a
different string there, your program can change which files are read.
-You can use @samp{-} to represent the standard input. By storing
+You can use @code{"-"} to represent the standard input. By storing
additional elements and incrementing @code{ARGC} you can cause
additional files to be read.
@@ -6074,8 +6618,10 @@ the particular environment variables. For example,
@code{ENVIRON["HOME"]} might be @file{/u/close}. Changing this array
does not affect the environment passed on to any programs that
@code{awk} may spawn via redirection or the @code{system} function.
-(This may not work under operating systems other than MS-DOS, Unix, or
-GNU.)
+(In a future version of @code{gawk}, it may do so.)
+
+Some operating systems may not have environment variables.
+On such systems, the array @code{ENVIRON} is empty.
@item FILENAME
@c @vindex FILENAME
@@ -6096,7 +6642,7 @@ It is reinitialized to 0 each time a new input file is started.
@c @vindex NF
@code{NF} is the number of fields in the current input record.
@code{NF} is set each time a new record is read, when a new field is
-created, or when $0 changes (@pxref{Fields}).@refill
+created, or when @code{$0} changes (@pxref{Fields}).@refill
@item NR
@c @vindex NR
@@ -6106,26 +6652,1274 @@ the beginning of the program's execution. (@pxref{Records}).
@item RLENGTH
@c @vindex RLENGTH
-@code{RLENGTH} is the length of the string matched by the @code{match}
-function (@pxref{String Functions}). @code{RLENGTH} is set by
-invoking the @code{match} function. Its value is the length of the
-matched string, or -1 if no match was found.@refill
+@code{RLENGTH} is the length of the substring matched by the
+@code{match} function (@pxref{String Functions}). @code{RLENGTH} is set
+by invoking the @code{match} function. Its value is the length of the
+matched string, or @minus{}1 if no match was found.@refill
@item RSTART
@c @vindex RSTART
-@code{RSTART} is the start of the string matched by the @code{match}
-function (@pxref{String Functions}). @code{RSTART} is set by invoking
-the @code{match} function. Its value is the position of the string where
-the matched string starts, or 0 if no match was found.@refill
+@code{RSTART} is the start-index of the substring matched by the
+@code{match} function (@pxref{String Functions}). @code{RSTART} is set
+by invoking the @code{match} function. Its value is the position of the
+string where the matched substring starts, or 0 if no match was
+found.@refill
@end table
-@node Sample Program, Notes, Special , Top
+@node Command Line, Language History, Built-in Variables, Top
+@c node-name, next, previous, up
+@chapter Invocation of @code{awk}
+@cindex command line
+@cindex invocation of @code{gawk}
+@cindex arguments, command line
+@cindex options, command line
+
+There are two ways to run @code{awk}: with an explicit program, or with
+one or more program files. Here are templates for both of them; items
+enclosed in @samp{@r{[}@dots{}@r{]}} in these templates are optional.
+
+@example
+awk @r{[@code{-F@var{fs}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} '@var{program}' @var{file} @dots{}
+awk @r{[@code{-F@var{fs}}] @code{-f @var{source-file}} [@code{-f @var{source-file} @dots{}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} @var{file} @dots{}
+@end example
+
+@menu
+* Options:: Command line options and their meanings.
+* Other Arguments:: Input file names and variable assignments.
+* AWKPATH Variable:: Searching directories for @code{awk} programs.
+@end menu
+
+@node Options, Other Arguments, Command Line, Command Line
+@section Command Line Options
+
+Options begin with a minus sign, and consist of a single character.
+The options and their meanings are as follows:
+
+@table @code
+@item -F@var{fs}
+Sets the @code{FS} variable to @var{fs} (@pxref{Field Separators}).
+
+@item -f @var{source-file}
+Indicates that the @code{awk} program is to be found in @var{source-file}
+instead of in the first non-option argument.
+
+@item -v @var{var}=@var{val}
+@cindex @samp{-v} option
+Sets the variable @var{var} to the value @var{val} @emph{before}
+execution of the program begins. Such variable values are available
+inside the @code{BEGIN} rule (see below for a fuller explanation).
+
+The @samp{-v} option only has room to set one variable, but you can use
+it more than once, setting another variable each time, like this:
+@samp{@w{-v foo=1} @w{-v bar=2}}.
+
+@item -a
+Specifies use of traditional @code{awk} syntax for regular expressions.
+This means that @samp{\} can be used to quote any regular expression
+operators inside of square brackets, just as it can be outside of them.
+This mode is currently the default; the @samp{-a} option is useful in
+shell scripts so that they will not break if the default is changed.
+@xref{Regexp Operators}.
+
+@item -e
+Specifies use of @code{egrep} syntax for regular expressions. This
+means that @samp{\} does not serve as a quoting character inside of
+square brackets; ideosyncratic techniques are needed to include various
+special characters within them. This mode may become the default at
+some time in the future. @xref{Regexp Operators}.
+
+@item -c
+@cindex @samp{-c} option
+Specifies @dfn{compatibility mode}, in which the GNU extensions in
+@code{gawk} are disabled, so that @code{gawk} behaves just like Unix
+@code{awk}. These extensions are noted below, where their usage is
+explained. @xref{Compatibility Mode}.
+
+@item -V
+@cindex @samp{-V} option
+Prints version information for this particular copy of @code{gawk}.
+This is so you can determine if your copy of @code{gawk} is up to date
+with respect to whatever the Free Software Foundation is currently
+distributing. This option may disappear in a future version of @code{gawk}.
+
+@item -C
+@cindex @samp{-C} option
+Prints the short version of the General Public License.
+This option may disappear in a future version of @code{gawk}.
+
+@item --
+Signals the end of the command line options. The following arguments
+are not treated as options even if they begin with @samp{-}. This
+interpretation of @samp{--} follows the POSIX argument parsing
+conventions.
+
+This is useful if you have file names that start with @samp{-},
+or in shell scripts, if you have file names that will be specified
+by the user and that might start with @samp{-}.
+@end table
+
+Any other options are flagged as invalid with a warning message, but
+are otherwise ignored.
+
+In compatibility mode, as a special case, if the value of @var{fs} supplied
+to the @samp{-F} option is @samp{t}, then @code{FS} is set to the tab
+character (@code{"\t"}). Also, the @samp{-C} and @samp{-V} options
+are not recognized.@refill
+
+If the @samp{-f} option is @emph{not} used, then the first non-option
+command line argument is expected to be the program text.
+
+The @samp{-f} option may be used more than once on the command line.
+Then @code{awk} reads its program source from all of the named files, as
+if they had been concatenated together into one big file. This is
+useful for creating libraries of @code{awk} functions. Useful functions
+can be written once, and then retrieved from a standard place, instead
+of having to be included into each individual program. You can still
+type in a program at the terminal and use library functions, by specifying
+@samp{-f /dev/tty}. @code{awk} will read a file from the terminal
+to use as part of the @code{awk} program. After typing your program,
+type @kbd{Control-d} (the end-of-file character) to terminate it.
+
+@node Other Arguments, AWKPATH Variable, Options, Command Line
+@section Other Command Line Arguments
+
+Any additional arguments on the command line are normally treated as
+input files to be processed in the order specified. However, an
+argument that has the form @code{@var{var}=@var{value}}, means to assign
+the value @var{value} to the variable @var{var}---it does not specify a
+file at all.
+
+@vindex ARGV
+All these arguments are made available to your @code{awk} program in the
+@code{ARGV} array (@pxref{Built-in Variables}). Command line options
+and the program text (if present) are omitted from the @code{ARGV}
+array. All other arguments, including variable assignments, are
+included.
+
+The distinction between file name arguments and variable-assignment
+arguments is made when @code{awk} is about to open the next input file.
+At that point in execution, it checks the ``file name'' to see whether
+it is really a variable assignment; if so, @code{awk} sets the variable
+instead of reading a file.
+
+Therefore, the variables actually receive the specified values after all
+previously specified files have been read. In particular, the values of
+variables assigned in this fashion are @emph{not} available inside a
+@code{BEGIN} rule (@pxref{BEGIN/END}), since such rules are run before
+@code{awk} begins scanning the argument list.@refill
+
+In some earlier implementations of @code{awk}, when a variable assignment
+occurred before any file names, the assignment would happen @emph{before}
+the @code{BEGIN} rule was executed. Some applications came to depend
+upon this ``feature''. When @code{awk} was changed to be more consistent,
+the @samp{-v} option was added to accomodate applications that depended
+upon this old behaviour.
+
+The variable assignment feature is most useful for assigning to variables
+such as @code{RS}, @code{OFS}, and @code{ORS}, which control input and
+output formats, before scanning the data files. It is also useful for
+controlling state if multiple passes are needed over a data file. For
+example:@refill
+
+@cindex multiple passes over data
+@cindex passes, multiple
+@example
+awk 'pass == 1 @{ @var{pass 1 stuff} @}
+ pass == 2 @{ @var{pass 2 stuff} @}' pass=1 datafile pass=2 datafile
+@end example
+
+@node AWKPATH Variable,, Other Arguments, Command Line
+@section The @code{AWKPATH} Environment Variable
+@cindex @code{AWKPATH} environment variable
+@cindex search path
+@cindex directory search
+@cindex path, search
+@c @cindex differences between @code{gawk} and @code{awk}
+
+The previous section described how @code{awk} program files can be named
+on the command line with the @samp{-f} option. In some @code{awk}
+implementations, you must supply a precise path name for each program
+file, unless the file is in the current directory.
+
+But in @code{gawk}, if the file name supplied in the @samp{-f} option
+does not contain a @samp{/}, then @code{gawk} searches a list of
+directories (called the @dfn{search path}), one by one, looking for a
+file with the specified name.
+
+The search path is actually a string containing directory names
+separated by colons. @code{gawk} gets its search path from the
+@code{AWKPATH} environment variable. If that variable does not exist,
+@code{gawk} uses the default path, which is
+@samp{.:/usr/lib/awk:/usr/local/lib/awk}.@refill
+
+The search path feature is particularly useful for building up libraries
+of useful @code{awk} functions. The library files can be placed in a
+standard directory that is in the default path, and then specified on
+the command line with a short file name. Otherwise, the full file name
+would have to be typed for each file.
+
+Path searching is not done if @code{gawk} is in compatibility mode.
+@xref{Command Line}.
+
+@strong{Note:} if you want files in the current directory to be found,
+you must include the current directory in the path, either by writing
+@file{.} as an entry in the path, or by writing a null entry in the
+path. (A null entry is indicated by starting or ending the path with a
+colon, or by placing two colons next to each other (@samp{::}).) If the
+current directory is not included in the path, then files cannot be
+found in the current directory. This path search mechanism is identical
+to the shell's.
+@c someday, @cite{The Bourne Again Shell}....
+
+@node Language History, Gawk Summary, Command Line, Top
+@chapter The Evolution of the @code{awk} Language
+
+This manual describes the GNU implementation of @code{awk}, which is patterned
+after the System V Release 4 version. Many @code{awk} users are only familiar
+with the original @code{awk} implementation in Version 7 Unix, which is also
+the basis for the version in Berkeley Unix. This chapter briefly describes
+the evolution of the @code{awk} language.
+
+@menu
+* V7/S5R3.1:: The major changes between V7 and System V Release 3.1.
+
+* S5R4:: The minor changes between System V Releases 3.1 and 4.
+
+* S5R4/GNU:: The extensions in @code{gawk} not in System V Release 4.
+@end menu
+
+@node V7/S5R3.1, S5R4, Language History, Language History
+@section Major Changes Between V7 and S5R3.1
+
+The @code{awk} language evolved considerably between the release of
+Version 7 Unix (1978) and the new version first made widely available in
+System V Release 3.1 (1987). This section summarizes the changes, with
+cross-references to further details.
+
+@itemize @bullet
+@item
+The requirement for @samp{;} to separate rules on a line
+(@pxref{Statements/Lines}).
+
+@item
+User-defined functions, and the @code{return} statement
+(@pxref{User-defined}).
+
+@item
+The @code{delete} statement (@pxref{Delete}).
+
+@item
+The @code{do}-@code{while} statement (@pxref{Do Statement}).
+
+@item
+The built-in functions @code{atan2}, @code{cos}, @code{sin}, @code{rand} and
+@code{srand} (@pxref{Numeric Functions}).
+
+@item
+The built-in functions @code{gsub}, @code{sub}, and @code{match}
+(@pxref{String Functions}).
+
+@item
+The built-in functions @code{close} and @code{system} (@pxref{I/O
+Functions}).
+
+@item
+The @code{ARGC}, @code{ARGV}, @code{FNR}, @code{RLENGTH}, @code{RSTART},
+and @code{SUBSEP} built-in variables (@pxref{Built-in Variables}).
+
+@item
+The conditional expression using the operators @samp{?} and @samp{:}
+(@pxref{Conditional Exp}).
+
+@item
+The exponentiation operator @samp{^} (@pxref{Arithmetic Ops}) and its
+assignment operator form @samp{^=} (@pxref{Assignment Ops}).@refill
+
+@item
+C-compatible operator precedence, which breaks some old @code{awk}
+programs (@pxref{Precedence}).
+
+@item
+Regexps as the value of @code{FS} (@pxref{Field Separators}), or as the
+third argument to the @code{split} function (@pxref{String
+Functions}).@refill
+
+@item
+Dynamic regexps as operands of the @samp{~} and @samp{!~} operators
+(@pxref{Regexp Usage}).
+
+@item
+Escape sequences (@pxref{Constants}) in regexps.@refill
+
+@item
+The escape sequences @samp{\b}, @samp{\f}, and @samp{\r}
+(@pxref{Constants}).
+
+@item
+Redirection of input for the @code{getline} function (@pxref{Getline}).
+
+@item
+Multiple @code{BEGIN} and @code{END} rules (@pxref{BEGIN/END}).
+
+@item
+Simulation of multidimensional arrays (@pxref{Multi-dimensional}).
+@end itemize
+
+@node S5R4, S5R4/GNU, V7/S5R3.1, Language History
+@section Minor Changes between S5R3.1 and S5R4
+
+The System V Release 4 version of Unix @code{awk} added these features:
+
+@itemize @bullet
+@item
+The @code{ENVIRON} variable (@pxref{Built-in Variables}).
+
+@item
+Multiple @samp{-f} options on the command line (@pxref{Command Line}).
+
+@item
+The @samp{-v} option for assigning variables before program execution begins
+(@pxref{Command Line}).
+
+@item
+The @samp{--} option for terminating command line options.
+
+@item
+The @samp{\a}, @samp{\v}, and @samp{\x} escape sequences (@pxref{Constants}).
+
+@item
+A defined return value for the @code{srand} built-in function
+(@pxref{Numeric Functions}).
+
+@item
+The @code{toupper} and @code{tolower} built-in string functions
+for case translation (@pxref{String Functions}).
+
+@item
+A cleaner specification for the @samp{%c} format-control letter in the
+@code{printf} function (@pxref{Printf}).
+
+@item
+The use of constant regexps such as @code{/foo/} as expressions, where
+they are equivalent to use of the matching operator, as in @code{$0 ~
+/foo/}.
+@end itemize
+
+@node S5R4/GNU, , S5R4, Language History
+@section Extensions In @code{gawk} Not In S5R4
+
+The GNU implementation, @code{gawk}, adds these features:
+
+@itemize @bullet
+@item
+The @code{AWKPATH} environment variable for specifying a path search for
+the @samp{-f} command line option (@pxref{Command Line}).
+
+@item
+The @samp{-C} and @samp{-V} command line options (@pxref{Command Line}).
+
+@item
+The @code{IGNORECASE} variable and its effects (@pxref{Case-sensitivity}).
+
+@item
+The @file{/dev/stdin}, @file{/dev/stdout}, @file{/dev/stderr}, and
+@file{/dev/fd/@var{n}} file name interpretation (@pxref{Special Files}).
+
+@item
+The @samp{-c} option to turn off these extensions (@pxref{Command Line}).
+
+@item
+The @samp{-a} and @samp{-e} options to specify the syntax of regular
+expressions that @code{gawk} will accept (@pxref{Command Line}).
+@end itemize
+
+@node Gawk Summary, Sample Program, Language History, Top
+@appendix @code{gawk} Summary
+
+@ignore
+See, man pages are good for something. This chapter started life as the
+gawk.1 man page for 2.11.
+@end ignore
+
+This appendix provides a brief summary of the @code{gawk} command line and the
+@code{awk} language. It is designed to serve as ``quick reference.'' It is
+therefore terse, but complete.
+
+@menu
+* Command Line Summary:: Recapitulation of the command line.
+* Language Summary:: A terse review of the language.
+* Variables/Fields:: Variables, fields, and arrays.
+* Rules Summary:: Patterns and Actions, and their component parts.
+* Functions Summary:: Defining and calling functions.
+@end menu
+
+@node Command Line Summary, Language Summary, Gawk Summary, Gawk Summary
+@appendixsec Command Line Options Summary
+
+The command line consists of options to @code{gawk} itself, the
+@code{awk} program text (if not supplied via the @samp{-f} option), and
+values to be made available in the @code{ARGC} and @code{ARGV}
+predefined @code{awk} variables:
+
+@example
+awk @r{[@code{-F@var{fs}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} '@var{program}' @var{file} @dots{}
+awk @r{[@code{-F@var{fs}}] @code{-f @var{source-file}} [@code{-f @var{source-file} @dots{}}] [@code{-v @var{var}=@var{val}}] [@code{-V}] [@code{-C}] [@code{-c}] [@code{-a}] [@code{-e}] [@code{--}]} @var{file} @dots{}
+@end example
+
+The options that @code{gawk} accepts are:
+
+@table @code
+@item -F@var{fs}
+Use @var{fs} for the input field separator (the value of the @code{FS}
+predefined variable).
+
+@item -f @var{program-file}
+Read the @code{awk} program source from the file @var{program-file}, instead
+of from the first command line argument.
+
+@item -v @var{var}=@var{val}
+Assign the variable @var{var} the value @var{val} before program execution
+begins.
+
+@item -a
+Specifies use of traditional @code{awk} syntax for regular expressions.
+This means that @samp{\} can be used to quote regular expression
+operators inside of square brackets, just as it can be outside of them.
+
+@item -e
+Specifies use of @code{egrep} syntax for regular expressions. This
+means that @samp{\} does not serve as a quoting character inside of
+square brackets.
+
+@item -c
+Specifies compatibility mode, in which @code{gawk} extensions are turned
+off.
+
+@item -V
+Print version information for this particular copy of @code{gawk} on the error
+output. This option may disappear in a future version of @code{gawk}.
+
+@item -C
+Print the short version of the General Public License on the error
+output. This option may disappear in a future version of @code{gawk}.
+
+@item --
+Signal the end of options. This is useful to allow further arguments to the
+@code{awk} program itself to start with a @samp{-}. This is mainly for
+consistency with the argument parsing conventions of POSIX.
+@end table
+
+Any other options are flagged as invalid, but are otherwise ignored.
+@xref{Command Line}, for more details.
+
+@node Language Summary, Variables/Fields, Command Line Summary, Gawk Summary
+@appendixsec Language Summary
+
+An @code{awk} program consists of a sequence of pattern-action statements
+and optional function definitions.
+
+@example
+@var{pattern} @{ @var{action statements} @}
+
+function @var{name}(@var{parameter list}) @{ @var{action statements} @}
+@end example
+
+@code{gawk} first reads the program source from the
+@var{program-file}(s) if specified, or from the first non-option
+argument on the command line. The @samp{-f} option may be used multiple
+times on the command line. @code{gawk} reads the program text from all
+the @var{program-file} files, effectively concatenating them in the
+order they are specified. This is useful for building libraries of
+@code{awk} functions, without having to include them in each new
+@code{awk} program that uses them. To use a library function in a file
+from a program typed in on the command line, specify @samp{-f /dev/tty};
+then type your program, and end it with a @kbd{C-d}. @xref{Command
+Line}.
+
+The environment variable @code{AWKPATH} specifies a search path to use
+when finding source files named with the @samp{-f} option. If the
+variable @code{AWKPATH} is not set, @code{gawk} uses the default path,
+@samp{.:/usr/lib/awk:/usr/local/lib/awk}. If a file name given to the
+@samp{-f} option contains a @samp{/} character, no path search is
+performed. @xref{AWKPATH Variable}, for a full description of the
+@code{AWKPATH} environment variable.@refill
+
+@code{gawk} compiles the program into an internal form, and then proceeds to
+read each file named in the @code{ARGV} array. If there are no files named
+on the command line, @code{gawk} reads the standard input.
+
+If a ``file'' named on the command line has the form
+@samp{@var{var}=@var{val}}, it is treated as a variable assignment: the
+variable @var{var} is assigned the value @var{val}.
+
+For each line in the input, @code{gawk} tests to see if it matches any
+@var{pattern} in the @code{awk} program. For each pattern that the line
+matches, the associated @var{action} is executed.
+
+@node Variables/Fields, Rules Summary, Language Summary, Gawk Summary
+@appendixsec Variables and Fields
+
+@code{awk} variables are dynamic; they come into existence when they are
+first used. Their values are either floating-point numbers or strings.
+@code{awk} also has one-dimension arrays; multiple-dimensional arrays
+may be simulated. There are several predefined variables that
+@code{awk} sets as a program runs; these are summarized below.
+
+@menu
+* Fields Summary:: Input field splitting.
+* Built-in Summary:: @code{awk}'s built-in variables.
+* Arrays Summary:: Using arrays.
+* Data Type Summary:: Values in @code{awk} are numbers or strings.
+@end menu
+
+@node Fields Summary, Built-in Summary, Variables/Fields, Variables/Fields
+@appendixsubsec Fields
+
+As each input line is read, @code{gawk} splits the line into
+@var{fields}, using the value of the @code{FS} variable as the field
+separator. If @code{FS} is a single character, fields are separated by
+that character. Otherwise, @code{FS} is expected to be a full regular
+expression. In the special case that @code{FS} is a single blank,
+fields are separated by runs of blanks and/or tabs. Note that the value
+of @code{IGNORECASE} (@pxref{Case-sensitivity}) also affects how fields
+are split when @code{FS} is a regular expression.
+
+Each field in the input line may be referenced by its position, @code{$1},
+@code{$2}, and so on. @code{$0} is the whole line. The value of a field may
+be assigned to as well. Field numbers need not be constants:
+
+@example
+n = 5
+print $n
+@end example
+
+@noindent
+prints the fifth field in the input line. The variable @code{NF} is set to
+the total number of fields in the input line.
+
+References to nonexistent fields (i.e., fields after @code{$NF}) return
+the null-string. However, assigning to a nonexistent field (e.g.,
+@code{$(NF+2) = 5}) increases the value of @code{NF}, creates any
+intervening fields with the null string as their value, and causes the
+value of @code{$0} to be recomputed, with the fields being separated by
+the value of @code{OFS}.@refill
+
+@xref{Reading Files}, for a full description of the way @code{awk} defines
+and uses fields.
+
+@node Built-in Summary, Arrays Summary, Fields Summary, Variables/Fields
+@appendixsubsec Built-in Variables
+
+@code{awk}'s built-in variables are:
+
+@table @code
+@item ARGC
+The number of command line arguments (not including options or the
+@code{awk} program itself).
+
+@item ARGV
+The array of command line arguments. The array is indexed from 0 to
+@code{ARGC} - 1. Dynamically changing the contents of @code{ARGV} can control
+the files used for data.@refill
+
+@item ENVIRON
+An array containing the values of the environment variables. The array
+is indexed by variable name, each element being the value of that
+variable. Thus, the environment variable @code{HOME} would be in
+@code{ENVIRON["HOME"]}. Its value might be @file{/u/close}.
+
+Changing this array does not affect the environment seen by programs
+which @code{gawk} spawns via redirection or the @code{system} function.
+(This may change in a future version of @code{gawk}.)
+
+Some operating systems do not have environment variables.
+The array @code{ENVIRON} is empty when running on these systems.
+
+@item FILENAME
+The name of the current input file. If no files are specified on the command
+line, the value of @code{FILENAME} is @samp{-}.
+
+@item FNR
+The input record number in the current input file.
+
+@item FS
+The input field separator, a blank by default.
+
+@item IGNORECASE
+The case-sensitivity flag for regular expression operations. If
+@code{IGNORECASE} has a nonzero value, then pattern matching in rules,
+field splitting with @code{FS}, regular expression matching with
+@samp{~} and @samp{!~}, and the @code{gsub}, @code{index}, @code{match},
+@code{split} and @code{sub} predefined functions all ignore case
+when doing regular expression operations.@refill
+
+@item NF
+The number of fields in the current input record.
+
+@item NR
+The total number of input records seen so far.
+
+@item OFMT
+The output format for numbers, @code{"%.6g"} by default.
+
+@item OFS
+The output field separator, a blank by default.
+
+@item ORS
+The output record separator, by default a newline.
+
+@item RS
+The input record separator, by default a newline. @code{RS} is exceptional
+in that only the first character of its string value is used for separating
+records. If @code{RS} is set to the null string, then records are separated by
+blank lines. When @code{RS} is set to the null string, then the newline
+character always acts as a field separator, in addition to whatever value
+@code{FS} may have.@refill
+
+@item RSTART
+The index of the first character matched by @code{match}; 0 if no match.
+
+@item RLENGTH
+The length of the string matched by @code{match}; @minus{}1 if no match.
+
+@item SUBSEP
+The string used to separate multiple subscripts in array elements, by
+default @code{"\034"}.
+@end table
+
+@xref{Built-in Variables}.
+
+@node Arrays Summary, Data Type Summary, Built-in Summary, Variables/Fields
+@appendixsubsec Arrays
+
+Arrays are subscripted with an expression between square brackets
+(@samp{[} and @samp{]}). The expression may be either a number or
+a string. Since arrays are associative, string indices are meaningful
+and are not converted to numbers.
+
+If you use multiple expressions separated by commas inside the square
+brackets, then the array subscript is a string consisting of the
+concatenation of the individual subscript values, converted to strings,
+separated by the subscript separator (the value of @code{SUBSEP}).
+
+The special operator @code{in} may be used in an @code{if} or
+@code{while} statement to see if an array has an index consisting of a
+particular value.
+
+@group
+@example
+if (val in array)
+ print array[val]
+@end example
+@end group
+
+If the array has multiple subscripts, use @code{(i, j, @dots{}) in array}
+to test for existence of an element.
+
+The @code{in} construct may also be used in a @code{for} loop to iterate
+over all the elements of an array. @xref{Scanning an Array}.
+
+An element may be deleted from an array using the @code{delete} statement.
+
+@xref{Arrays}, for more detailed information.
+
+@node Data Type Summary, , Arrays Summary, Variables/Fields
+@appendixsubsec Data Types
+
+The value of an @code{awk} expression is always either a number
+or a string.
+
+Certain contexts (such as arithmetic operators) require numeric
+values. They convert strings to numbers by interpreting the text
+of the string as a numeral. If the string does not look like a
+numeral, it converts to 0.
+
+Certain contexts (such as concatenation) require string values.
+They convert numbers to strings by effectively printing them.
+
+To force conversion of a string value to a number, simply add 0
+to it. If the value you start with is already a number, this
+does not change it.
+
+To force conversion of a numeric value to a string, concatenate it with
+the null string.
+
+The @code{awk} language defines comparisons as being done numerically if
+possible, otherwise one or both operands are converted to strings and
+a string comparison is performed.
+
+Uninitialized variables have the string value @code{""} (the null, or
+empty, string). In contexts where a number is required, this is
+equivalent to 0.
+
+@xref{Variables}, for more information on variable naming and initialization;
+@pxref{Conversion}, for more information on how variable values are
+interpreted.@refill
+
+@node Rules Summary, Functions Summary, Variables/Fields, Gawk Summary
+@appendixsec Patterns and Actions
+
+@menu
+* Pattern Summary:: Quick overview of patterns.
+* Regexp Summary:: Quick overview of regular expressions.
+* Actions Summary:: Quick overview of actions.
+@end menu
+
+An @code{awk} program is mostly composed of rules, each consisting of a
+pattern followed by an action. The action is enclosed in @samp{@{} and
+@samp{@}}. Either the pattern may be missing, or the action may be
+missing, but, of course, not both. If the pattern is missing, the
+action is executed for every single line of input. A missing action is
+equivalent to this action,
+
+@example
+@{ print @}
+@end example
+
+@noindent
+which prints the entire line.
+
+Comments begin with the @samp{#} character, and continue until the end of the
+line. Blank lines may be used to separate statements. Normally, a statement
+ends with a newline, however, this is not the case for lines ending in a
+@samp{,}, @samp{@{}, @samp{?}, @samp{:}, @samp{&&}, or @samp{||}. Lines
+ending in @code{do} or @code{else} also have their statements automatically
+continued on the following line. In other cases, a line can be continued by
+ending it with a @samp{\}, in which case the newline is ignored.@refill
+
+Multiple statements may be put on one line by separating them with a @samp{;}.
+This applies to both the statements within the action part of a rule (the
+usual case), and to the rule statements themselves.
+
+@xref{Comments}, for information on @code{awk}'s commenting convention;
+@pxref{Statements/Lines}, for a description of the line continuation
+mechanism in @code{awk}.
+
+@node Pattern Summary, Regexp Summary, Rules Summary, Rules Summary
+@appendixsubsec Patterns
+
+@code{awk} patterns may be one of the following:
+
+@example
+/@var{regular expression}/
+@var{relational expression}
+@var{pattern} && @var{pattern}
+@var{pattern} || @var{pattern}
+@var{pattern} ? @var{pattern} : @var{pattern}
+(@var{pattern})
+! @var{pattern}
+@var{pattern1}, @var{pattern2}
+BEGIN
+END
+@end example
+
+@code{BEGIN} and @code{END} are two special kinds of patterns that are not
+tested against the input. The action parts of all @code{BEGIN} rules are
+merged as if all the statements had been written in a single @code{BEGIN}
+rule. They are executed before any of the input is read. Similarly, all the
+@code{END} rules are merged, and executed when all the input is exhausted (or
+when an @code{exit} statement is executed). @code{BEGIN} and @code{END}
+patterns cannot be combined with other patterns in pattern expressions.
+@code{BEGIN} and @code{END} rules cannot have missing action parts.@refill
+
+For @samp{/@var{regular-expression}/} patterns, the associated statement is
+executed for each input line that matches the regular expression. Regular
+expressions are the same as those in @code{egrep}, and are summarized below.
+
+A @var{relational expression} may use any of the operators defined below in
+the section on actions. These generally test whether certain fields match
+certain regular expressions.
+
+The @samp{&&}, @samp{||}, and @samp{!} operators are logical ``and'',
+logical ``or'', and logical ``not'', respectively, as in C. They do
+short-circuit evaluation, also as in C, and are used for combining more
+primitive pattern expressions. As in most languages, parentheses may be
+used to change the order of evaluation.
+
+The @samp{?:} operator is like the same operator in C. If the first
+pattern matches, then the second pattern is matched against the input
+record; otherwise, the third is matched. Only one of the second and
+third patterns is matched.
+
+The @samp{@var{pattern1}, @var{pattern2}} form of a pattern is called a
+range pattern. It matches all input lines starting with a line that
+matches @var{pattern1}, and continuing until a line that matches
+@var{pattern2}, inclusive. A range pattern cannot be used as an operand
+to any of the pattern operators.
+
+@xref{Patterns}, for a full description of the pattern part of @code{awk}
+rules.
+
+@node Regexp Summary, Actions Summary, Pattern Summary, Rules Summary
+@appendixsubsec Regular Expressions
+
+Regular expressions are the extended kind found in @code{egrep}.
+They are composed of characters as follows:
+
+@table @code
+@item @var{c}
+matches the character @var{c} (assuming @var{c} is a character with no
+special meaning in regexps).
+
+@item \@var{c}
+matches the literal character @var{c}.
+
+@item .
+matches any character except newline.
+
+@item ^
+matches the beginning of a line or a string.
+
+@item $
+matches the end of a line or a string.
+
+@item [@var{abc}@dots{}]
+matches any of the characters @var{abc}@dots{} (character class).
+
+@item [^@var{abc}@dots{}]
+matches any character except @var{abc}@dots{} and newline (negated
+character class).
+
+@item @var{r1}|@var{r2}
+matches either @var{r1} or @var{r2} (alternation).
+
+@item @var{r1r2}
+matches @var{r1}, and then @var{r2} (concatenation).
+
+@item @var{r}+
+matches one or more @var{r}'s.
+
+@item @var{r}*
+matches zero or more @var{r}'s.
+
+@item @var{r}?
+matches zero or one @var{r}'s.
+
+@item (@var{r})
+matches @var{r} (grouping).
+@end table
+
+@xref{Regexp}, for a more detailed explanation of regular expressions.
+
+The escape sequences allowed in string constants are also valid in
+regular expressions (@pxref{Constants}).
+
+@node Actions Summary, , Regexp Summary, Rules Summary
+@appendixsubsec Actions
+
+Action statements are enclosed in braces, @samp{@{} and @samp{@}}.
+Action statements consist of the usual assignment, conditional, and looping
+statements found in most languages. The operators, control statements,
+and input/output statements available are patterned after those in C.
+
+@menu
+* Operator Summary:: @code{awk} operators.
+* Control Flow Summary:: The control statements.
+* I/O Summary:: The I/O statements.
+* Printf Summary:: A summary of @code{printf}.
+* Special File Summary:: Special file names interpreted internally.
+* Numeric Functions Summary:: Built-in numeric functions.
+* String Functions Summary:: Built-in string functions.
+* String Constants Summary:: Escape sequences in strings.
+@end menu
+
+@node Operator Summary, Control Flow Summary, Actions Summary, Actions Summary
+@appendixsubsubsec Operators
+
+The operators in @code{awk}, in order of increasing precedence, are
+
+@table @code
+@item = += -= *= /= %= ^=
+Assignment. Both absolute assignment (@code{@var{var}=@var{value}})
+and operator assignment (the other forms) are supported.
+
+@item ?:
+A conditional expression, as in C. This has the form @code{@var{expr1} ?
+@var{expr2} : @var{expr3}}. If @var{expr1} is true, the value of the
+expression is @var{expr2}; otherwise it is @var{expr3}. Only one of
+@var{expr2} and @var{expr3} is evaluated.@refill
+
+@item ||
+Logical ``or''.
+
+@item &&
+Logical ``and''.
+
+@item ~ !~
+Regular expression match, negated match.
+
+@item < <= > >= != ==
+The usual relational operators.
+
+@item @var{blank}
+String concatenation.
+
+@item + -
+Addition and subtraction.
+
+@item * / %
+Multiplication, division, and modulus.
+
+@item + - !
+Unary plus, unary minus, and logical negation.
+
+@item ^
+Exponentiation (@samp{**} may also be used, and @samp{**=} for the assignment
+operator).
+
+@item ++ --
+Increment and decrement, both prefix and postfix.
+
+@item $
+Field reference.
+@end table
+
+@xref{Expressions}, for a full description of all the operators listed
+above. @xref{Fields}, for a description of the field reference operator.
+
+@node Control Flow Summary, I/O Summary, Operator Summary, Actions Summary
+@appendixsubsubsec Control Statements
+
+The control statements are as follows:
+
+@example
+if (@var{condition}) @var{statement} @r{[} else @var{statement} @r{]}
+while (@var{condition}) @var{statement}
+do @var{statement} while (@var{condition})
+for (@var{expr1}; @var{expr2}; @var{expr3}) @var{statement}
+for (@var{var} in @var{array}) @var{statement}
+break
+continue
+delete @var{array}[@var{index}]
+exit @r{[} @var{expression} @r{]}
+@{ @var{statements} @}
+@end example
+
+@xref{Statements}, for a full description of all the control statements
+listed above.
+
+@node I/O Summary, Printf Summary, Control Flow Summary, Actions Summary
+@appendixsubsubsec I/O Statements
+
+The input/output statements are as follows:
+
+@table @code
+@item getline
+Set @code{$0} from next input record; set @code{NF}, @code{NR}, @code{FNR}.
+
+@item getline <@var{file}
+Set @code{$0} from next record of @var{file}; set @code{NF}.
+
+@item getline @var{var}
+Set @var{var} from next input record; set @code{NF}, @code{FNR}.
+
+@item getline @var{var} <@var{file}
+Set @var{var} from next record of @var{file}.
+
+@item next
+Stop processing the current input record. The next input record is read and
+processing starts over with the first pattern in the @code{awk} program.
+If the end of the input data is reached, the @code{END} rule(s), if any,
+are executed.
+
+@item print
+Prints the current record.
+
+@item print @var{expr-list}
+Prints expressions.
+
+@item print @var{expr-list} > @var{file}
+Prints expressions on @var{file}.
+
+@item printf @var{fmt, expr-list}
+Format and print.
+
+@item printf @var{fmt, expr-list} > file
+Format and print on @var{file}.
+@end table
+
+Other input/output redirections are also allowed. For @code{print} and
+@code{printf}, @samp{>> @var{file}} appends output to the @var{file},
+while @samp{| @var{command}} writes on a pipe. In a similar fashion,
+@samp{@var{command} | getline} pipes input into @code{getline}.
+@code{getline} returns 0 on end of file, and @minus{}1 on an error.@refill
+
+@xref{Getline}, for a full description of the @code{getline} statement.
+@xref{Printing}, for a full description of @code{print} and
+@code{printf}. Finally, @pxref{Next Statement}, for a description of
+how the @code{next} statement works.@refill
+
+@node Printf Summary, Special File Summary, I/O Summary, Actions Summary
+@appendixsubsubsec @code{printf} Summary
+
+The @code{awk} @code{printf} statement and @code{sprintf} function
+accept the following conversion specification formats:
+
+@table @code
+@item %c
+An ASCII character. If the argument used for @samp{%c} is numeric, it is
+treated as a character and printed. Otherwise, the argument is assumed to
+be a string, and the only first character of that string is printed.
+
+@item %d
+A decimal number (the integer part).
+
+@item %i
+Also a decimal integer.
+
+@item %e
+A floating point number of the form
+@samp{@r{[}-@r{]}d.ddddddE@r{[}+-@r{]}dd}.@refill
+
+@item %f
+A floating point number of the form
+@r{[}@code{-}@r{]}@code{ddd.dddddd}.
+
+@item %g
+Use @samp{%e} or @samp{%f} conversion, whichever is shorter, with
+nonsignificant zeros suppressed.
+
+@item %o
+An unsigned octal number (again, an integer).
+
+@item %s
+A character string.
+
+@item %x
+An unsigned hexadecimal number (an integer).
+
+@item %X
+Like @samp{%x}, except use @samp{A} through @samp{F} instead of @samp{a}
+through @samp{f} for decimal 10 through 15.@refill
+
+@item %%
+A single @samp{%} character; no argument is converted.
+@end table
+
+There are optional, additional parameters that may lie between the @samp{%}
+and the control letter:
+
+@table @code
+@item -
+The expression should be left-justified within its field.
+
+@item @var{width}
+The field should be padded to this width. If @var{width} has a leading zero,
+then the field is padded with zeros. Otherwise it is padded with blanks.
+
+@item .@var{prec}
+A number indicating the maximum width of strings or digits to the right
+of the decimal point.
+@end table
+
+@xref{Printf}, for examples and for a more detailed description.
+
+@node Special File Summary, Numeric Functions Summary, Printf Summary, Actions Summary
+@appendixsubsubsec Special File Names
+
+When doing I/O redirection from either @code{print} or @code{printf} into a
+file, or via @code{getline} from a file, @code{gawk} recognizes certain special
+file names internally. These file names allow access to open file descriptors
+inherited from @code{gawk}'s parent process (usually the shell). The
+file names are:
+
+@table @file
+@item /dev/stdin
+The standard input.
+
+@item /dev/stdout
+The standard output.
+
+@item /dev/stderr
+The standard error output.
+
+@item /dev/fd/@var{n}
+The file denoted by the open file descriptor @var{n}.
+@end table
+
+@noindent
+These file names may also be used on the command line to name data files.
+
+@xref{Special Files}, for a longer description that provides the motivation
+for this feature.
+
+@node Numeric Functions Summary, String Functions Summary, Special File Summary, Actions Summary
+@appendixsubsubsec Numeric Functions
+
+@code{awk} has the following predefined arithmetic functions:
+
+@table @code
+@item atan2(@var{y}, @var{x})
+returns the arctangent of @var{y/x} in radians.
+
+@item cos(@var{expr})
+returns the cosine in radians.
+
+@item exp(@var{expr})
+the exponential function.
+
+@item int(@var{expr})
+truncates to integer.
+
+@item log(@var{expr})
+the natural logarithm function.
+
+@item rand()
+returns a random number between 0 and 1.
+
+@item sin(@var{expr})
+returns the sine in radians.
+
+@item sqrt(@var{expr})
+the square root function.
+
+@item srand(@var{expr})
+use @var{expr} as a new seed for the random number generator. If no @var{expr}
+is provided, the time of day is used. The return value is the previous
+seed for the random number generator.
+@end table
+
+@node String Functions Summary, String Constants Summary, Numeric Functions Summary, Actions Summary
+@appendixsubsubsec String Functions
+
+@code{awk} has the following predefined string functions:
+
+@table @code
+@item gsub(@var{r}, @var{s}, @var{t})
+for each substring matching the regular expression @var{r} in the string
+@var{t}, substitute the string @var{s}, and return the number of substitutions.
+If @var{t} is not supplied, use @code{$0}.
+
+@item index(@var{s}, @var{t})
+returns the index of the string @var{t} in the string @var{s}, or 0 if
+@var{t} is not present.
+
+@item length(@var{s})
+returns the length of the string @var{s}.
+
+@item match(@var{s}, @var{r})
+returns the position in @var{s} where the regular expression @var{r}
+occurs, or 0 if @var{r} is not present, and sets the values of @code{RSTART}
+and @code{RLENGTH}.
+
+@item split(@var{s}, @var{a}, @var{r})
+splits the string @var{s} into the array @var{a} on the regular expression
+@var{r}, and returns the number of fields. If @var{r} is omitted, @code{FS}
+is used instead.
+
+@item sprintf(@var{fmt}, @var{expr-list})
+prints @var{expr-list} according to @var{fmt}, and returns the resulting string.
+
+@item sub(@var{r}, @var{s}, @var{t})
+this is just like @code{gsub}, but only the first matching substring is
+replaced.
+
+@item substr(@var{s}, @var{i}, @var{n})
+returns the @var{n}-character substring of @var{s} starting at @var{i}.
+If @var{n} is omitted, the rest of @var{s} is used.
+
+@item tolower(@var{str})
+returns a copy of the string @var{str}, with all the upper-case characters in
+@var{str} translated to their corresponding lower-case counterparts.
+Nonalphabetic characters are left unchanged.
+
+@item toupper(@var{str})
+returns a copy of the string @var{str}, with all the lower-case characters in
+@var{str} translated to their corresponding upper-case counterparts.
+Nonalphabetic characters are left unchanged.
+
+@item system(@var{cmd-line})
+Execute the command @var{cmd-line}, and return the exit status.
+@end table
+
+@xref{Built-in}, for a description of all of @code{awk}'s built-in functions.
+
+@node String Constants Summary, , String Functions Summary, Actions Summary
+@appendixsubsubsec String Constants
+
+String constants in @code{awk} are sequences of characters enclosed
+between double quotes (@code{"}). Within strings, certain @dfn{escape sequences}
+are recognized, as in C. These are:
+
+@table @code
+@item \\
+A literal backslash.
+
+@item \a
+The ``alert'' character; usually the ASCII BEL character.
+
+@item \b
+Backspace.
+
+@item \f
+Formfeed.
+
+@item \n
+Newline.
+
+@item \r
+Carriage return.
+
+@item \t
+Horizontal tab.
+
+@item \v
+Vertical tab.
+
+@item \x@var{hex digits}
+The character represented by the string of hexadecimal digits following
+the @samp{\x}. As in ANSI C, all following hexadecimal digits are
+considered part of the escape sequence. (This feature should tell us
+something about language design by committee.) E.g., @code{"\x1B"} is a
+string containing the ASCII ESC (escape) character.
+
+@item \@var{ddd}
+The character represented by the 1-, 2-, or 3-digit sequence of octal
+digits. Thus, @code{"\033"} is also a string containing the ASCII ESC
+(escape) character.
+
+@item \@var{c}
+The literal character @var{c}.
+@end table
+
+The escape sequences may also be used inside constant regular expressions
+(e.g., the regexp @code{@w{/[@ \t\f\n\r\v]/}} matches whitespace
+characters).@refill
+
+@xref{Constants}.
+
+@node Functions Summary, , Rules Summary, Gawk Summary
+@appendixsec Functions
+
+Functions in @code{awk} are defined as follows:
+
+@example
+function @var{name}(@var{parameter list}) @{ @var{statements} @}
+@end example
+
+Actual parameters supplied in the function call are used to instantiate
+the formal parameters declared in the function. Arrays are passed by
+reference, other variables are passed by value.
+
+If there are fewer arguments passed than there are names in @var{parameter-list},
+the extra names are given the null string as value. Extra names have the
+effect of local variables.
+
+The open-parenthesis in a function call must immediately follow the
+function name, without any intervening white space. This is to avoid a
+syntactic ambiguity with the concatenation operator.
+
+The word @code{func} may be used in place of @code{function}.
+
+@xref{User-defined}, for a more complete description.
+
+@node Sample Program, Notes, Gawk Summary, Top
@appendix Sample Program
The following example is a complete @code{awk} program, which prints
the number of occurrences of each word in its input. It illustrates the
associative nature of @code{awk} arrays by using strings as subscripts. It
-also demonstrates the @code{for @var{x} in @var{array}} construction.
+also demonstrates the @samp{for @var{x} in @var{array}} construction.
Finally, it shows how @code{awk} can be used in conjunction with other
utility programs to do a useful task of some complexity with a minimum of
effort. Some explanations follow the program listing.@refill
@@ -6146,9 +7940,9 @@ END @{
The first thing to notice about this program is that it has two rules. The
first rule, because it has an empty pattern, is executed on every line of
-the input. It uses @code{awk}'s field--accessing mechanism (@pxref{Fields})
-to pick out the individual words from the line, and the special variable
-@code{NF} (@pxref{Special}) to know how many fields are available.
+the input. It uses @code{awk}'s field-accessing mechanism (@pxref{Fields})
+to pick out the individual words from the line, and the built-in variable
+@code{NF} (@pxref{Built-in Variables}) to know how many fields are available.
For each input word, an element of the array @code{freq} is incremented to
reflect that the word has been seen an additional time.@refill
@@ -6169,7 +7963,7 @@ punctuation characters count as part of words.@refill
@item
The @code{awk} language considers upper and lower case characters to be
-distinct. Therefore, @samp{foo} and @samp{Foo} will not be treated by this
+distinct. Therefore, @samp{foo} and @samp{Foo} are not treated by this
program as the same word. This is undesirable since in normal text, words
are capitalized if they begin sentences, and a frequency analyzer should not
be sensitive to that.@refill
@@ -6180,8 +7974,8 @@ interested in which words occur most frequently, or having an alphabetized
table of how frequently each word occurs.@refill
@end itemize
-The way to solve these problems is to use other operating system utilities
-to process the input and output of the @code{awk} script. Suppose the
+The way to solve these problems is to use other system utilities to
+process the input and output of the @code{awk} script. Suppose the
script shown above is saved in the file @file{frequency.awk}. Then the
shell command:@refill
@@ -6214,9 +8008,12 @@ See the general operating system documentation for more information on how
to use the @code{tr} and @code{sort} commands.@refill
@ignore
-@strong{I have some more substantial programs courtesy of Rick Adams
+@strong{ADR: I have some more substantial programs courtesy of Rick Adams
at UUNET. I am planning on incorporating those either in addition to or
instead of this program.}
+
+@strong{I would also like to incorporate the general @code{translate}
+function that I have written.}
@end ignore
@node Notes, Glossary, Sample Program, Top
@@ -6227,97 +8024,91 @@ maintainers of @code{gawk}. Everything in it applies specifically to
@code{gawk}, and not to other implementations.
@menu
-* Extensions:: Things@code{gawk} does that Unix @code{awk} does not.
+* Compatibility Mode:: How to disable certain @code{gawk} extensions.
-* Future Extensions:: Things likely to appear in a future release.
+* Future Extensions:: New features we may implement soon.
-* Improvements:: Suggestions for future improvements.
-
-* Manual Improvements:: Suggestions for improvements to this manual.
+* Improvements:: Suggestions for improvements by volunteers.
@end menu
-@node Extensions, Future Extensions, , Notes
-@appendixsec GNU Extensions to the AWK Language
+@node Compatibility Mode, Future Extensions, Notes, Notes
+@appendixsec Downwards Compatibility and Debugging
-Several new features are in a state of flux. They are described here
-merely to document them somewhat, but they will probably change. We hope
-they will be incorporated into other versions of @code{awk}, too.
+@xref{S5R4/GNU}, for a summary of the GNU extensions to the @code{awk}
+language and program. All of these features can be turned off either by
+compiling @code{gawk} with @samp{-DSTRICT} (not recommended), or by
+invoking @code{gawk} with the @samp{-c} option.@refill
-All of these features can be turned off either by compiling @code{gawk}
-with @samp{-DSTRICT}, or by invoking @code{gawk} as @samp{awk}.
+If @code{gawk} is compiled for debugging with @samp{-DDEBUG}, then there
+are two more options available on the command line.
-@table @asis
-@item The @code{AWKPATH} environment variable
-When opening a file supplied via the @samp{-f} option, if the filename does
-not contain a @samp{/}, @code{gawk} will perform a @dfn{path search}
-for the file, similar to that performed by the shell. @code{gawk} gets
-its search path from the @code{AWKPATH} environment variable. If that
-variable does not exist, it uses the default path
-@code{".:/usr/lib/awk:/usr/local/lib/awk"}.@refill
-
-@item Case Independent Matching
-Two new operators have been introduced, @code{~~}, and @code{!~~}.
-These perform regular expression match and no-match operations that are
-case independent. In other words, @samp{A} and @samp{a} would both
-match @samp{/a/}.
-
-@item The @samp{-i} option
-This option causes the @code{~} and @code{!~} operators to behave
-like the @code{~~} and @code{!~~} operators described above.
-
-@item The @samp{-v} option
-This option prints version information for this particular copy of @code{gawk}.
-This is so you can determine if your copy of @code{gawk} is up to date
-with respect to whatever the Free Software Foundation is currently
-distributing. It may disappear in a future version of @code{gawk}.
+@table @samp
+@item -d
+Print out debugging information during execution.
+
+@item -D
+Print out the parse stack information as the program is being parsed.
@end table
-@node Future Extensions, Improvements, Extensions, Notes
-@appendixsec Extensions Likely To Appear In A Future Release
+Both of these options are intended only for serious @code{gawk} developers,
+and not for the casual user. They probably have not even been compiled into
+your version of @code{gawk}, since they slow down execution.
-Here are some more extensions that indicate the directions we are
-currently considering for @code{gawk}. Like the previous section, this
-section is also subject to change. None of these are implemented yet.
+The code for recognizing special file names such as @file{/dev/stdin}
+can be disabled at compile time with @samp{-DNO_DEV_FD}, or with
+@samp{-DSTRICT}.@refill
-@table @asis
-@item The @code{IGNORECASE} special variable
-If @code{IGNORECASE} is non--zero, then @emph{all} regular expression matching
-will be done in a case--independent fashion. The @samp{-i} option and the
-@code{~~} and @code{!~~} operators will go away, as this mechanism
-generalizes those facilities.
+@node Future Extensions, Improvements, Compatibility Mode, Notes
+@appendixsec Probable Future Extensions
+
+This section briefly lists extensions that indicate the directions we are
+currently considering for @code{gawk}.
-@item More Escape Sequences
-The ANSI C @samp{\a}, and @samp{\x} escape sequences will be recognized.
-Unix @code{awk} does not recognize @samp{\v}, although @code{gawk} does.
+@table @asis
+@item ANSI C compatible @code{printf}
+The @code{printf} and @code{sprintf} functions may be enhanced to be
+fully compatible with the specification for the @code{printf} family
+of functions in ANSI C.@refill
@item @code{RS} as a regexp
-The meaning of @code{RS} will be generalized along the lines of @code{FS}.
+The meaning of @code{RS} may be generalized along the lines of @code{FS}.
+
+@item Control of subprocess environment
+Changes made in @code{gawk} to the array @code{ENVIRON} may be
+propagated to subprocesses run by @code{gawk}.
+
+@item Data bases
+It may be possible to map an NDBM/GDBM file into an @code{awk} array.
-@item Transliteration Functions
-We are planning on adding @code{toupper} and @code{tolower} functions which
-will take string arguments, and return strings where the case of each letter
-has been transformed to upper-- or lower--case respectively.
+@item Single-character fields
+The null string, @code{""}, as a field separator, will cause field
+splitting and the split function to separate individual characters.
+Thus, @code{split(a, "abcd", "")} would yield @code{a[1] == "a"},
+@code{a[2] == "b"}, and so on.
-@item Access To System File Descriptors
-@code{gawk} will recognize the special file names @file{/dev/stdin},
-@file{/dev/stdout}, @file{/dev/stderr}, and @file{/dev/fd/@var{N}} internally.
-These will allow access to inherited file descriptors from within an
-@code{awk} program.@refill
+@item Fixed-length fields and records
+A mechanism may be provided to allow the specification of fixed length
+fields and records.
+
+@item Regexp syntax
+The @code{egrep} syntax for regular expressions, now specified
+with the @samp{-e} option, may become the default, since the
+POSIX standard may specify this.
@c this is @emph{very} long term --- not worth including right now.
@ignore
@item The C Comma Operator
We may add the C comma operator, which takes the form
-@var{expr1}@code{,}@code{expr2}. The first expression is evaluated, and the
+@code{@var{expr1},@var{expr2}}. The first expression is evaluated, and the
result is thrown away. The value of the full expression is the value of
@var{expr2}.@refill
@end ignore
@end table
-@node Improvements, Manual Improvements, Future Extensions, Notes
-@appendixsec Suggestions for Future Improvements
+@node Improvements,, Future Extensions, Notes
+@appendixsec Suggestions for Improvements
-Here are some projects that would--be @code{gawk} hackers might like to take
+Here are some projects that would-be @code{gawk} hackers might like to take
on. They vary in size from a few days to a few weeks of programming,
depending on which one you choose and how fast a programmer you are. Please
send any improvements you write to the maintainers at the GNU
@@ -6325,22 +8116,21 @@ project.@refill
@enumerate
@item
-State machine regexp matcher: At present, @code{gawk} uses the backtracking
-regular expression matcher from the GNU subroutine library. If a regexp is
-really going to be used a lot of times, it is faster to convert it once to a
-description of a finite state machine, then run a routine simulating that
-machine every time you want to match the regexp. You could use
-the matching routines used by GNU @code{egrep}.
+State machine regexp matcher: At present, @code{gawk} uses the
+backtracking regular expression matcher from the GNU subroutine library.
+If a regexp is really going to be used a lot of times, it is faster to
+convert it once to a description of a finite state machine, then run a
+routine simulating that machine every time you want to match the regexp.
+You might be able to use the matching routines used by GNU @code{egrep}.
@item
-Compilation of @code{awk} programs: @code{gawk} uses a @code{Bison}
-(YACC--like) parser to convert the script given it into a syntax tree;
-the syntax tree is then executed by a simple recursive evaluator.
-Both of these steps incur a lot of overhead, since parsing can be slow
-(especially if you also do the previous project and convert regular
-expressions to finite state machines at compile time) and the
-recursive evaluator performs many procedure calls to do even the
-simplest things.@refill
+Compilation of @code{awk} programs: @code{gawk} uses a Bison (YACC-like)
+parser to convert the script given it into a syntax tree; the syntax
+tree is then executed by a simple recursive evaluator. Both of these
+steps incur a lot of overhead, since parsing can be slow (especially if
+you also do the previous project and convert regular expressions to
+finite state machines at compile time) and the recursive evaluator
+performs many procedure calls to do even the simplest things.@refill
It should be possible for @code{gawk} to convert the script's parse tree
into a C program which the user would then compile, using the normal
@@ -6354,138 +8144,145 @@ in GNU Emacs Lisp. The recursive evaluator would then be replaced by
a straight line byte code interpreter that would be intermediate in speed
between running a compiled program and doing what @code{gawk} does
now.@refill
-@end enumerate
-
-@node Manual Improvements, , Improvements, Notes
-@appendixsec Suggestions For Future Improvements of This Manual
-@enumerate
@item
An error message section has not been included in this version of the
manual. Perhaps some nice beta testers will document some of the messages
for the future.
-
-@item
-A summary page has not been included, as the ``man'', or help, page that
-comes with the @code{gawk} code should suffice.
-
-GNU only supports Info, so this manual itself should contain whatever
-forms of information it would be useful to have on an Info summary page.
-
-@item
-A function and variable index has not been included as we are not sure what to
-put in it.
-@c @strong{ADR: I think I can tackle this.}
-
-@item
-A section summarizing the differences between V7 @code{awk} and
-System V Release 4 @code{awk} would be useful for long--time @code{awk}
-hackers.
@end enumerate
@node Glossary, Index , Notes, Top
@appendix Glossary
-@c @strong{Add a cross-reference to most of these entries.}
-
@table @asis
@item Action
A series of @code{awk} statements attached to a rule. If the rule's
pattern matches an input record, the @code{awk} language executes the
-rule's action. Actions are always enclosed in curly braces.@refill
+rule's action. Actions are always enclosed in curly braces.
+@xref{Actions}.@refill
-@item Amazing @code{awk} assembler
+@item Amazing @code{awk} Assembler
Henry Spencer at the University of Toronto wrote a retargetable assembler
completely as @code{awk} scripts. It is thousands of lines long, including
-machine descriptions for several 8--bit microcomputers. It is distributed
+machine descriptions for several 8-bit microcomputers. It is distributed
with @code{gawk} and is a good example of a program that would have been
better written in another language.@refill
@item Assignment
An @code{awk} expression that changes the value of some @code{awk}
variable or data object. An object that you can assign to is called an
-@dfn{lvalue}.@refill
+@dfn{lvalue}. @xref{Assignment Ops}.@refill
+
+@item @code{awk} Language
+The language in which @code{awk} programs are written.
+
+@item @code{awk} Program
+An @code{awk} program consists of a series of @dfn{patterns} and
+@dfn{actions}, collectively known as @dfn{rules}. For each input record
+given to the program, the program's rules are all processed in turn.
+@code{awk} programs may also contain function definitions.@refill
+
+@item @code{awk} Script
+Another name for an @code{awk} program.
-@item Built-in function
-The @code{awk} language provides built--in functions that perform various
+@item Built-in Function
+The @code{awk} language provides built-in functions that perform various
numerical and string computations. Examples are @code{sqrt} (for the
square root of a number) and @code{substr} (for a substring of a
-string).@refill
+string). @xref{Built-in}.@refill
+
+@item Built-in Variable
+The variables @code{ARGC}, @code{ARGV}, @code{ENVIRON}, @code{FILENAME},
+@code{FNR}, @code{FS}, @code{NF}, @code{IGNORECASE}, @code{NR}, @code{OFMT},
+@code{OFS}, @code{ORS}, @code{RLENGTH}, @code{RSTART}, @code{RS}, and
+@code{SUBSEP}, have special meaning to @code{awk}. Changing some of them
+affects @code{awk}'s running environment. @xref{Built-in Variables}.@refill
@item C
-The system programming language that most of GNU is written in. The
-@code{awk} programming language has C--like syntax, and this manual
+The system programming language that most GNU software is written in. The
+@code{awk} programming language has C-like syntax, and this manual
points out similarities between @code{awk} and C when appropriate.@refill
-@item Compound statement
+@item Compound Statement
A series of @code{awk} statements, enclosed in curly braces. Compound
-statements may be nested.@refill
+statements may be nested. @xref{Statements}.@refill
@item Concatenation
Concatenating two strings means sticking them together, one after another,
giving a new string. For example, the string @samp{foo} concatenated with
-the string @samp{bar} gives the string @samp{foobar}.@refill
-
-@item Conditional expression
+the string @samp{bar} gives the string @samp{foobar}.
+@xref{Concatenation}.@refill
+
+@item Conditional Expression
+An expression using the @samp{?:} ternary operator, such as
+@code{@var{expr1} ? @var{expr2} : @var{expr3}}. The expression
+@var{expr1} is evaluated; if the result is true, the value of the whole
+expression is the value of @var{expr2} otherwise the value is
+@var{expr3}. In either case, only one of @var{expr2} and @var{expr3}
+is evaluated. @xref{Conditional Exp}.@refill
+
+@item Constant Regular Expression
+A constant regular expression is a regular expression written within
+slashes, such as @samp{/foo/}. This regular expression is chosen
+when you write the @code{awk} program, and cannot be changed doing
+its execution. @xref{Regexp Usage}.
+
+@item Comparison Expression
A relation that is either true or false, such as @code{(a < b)}.
-Conditional expressions are used in @code{if} and @code{while} statements,
-and in patterns to select which input records to process.@refill
+Comparison expressions are used in @code{if} and @code{while} statements,
+and in patterns to select which input records to process.
+@xref{Comparison Ops}.@refill
-@item Curly braces
+@item Curly Braces
The characters @samp{@{} and @samp{@}}. Curly braces are used in
@code{awk} for delimiting actions, compound statements, and function
bodies.@refill
-@item Data objects
+@item Data Objects
These are numbers and strings of characters. Numbers are converted into
-strings and vice versa, as needed.@refill
+strings and vice versa, as needed. @xref{Conversion}.@refill
+
+@item Dynamic Regular Expression
+A dynamic regular expression is a regular expression written as an
+ordinary expression. It could be a string constant, such as
+@code{"foo"}, but it may also be an expression whose value may vary.
+@xref{Regexp Usage}.
@item Escape Sequences
-A special sequence of characters used for describing non--printable
+A special sequence of characters used for describing nonprinting
characters, such as @samp{\n} for newline, or @samp{\033} for the ASCII
-ESC (escape) character.
+ESC (escape) character. @xref{Constants}.
@item Field
When @code{awk} reads an input record, it splits the record into pieces
separated by whitespace (or by a separator regexp which you can
-change by setting the special variable @code{FS}). Such pieces are
-called fields.@refill
+change by setting the built-in variable @code{FS}). Such pieces are
+called fields. @xref{Records}.@refill
@item Format
Format strings are used to control the appearance of output in the
@code{printf} statement. Also, data conversions from numbers to strings
-are controlled by the format string contained in the special variable
-@code{OFMT}.@refill
+are controlled by the format string contained in the built-in variable
+@code{OFMT}. @xref{Control Letters}; also @pxref{Output Separators}.@refill
@item Function
A specialized group of statements often used to encapsulate general
-or program--specific tasks. @code{awk} has a number of built--in
-functions, and also allows you to define your own.
+or program-specific tasks. @code{awk} has a number of built-in
+functions, and also allows you to define your own. @xref{Built-in};
+also @pxref{User-defined}.
@item @code{gawk}
The GNU implementation of @code{awk}.
-@item @code{awk} language
-The language in which @code{awk} programs are written.
-
-@item @code{awk} program
-An @code{awk} program consists of a series of @dfn{patterns} and
-@dfn{actions}, collectively known as @dfn{rules}. For each input record
-given to the program, the program's rules are all processed in turn.
-@code{awk} programs may also contain function definitions.@refill
-
-@item @code{awk} script
-Another name for an @code{awk} program.
-
-@item Input record
+@item Input Record
A single chunk of data read in by @code{awk}. Usually, an @code{awk} input
-record consists of one line of text.@refill
+record consists of one line of text. @xref{Records}.@refill
@item Keyword
In the @code{awk} language, a keyword is a word that has special
meaning. Keywords are reserved and may not be used as variable names.
-The keywords are:
+The keywords of @code{awk} are:
@code{if},
@code{else},
@code{while},
@@ -6517,12 +8314,12 @@ rules.
A pattern is an arbitrary conditional expression against which input is
tested. If the condition is satisfied, the pattern is said to @dfn{match}
the input record. A typical pattern might compare the input record against
-a regular expression.@refill
+a regular expression. @xref{Patterns}.@refill
@item Range (of input lines)
A sequence of consecutive lines from the input file. A pattern
can specify ranges of input lines for @code{awk} to process, or it can
-specify single lines.@refill
+specify single lines. @xref{Patterns}.@refill
@item Recursion
When a function calls itself, either directly or indirectly.
@@ -6533,9 +8330,9 @@ Redirection means performing input from other than the standard input
stream, or output to other than the standard output stream.
You can redirect the output of the @code{print} and @code{printf} statements
-to a file or a system command, using the @code{>}, @code{>>}, and @code{|}
+to a file or a system command, using the @samp{>}, @samp{>>}, and @samp{|}
operators. You can redirect input to the @code{getline} statement using
-the @code{<} and @code{|} operators.@refill
+the @samp{<} and @samp{|} operators. @xref{Redirection}.@refill
@item Regular Expression
See ``regexp''.
@@ -6545,7 +8342,8 @@ Short for @dfn{regular expression}. A regexp is a pattern that denotes a
set of strings, possibly an infinite set. For example, the regexp
@samp{R.*xp} matches any string starting with the letter @samp{R}
and ending with the letters @samp{xp}. In @code{awk}, regexps are
-used in patterns and in conditional expressions.@refill
+used in patterns and in conditional expressions. Regexps may contain
+escape sequences. @xref{Regexp}.@refill
@item Rule
A segment of an @code{awk} program, that specifies how to process single
@@ -6554,12 +8352,15 @@ input records. A rule consists of a @dfn{pattern} and an @dfn{action}.
satisfies the rule's pattern, @code{awk} executes the rule's action.
Otherwise, the rule does nothing for that input record.@refill
-@item Special Variable
-The variables @code{ARGC}, @code{ARGV}, @code{ENVIRON}, @code{FILENAME},
-@code{FNR}, @code{FS}, @code{NF}, @code{NR}, @code{OFMT}, @code{OFS},
-@code{ORS}, @code{RLENGTH}, @code{RSTART}, @code{RS}, @code{SUBSEP}, have
-special meaning to @code{awk}. Changing some of them affects @code{awk}'s
-running environment.@refill
+@item Side Effect
+A side effect occurs when an expression has an effect aside from merely
+producing a value. Assignment expressions, increment expressions and
+function calls have side effects. @xref{Assignment Ops}.
+
+@item Special File
+A file name interpreted internally by @code{gawk}, instead of being handed
+directly to the underlying operating system. For example, @file{/dev/stdin}.
+@xref{Special Files}.
@item Stream Editor
A program that reads records from an input stream and processes them one
@@ -6570,15 +8371,16 @@ user.@refill
@item String
A datum consisting of a sequence of characters, such as @samp{I am a
-string}. Constant strings are written with double--quotes in the
+string}. Constant strings are written with double-quotes in the
@code{awk} language, and may contain @dfn{escape sequences}.
+@xref{Constants}.
@item Whitespace
A sequence of blank or tab characters occurring inside an input record or a
string.@refill
@end table
-@node Index, , Glossary, Top
+@node Index, , Glossary, Top
@unnumbered Index
@printindex cp