aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorArnold D. Robbins <arnold@skeeve.com>2010-07-15 23:12:49 +0300
committerArnold D. Robbins <arnold@skeeve.com>2010-07-15 23:12:49 +0300
commit3697ec5ca140f686643d204a54181a5ddbf9a799 (patch)
tree592873e8614475012ddd5f4e6d0482acadbfc9e2
parentf3d9dd233ac07f764a554528c85be3768a1d1ddb (diff)
downloadegawk-3697ec5ca140f686643d204a54181a5ddbf9a799.tar.gz
egawk-3697ec5ca140f686643d204a54181a5ddbf9a799.tar.bz2
egawk-3697ec5ca140f686643d204a54181a5ddbf9a799.zip
Moved to gawk 2.11.
-rw-r--r--CHANGES177
-rw-r--r--FUTURES22
-rw-r--r--Makefile250
-rw-r--r--PROBLEMS14
-rw-r--r--README108
-rw-r--r--alloca.c18
-rw-r--r--alloca.s4
-rw-r--r--array.c (renamed from awk8.c)49
-rw-r--r--awk.h504
-rw-r--r--awk.tab.c3050
-rw-r--r--awk.y639
-rw-r--r--awk1.c558
-rw-r--r--awk4.c404
-rw-r--r--awk7.c1123
-rw-r--r--awka.c68
-rw-r--r--builtin.c (renamed from awk3.c)773
-rw-r--r--debug.c (renamed from awk6.c)71
-rw-r--r--eval.c (renamed from awk2.c)840
-rw-r--r--field.c412
-rw-r--r--gawk-info6151
-rw-r--r--gawk-info-11231
-rw-r--r--gawk-info-21265
-rw-r--r--gawk-info-31385
-rw-r--r--gawk-info-41400
-rw-r--r--gawk-info-5960
-rw-r--r--gawk.1234
-rw-r--r--gawk.aux202
-rw-r--r--gawk.cp234
-rw-r--r--gawk.cps253
-rw-r--r--gawk.dvibin320368 -> 0 bytes
-rw-r--r--gawk.fn10
-rw-r--r--gawk.fns13
-rw-r--r--gawk.ky0
-rw-r--r--gawk.kys0
-rw-r--r--gawk.pg0
-rw-r--r--gawk.pgs0
-rw-r--r--gawk.texinfo5962
-rw-r--r--gawk.toc104
-rw-r--r--gawk.tp0
-rw-r--r--gawk.tps0
-rw-r--r--gawk.vr17
-rw-r--r--gawk.vrs21
-rw-r--r--gnu.getopt.c417
-rw-r--r--io.c765
-rw-r--r--main.c548
-rw-r--r--missing.c52
-rw-r--r--missing.d/dup2.c12
-rw-r--r--missing.d/gcvt.c9
-rw-r--r--missing.d/getopt.c (renamed from att.getopt.c)5
-rw-r--r--missing.d/memcmp.c18
-rw-r--r--missing.d/memcpy.c18
-rw-r--r--missing.d/memset.c18
-rw-r--r--missing.d/random.c (renamed from random.c)0
-rw-r--r--missing.d/strcase.c93
-rw-r--r--missing.d/strchr.c35
-rw-r--r--missing.d/strerror.c (renamed from do_free.c)24
-rw-r--r--missing.d/strtod.c117
-rw-r--r--missing.d/tmpnam.c27
-rw-r--r--missing.d/vprintf.c54
-rw-r--r--msg.c (renamed from awk5.c)98
-rw-r--r--node.c (renamed from awk9.c)304
-rw-r--r--patchlevel.h1
-rw-r--r--pc.d/makefile.pc (renamed from makefile.pc)0
-rw-r--r--pc.d/names.lnk (renamed from names.lnk)0
-rw-r--r--pc.d/popen.c90
-rw-r--r--pc.d/popen.h8
-rw-r--r--regex.c28
-rw-r--r--regex.h13
-rw-r--r--support/texindex.c1673
-rw-r--r--support/texinfo.tex2357
-rw-r--r--version.sh (renamed from version.c)20
-rw-r--r--y.tab.c2282
-rw-r--r--y.tab.h47
73 files changed, 14623 insertions, 23036 deletions
diff --git a/CHANGES b/CHANGES
new file mode 100644
index 00000000..1f582bbb
--- /dev/null
+++ b/CHANGES
@@ -0,0 +1,177 @@
+Changes from 2.10beta to 2.11beta
+---------------------------------
+
+This release fixes all reported bugs that we could reproduce. Probably
+some of the changes are not documented here.
+
+The next release will probably not be a beta release!
+
+The most important change is the addition of the -nostalgia option. :-)
+
+The documentation has been improved and brought up-to-date.
+
+There has been a lot of general cleaning up of the code that is not otherwise
+documented here. There has been a movement toward using standard-conforming
+library routines and providing them (in missing.d) for systems lacking them.
+Improved (hopefully) configuration through Makfile modifications and missing.c.
+In particular, straightened out confusion over vprintf #defines, declarations
+etc.
+
+Deleted RCS log comments from source, to reduce source size by about one third.
+Most of them were horribly out-of-date, anyway.
+
+Renamed source files to reflect (for the most part) their contents.
+
+More and improved error messages. Cleanup and fixes to yyerror().
+String constants are not altered in input buffer, so error messages come out
+better. Fixed usage message. Make use of ANSI C strerror() function
+(provided).
+
+Plugged many more memory leaks. The memory consumption is now quite
+reasonable over a wide range of programs.
+
+Uses volatile declaration if STDC > 0 to avoid problems due to longjmp.
+
+New -a and -e options to use awk or egrep style regexps, respectively,
+since POSIX says awk should use egrep regexps. Default is -a.
+
+Added -v option for setting variables before the first file is encountered.
+Version information now uses -V and copyleft uses -C.
+
+Added a patchlevel.h file and its use for -V and -C.
+
+Append_right() optimized for major improvement to programs with a *lot*
+of statements.
+
+Operator precedence has been corrected to match draft Posix.
+
+Tightened up grammar for builtin functions so that only length
+may be called without arguments or parentheses.
+
+/regex/ is now a normal expression that can appear in any expression
+context.
+
+Allow /= to begin a regexp. Allow ..[../..].. in a regexp.
+
+Allow empty compound statements ({}).
+
+Made return and next illegal outside a function and in BEGIN/END respectively.
+
+Division by zero is now illegal and causes a fatal error.
+
+Fixed exponentiation so that x ^ 0 and x ^= 0 both return 1.
+
+Fixed do_sqrt, do_log, and do_exp to do argument/return checking and
+print an error message, per the manual.
+
+Fixed main to catch SIGSEGV to get source and data file line numbers.
+
+Fixed yyerror to print the ^ at the beginning of the bad token, not the end.
+
+Fix to substr() builtin: it was failing if the arguments
+weren't already strings.
+
+Added new node value flag NUMERIC to indicate that a variable is
+purely a number as opposed to type NUM which indicates that
+the node's numeric value is valid. This is set in make_number(),
+tmp_number and r_force_number() when appropriate and used in
+cmp_nodes(). This fixed a bug in comparison of variables that had
+numeric prefixes. The new code uses strtod() and eliminates is_a_number().
+A simple strtod() is provided for systems lacking one. It does no
+overflow checking, so could be improved.
+
+Simplification and efficiency improvement in force_string.
+
+Added performance tweak in r_force_number().
+
+Fixed a bug with nested loops and break/continue in functions.
+
+Fixed inconsistency in handling of empty fields when $0 has to be rebuilt.
+Happens to simplify rebuild_record().
+
+Cleaned up the code associated with opening a pipe for reading. Gawk
+now has its own popen routine (gawk_popen) that allocates an IOBUF
+and keeps track of the pid of the child process. gawk_pclose
+marks the appropriate child as defunct in the right struct redirect.
+
+Cleaned up and fixed close_redir().
+
+Fixed an obscure bug to do with redirection. Intermingled ">" and ">>"
+redirects did not output in a predictable order.
+
+Improved handling of output bufferring: now all print[f]s redirected to a tty
+or pipe are flushed immediately and non-redirected output to a tty is flushed
+before the next input record is read.
+
+Fixed a bug in get_a_record() where bcopy() could have copied over
+a random pointer.
+
+Fixed a bug when RS="" and records separated by multiple blank lines.
+
+Got rid of SLOWIO code which was out-of-date anyway.
+
+Fix in get_field() for case where $0 is changed and then $(n) are
+changed and then $0 is used.
+
+Fixed infinite loop on failure to open file for reading from getline.
+Now handles redirect file open failures properly.
+
+Filenames such as /dev/stdin now allowed on the command line as well as
+in redirects.
+
+Fixed so that gawk '$1' where $1 is a zero tests false.
+
+Fixed parsing so that `RLENGTH -1' parses the same as `RLENGTH - 1',
+for example.
+
+The return from a user-defined function now defaults to the Null node.
+This fixes a core-dump-causing bug when the return value of a function
+is used and that function returns no value.
+
+Now catches floating point exceptions to avoid core dumps.
+
+Bug fix for deleting elements of an array -- under some conditions, it was
+deleting more than one element at a time.
+
+Fix in AWKPATH code for running off the end of the string.
+
+Fixed handling of precision in *printf calls. %0.2d now works properly,
+as does %c. [s]printf now recognizes %i and %X.
+
+Fixed a bug in printing of very large (>240) strings.
+
+Cleaned up erroneous behaviour for RS == "".
+
+Added IGNORECASE support to index().
+
+Simplified and fixed newnode/freenode.
+
+Fixed reference to $(anything) in a BEGIN block.
+
+Eliminated use of USG rand48().
+
+Bug fix in force_string for machines with 16-bit ints.
+
+Replaced use of mktemp() with tmpnam() and provided a partial implementation of
+the latter for systems that don't have it.
+
+Added a portability check for includes in io.c.
+
+Minor portability fix in alloc.c plus addition of xmalloc().
+
+Portability fix: on UMAX4.2, st_blksize is zero for a pipe, thus breaking
+iop_alloc() -- fixed.
+
+Workaround for compiler bug on Sun386i in do_sprintf.
+
+More and improved prototypes in awk.h.
+
+Consolidated C escape parsing code into one place.
+
+strict flag is now turned on only when invoked with compatability option.
+It now applies to fewer things.
+
+Changed cast of f._ptr in vprintf.c from (unsigned char *) to (char *).
+Hopefully this is right for the systems that use this code (I don't).
+
+Support for pipes under MSDOS added.
diff --git a/FUTURES b/FUTURES
new file mode 100644
index 00000000..dd002e53
--- /dev/null
+++ b/FUTURES
@@ -0,0 +1,22 @@
+This file lists future projects and enhancements for gawk.
+
+Synchronize alloca.[cs] and regex.[ch] with the latest versions at GNU.
+(this will likely be done as a patch to 2.11.)
+
+Convert yylex() to allow arbitrary-length program lines.
+
+Allow OFMT to be other than a floating point format.
+
+Make printf fully compatible with the ANSI C spec.
+
+Make it faster and smaller.
+
+Allow RS to be a regexp.
+
+Read in environment only if necessary. (Is this all that big a deal?)
+
+Use faster regex algorithms.
+
+Create a gawk-to-C translator?
+
+Create a gawk compiler?
diff --git a/Makefile b/Makefile
index 900d0ef2..b60e9adc 100644
--- a/Makefile
+++ b/Makefile
@@ -1,7 +1,5 @@
# Makefile for GNU Awk.
#
-# Rewritten by Arnold Robbins, September 1988, March 1989.
-#
# Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
#
# This file is part of GAWK, the GNU implementation of the
@@ -21,91 +19,155 @@
# along with GAWK; see the file COPYING. If not, write to
# the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+# User tunable macros
+
# CFLAGS: options to the C compiler
#
# -O optimize
# -g include dbx/sdb info
-# -gg include gdb debugging info; only for GCC
+# -gg include gdb debugging info; only for GCC (deprecated)
# -pg include new (gmon) profiling info
# -p include old style profiling info (System V)
#
-# -DNOVPRINTF - system has no vprintf and associated routines
-# -DHASDOPRNT - system needs version of vprintf et al. defined in awk5.c
-# and has a BSD compatable doprnt()
-# -DNOMEMCMP - system lacks memcmp()
-# -DUSG - system is generic-ish System V.
+# To port GAWK, examine and adjust the following flags carefully.
+# In addition, you will have to look at alloca below.
+# The intent (eventual) is to not penalize the most-standard-conforming
+# systems with a lot of #define's.
#
-OPTIMIZE=-O
-DEBUG=#-DDEBUG #-DFUNC_TRACE -DMEMDEBUG
-DEBUGGER=#-g
-PROFILE=#-pg
-SYSV=
-BSD=#-DHASDOPRNT
-MEMCMP=#-DNOMEMCMP
-VPRINTF=#-DNOVPRINTF
-
-FLAGS= $(OPTIMIZE) $(SYSV) $(DEBUG) $(BSD) $(MEMCMP) $(VPRINTF)
-CFLAGS= $(FLAGS) $(DEBUGGER) $(PROFILE)
-LDFLAGS= #-Bstatic
-
-SRC = awk1.c awk2.c awk3.c awk4.c awk5.c \
- awk6.c awk7.c awk8.c awk9.c version.c do_free.c awka.c
-
-PCSTUFF= makefile.pc names.lnk random.c
-
-AWKOBJS = awk1.o awk2.o awk3.o awk4.o awk5.o awk6.o awk7.o awk8.o awk9.o \
- version.o awka.o # do_free.o # used for MEMDEBUG
-ALLOBJS = $(AWKOBJS) awk.tab.o
+# -DBCOPY_MISSING - bcopy() et al. are missing; will replace
+# with a #define'd memcpy() et al. -- use at
+# your own risk (should really use a memmove())
+# -DSPRINTF_INT - sprintf() returns int (most USG systems)
+# -DBLKSIZE_MISSING - st_blksize missing from stat() structure
+# (most USG systems)
+# -DBSDSTDIO - has a BSD internally-compatible stdio
+# -DDOPRNT_MISSING - lacks doprnt() routine
+# -DDUP2_MISSING - lacks dup2() system call (S5Rn, n < 4)
+# -DGCVT_MISSING - lacks gcvt() routine
+# -DGETOPT_MISSING - lacks getopt() routine
+# -DMEMCMP_MISSING - lacks memcmp() routine
+# -DMEMCPY_MISSING - lacks memcpy() routine
+# -DMEMSET_MISSING - lacks memset() routine
+# -DRANDOM_MISSING - lacks random() routine
+# -DSTRCASE_MISSING - lacks strcasecmp() routine
+# -DSTRCHR_MISSING - lacks strchr() and strrchr() routines
+# -DSTRERROR_MISSING - lacks (ANSI C) strerror() routine
+# -DSTRTOD_MISSING - lacks strtod() routine
+# -DTMPNAM_MISSING - lacks or deficient tmpnam() routine
+# -DVPRINTF_MISSING - lacks vprintf and associated routines
+
+# Sun running SunOS 4.x
+MISSING = -DSTRERROR_MISSING -DSTRCASE_MISSING
+
+# SGI Personal Iris (Sys V derived)
+# MISSING = -DSPRINTF_INT -DBLKSIZE_MISSING -DSTRERROR_MISSING -DRANDOM_MISSING
+
+# VAX running Ultrix 3.x
+# MISSING = -DSTRERROR_MISSING
+
+# A generic 4.2 BSD machine
+# (eliminate GETOPT_MISSING for 4.3 release)
+# (eliminate STRCASE_MISSING and TMPNAM_MISSING for Tahoe release)
+# MISSING = -DBSDSTDIO -DMEMCMP_MISSING -DMEMCPY_MISSING -DMEMSET_MISSING \
+# -DSTRERROR_MISSING -DSTRTOD_MISSING -DVPRINTF_MISSING \
+# -DSTRCASE_MISSING -DTMPNAM_MISSING \
+# -DGETOPT_MISSING -DSTRCHR_MISSING
+
+# On Amdahl UTS, a SysVr2-derived system
+# MISSING = -DBCOPY_MISSING -DSPRINTF_INT -DRANDOM_MISSING -DSTRERROR_MISSING \
+# -DSTRCASE_MISSING -DDUP2_MISSING # -DBLKSIZE_MISSING ??????
+
+# Comment out the next line if you don't have gcc.
+# Also choose just one of -g and -O.
+CC= gcc
+
+OPTIMIZE= -O
+PROFILE= #-pg
+DEBUG= #-DDEBUG #-DMEMDEBUG #-DFUNC_TRACE #-DMPROF
+DEBUGGER= #-g -Bstatic
+WARN= #-W -Wunused -Wimplicit -Wreturn-type -Wcomment # for gcc only
# Parser to use on grammar -- if you don't have bison use the first one
#PARSER = yacc
PARSER = bison
-# S5OBJS
+# ALLOCA
# Set equal to alloca.o if your system is S5 and you don't have
-# alloca. Uncomment the rule below to actually make alloca.o.
-S5OBJS=
+# alloca. Uncomment one of the rules below to make alloca.o from
+# either alloca.s or alloca.c.
+ALLOCA= #alloca.o
+
+#
+# With the exception of the alloca rule referred to above, you shouldn't
+# need to customize this file below this point.
+#
+
+FLAGS= $(MISSING) $(DEBUG)
+CFLAGS= $(FLAGS) $(DEBUGGER) $(PROFILE) $(OPTIMIZE) $(WARN)
+
+# object files
+AWKOBJS = main.o eval.o builtin.o msg.o debug.o io.o field.o array.o node.o \
+ version.o missing.o
+
+ALLOBJS = $(AWKOBJS) awk.tab.o
+
+# GNUOBJS
+# GNU stuff that gawk uses as library routines.
+GNUOBJS= regex.o $(ALLOCA)
+
+# source and documentation files
+SRC = main.c eval.c builtin.c msg.c \
+ debug.c io.c field.c array.c node.c missing.c
+
+ALLSRC= $(SRC) awk.tab.c
+
+AWKSRC= awk.h awk.y $(ALLSRC) version.sh patchlevel.h
-# GETOPT
-# Set equal to getopt.o if you have a generic BSD system. The
-# generic BSD getopt is reported to not work with gawk. The
-# gnu getopt is supplied in gnu.getopt.c. The Public Domain
-# getopt from AT&T is in att.getopt.c. Choose one of these,
-# and rename it getopt.c.
-GETOPT=
+GNUSRC = alloca.c alloca.s regex.c regex.h
-# LIBOBJS
-# Stuff that awk uses as library routines, but not in /lib/libc.a.
-LIBOBJS= regex.o $(S5OBJS) $(GETOPT)
+COPIES = missing.d/dup2.c missing.d/gcvt.c missing.d/getopt.c \
+ missing.d/memcmp.c missing.d/memcpy.c missing.d/memset.c \
+ missing.d/random.c missing.d/strcase.c missing.d/strchr.c \
+ missing.d/strerror.c missing.d/strtod.c missing.d/tmpnam.c \
+ missing.d/vprintf.c
-UPDATES = Makefile awk.h awk.y \
- $(SRC) regex.c regex.h
+SUPPORT = support/texindex.c support/texinfo.tex
+
+DOCS= gawk.1 gawk.texinfo
INFOFILES= gawk-info gawk-info-1 gawk-info-2 gawk-info-3 gawk-info-4 \
- gawk-info-5 gawk.aux gawk.cp gawk.cps gawk.dvi gawk.fn gawk.fns \
- gawk.ky gawk.kys gawk.pg gawk.pgs gawk.texinfo gawk.toc \
- gawk.tp gawk.tps gawk.vr gawk.vrs
+ gawk-info-5 gawk-info-6 gawk.aux gawk.cp gawk.cps gawk.fn \
+ gawk.fns gawk.ky gawk.kys gawk.pg gawk.pgs gawk.toc \
+ gawk.tp gawk.tps gawk.vr gawk.vrs
-# DOCS
-# Documentation for users
-#
-DOCS=gawk.1 $(INFOFILES)
+MISC = CHANGES COPYING FUTURES Makefile PROBLEMS README
+
+PCSTUFF= pc.d/makefile.pc pc.d/names.lnk pc.d/popen.c pc.d/popen.h
+
+ALLDOC= gawk.dvi $(INFOFILES)
-# We don't distribute shar files, but they're useful for mailing.
-SHARS = $(DOCS) COPYING README PROBLEMS $(UPDATES) awk.tab.c \
- alloca.s alloca.c att.getopt.c gnu.getopt.c $(PCSTUFF)
+ALLFILES= $(AWKSRC) $(GNUSRC) $(COPIES) $(MISC) $(DOCS) $(ALLDOC) $(PCSTUFF) $(SUPPORT)
-gawk: $(ALLOBJS) $(LIBOBJS)
- $(CC) -o gawk $(CFLAGS) $(ALLOBJS) $(LIBOBJS) -lm $(LDFLAGS)
+# Release of gawk. There can be no leading or trailing white space here!
+REL=2.11
+
+# rules to build gawk
+gawk: $(ALLOBJS) $(GNUOBJS)
+ $(CC) -o gawk $(CFLAGS) $(ALLOBJS) $(GNUOBJS) -lm
$(AWKOBJS): awk.h
+main.o: patchlevel.h
+
awk.tab.o: awk.h awk.tab.c
awk.tab.c: awk.y
$(PARSER) -v awk.y
-mv -f y.tab.c awk.tab.c
+version.c: version.sh
+ sh version.sh $(REL) > version.c
+
# Alloca: uncomment this if your system (notably System V boxen)
# does not have alloca in /lib/libc.a
#
@@ -119,40 +181,52 @@ awk.tab.c: awk.y
#
#alloca.o: alloca.c
-lint: $(SRC)
- lint -hcbax $(FLAGS) $(SRC) awk.tab.c
+# auxiliary rules for release maintenance
+lint: $(ALLSRC)
+ lint -hcbax $(FLAGS) $(ALLSRC)
-clean:
- rm -f gawk *.o core awk.output awk.tab.c gmon.out make.out
-
-awk.shar: $(SHARS)
- shar -f awk -c $(SHARS)
-
-awk.tar: $(SHARS)
- tar cvf awk.tar $(SHARS)
-
-updates.tar: $(UPDATES)
- tar cvf gawk.tar $(UPDATES)
-
-awk.tar.Z: awk.tar
- compress < awk.tar > awk.tar.Z
-
-doc: $(DOCS)
- nroff -man $(DOCS) | col > $(DOCS).out
+xref:
+ cxref -c $(FLAGS) $(ALLSRC) | grep -v ' /' >xref
-# This command probably won't be useful to the rest of the world, but makes
-# life much easier for me.
-dist: awk.tar awk.tar.Z
+clean:
+ rm -f gawk *.o core awk.output awk.tab.c gmon.out make.out version.c
+
+clobber: clean
+ rm -f $(ALLDOC) gawk.log
+
+gawk.dvi: gawk.texinfo
+ tex gawk.texinfo ; texindex gawk.??
+ tex gawk.texinfo ; texindex gawk.??
+ tex gawk.texinfo
+
+$(INFOFILES): gawk.texinfo
+ makeinfo gawk.texinfo
+
+srcrelease: $(AWKSRC) $(GNUSRC) $(DOCS) $(MISC) $(COPIES) $(PCSTUFF) $(SUPPORT)
+ -mkdir gawk-$(REL)
+ cp -p $(AWKSRC) $(GNUSRC) $(DOCS) $(MISC) gawk-$(REL)
+ -mkdir gawk-$(REL)/missing.d
+ cp -p $(COPIES) gawk-$(REL)/missing.d
+ -mkdir gawk-$(REL)/pc.d
+ cp -p $(PCSTUFF) gawk-$(REL)/pc.d
+ -mkdir gawk-$(REL)/support
+ cp -p $(SUPPORT) gawk-$(REL)/support
+ tar -cf - gawk-$(REL) | compress > gawk-$(REL).tar.Z
+
+docrelease: $(ALLDOC)
+ -mkdir gawk-$(REL)-doc
+ cp -p $(INFOFILES) gawk.dvi gawk-$(REL)-doc
+ nroff -man gawk.1 > gawk-$(REL)-doc/gawk.1.pr
+ tar -cf - gawk-$(REL)-doc | compress > gawk-doc-$(REL).tar.Z
+
+psrelease: docrelease
+ -mkdir gawk-postscript
+ dvi2ps gawk.dvi > gawk-postscript/gawk.postscript
+ psroff -t -man gawk.1 > gawk-postscript/gawk.1.ps
+ tar -cf - gawk-postscript | compress > gawk.postscript.tar.Z
+
+release: srcrelease docrelease psrelease
+ rm -fr gawk-postscript gawk-$(REL) gawk-$(REL)-doc
diff:
for i in RCS/*; do rcsdiff -c -b $$i > `basename $$i ,v`.diff; done
-
-update: $(UPDATES)
- sendup $?
- touch update
-
-release: $(SHARS)
- -rm -fr gawk-dist
- mkdir gawk-dist
- cp -p $(SHARS) gawk-dist
- tar -cvf - gawk-dist | compress > dist.tar.Z
diff --git a/PROBLEMS b/PROBLEMS
index cc9b9fb4..07efe657 100644
--- a/PROBLEMS
+++ b/PROBLEMS
@@ -1,19 +1,13 @@
-This is a list of known problems in gawk 2.10.
+This is a list of known problems in gawk 2.11.
Hopefully they will all be fixed in the next major release of gawk.
Please keep in mind that this is still beta software and the code
is still undergoing significant evolution.
-1. %g does not truncate non-significant zeros.
- gawk 'BEGIN { printf "%g\n", 1 }' should print "1", not "1.000000".
+1. The debugging code does not print redirection info.
-2. %d doesn't quite work either:
- echo 1 | gawk '{ printf "%0.2d\n", $1 }' should print "01", not "1".
+2. The scanner needs work.
-3. The debugging code does not print redirection info.
-
-4. The scanner needs an overhaul.
-
-5. The source code files could probably stand some reorganization as well.
+3. Gawk's printf doesn't yet match the latest nawk's.
Arnold Robbins
diff --git a/README b/README
index e64107b9..c75c6148 100644
--- a/README
+++ b/README
@@ -1,53 +1,84 @@
README:
-This is GNU Awk 2.10 Beta. It should be upwardly compatible with the
-System V Release 4 awk. (Yes, you read that right.)
+This is GNU Awk 2.11 Beta. It should be upwardly compatible with the
+System V Release 4 awk.
-This represents a major improvement over the previous release. In
-particular, most known bugs have been fixed, and the memory leaks have
-been plugged. However, the code continues to undergo steady evolution.
-Known problems are given in the PROBLEMS file.
+This release is essentially a bug fix release. The files have been
+renamed and code moved around to organize things by function. Gawk should
+also be somewhat faster now. More care has been given towards portability
+across different Unix systems. See the installation instructions, below.
-MS-DOS changes are included, see below for more information.
+Known problems are given in the PROBLEMS file. Work to be done is
+described briefly in the FUTURES file.
-The gawk.1 man page is concise but (to the best of our knowledge) complete.
-Included in this release is gawk.texinfo. It does not document all the new
-features in 2.10 not in 2.02; that will be rectified. For the moment, the man
-page should be considered authoritative when it conflicts with the
-gawk.texinfo file. This is basically the last release for which we will
-be keeping the man page current.
+The gawk.texinfo included in this release has been revised; it should
+be in sync with what the code does. The man page should also be accurate,
+but no promises there.
-CHANGES FROM 2.02
+CHANGES FROM 2.10
User visible changes:
- Gawk now accepts the ANSI \a and \x escapes.
- You may now use /dev/std{in,out,err} and /dev/fd/N to refer
- by name to the respective inherited open file descriptors.
- There are new tolower() and toupper() functions.
- The -i option and ~~ and !~~ are gone.
- A new variable, IGNORECASE, if non-zero causes *all* regular
- expression operations to be case-insensitive.
- A -V option to print the GNU short Copyleft info.
+ Compatibility mode is now obtained via new -c option.
+ The new ANSI \a and \x escapes are now a standard part of gawk
+ as Unix nawk has picked them up.
+ The new tolower() and toupper() functions are also standard.
+ A new undocumented option, -nostalgia, has been added.
+ Command line options have changed somewhat from 2.10.
+ -v is now -V
+ -V is now -C
+ new -v for doing variable assignments before the BEGIN block.
+ new -c for compatibility mode.
+ new -a for awk style regexps (default)
+ new -e for egrep style regexps, per the POSIX draft spec.
+ Some more formats have been added to printf, ala nawk and ANSI C.
Other changes (the hard stuff):
- Almost all known bugs fixed.
- Memory leaks plugged.
- Lots of changes to improve performance.
- Everything is now under the new General Public License.
+ All known bugs fixed.
+ Still more memory leaks plugged.
+ Lots of changes to improve performance and portability.
+
+PC users take note! PC support is not provided in this release as we
+ could not get anyone to do it; the person who did it for 2.10 lost
+ his network connectivity. It may be provided later either by
+ us or by him. The stuff in pc.d is from 2.10; anyone who cares
+ to make it work for 2.11 under MS-DOS is welcome to do so and
+ to feed the changes back to us.
INSTALLATION:
The Makefile will need some tailoring. Currently it is set up for
-a Sun running SunOS 4.x. The changes to make in the Makefile are
-commented and should be obvious.
+a Sun running SunOS 4.x and gcc. The changes to make in the Makefile are
+commented and should be obvious. Starting with 2.11, our intent has been
+to make the code conform to standards (ANSI, POSIX, SVID, in that order)
+whenever possible, and to not penalize standard conforming systems.
+We have included substitute versions of routines not universally available.
+Simply add the appropriate define for the missing feature(s) on your system.
+
+If you have 4.2 or 4.3 BSD, you should add -DTMPNAM_MISSING since the
+version of tmpnam on these systems won't accept a NULL pointer.
+This does not apply to 4.3-tahoe or the S5R[23] systems I have access to.
+You need this if gawk core dumps on something simple like 'BEGIN {print "hi"}'.
If you have neither bison nor yacc, use the awk.tab.c file here. It was
generated with bison, and should have no AT&T code in it. (Note that
modifying awk.y without bison or yacc will be difficult, at best. You might
want to get a copy of bison from the FSF too.)
-If you have an MS-DOS system, use makefile.pc, and choose one of att.getopt.c
-or gnu.getopt.c.
+If you have an MS-DOS system, use the stuff in pc.d.
+(But see the note above.)
+
+PRINTING THE MANUAL
+
+The 'support' directory contains texinfo.tex 2.1, which will be necessary
+for printing the manual, and the texindex.c program from the emacs distribution
+which is also necessary. See the makefile for the steps needed to get a
+DVI file from the manual.
+
+CAVEATS
+
+The existence of a patchlevel.h file does *N*O*T* imply a commitment on
+our part to issue bug fixes or patches. It is there in case we should
+decide to do so.
BUG REPORTS AND FIXES:
@@ -58,16 +89,15 @@ Department of Mathematics, Statistics and Computing Science,
Dalhousie University, Halifax, Nova Scotia, Canada
UUCP {uunet utai watmath}!dalcs!david
-CDN david@cs.dal.cdn
-INTERNET david%dalcs@uunet.UU.NET
+INTERNET david@cs.dal.ca
Arnold Robbins
Emory University Computing Center
Emory University, Atlanta, GA, 30322, USA
-DOMAIN: arnold@emoryu1.cc.emory.edu
-UUCP: { gatech, mtxinu }!emoryu1!arnold
-BITNET: arnold@emoryu1
+INTERNET: arnold@emoryu1.cc.emory.edu
+UUCP: { gatech, mtxinu }!emoryu1!arnold
+BITNET: arnold@emoryu1
If you can't contact either of us, try Jay Fenlason, hack@prep.ai.mit.edu
AKA mit-eddie!prep!hack. During odd hours he can sometimes be reached at
@@ -77,8 +107,10 @@ never heard of him. (Direct them to the microvax about 10 feet to their left.)
MS-DOS SUPPORT
+(This section is now outdated, see above.)
+
Support for MSC 5.1 was supplied by Conrad Kwok and Scott Garfinkle.
Scott is the contact person if you have problems with the MS-DOS version,
-smsdpg!seg@uunet.uu.net. Of course, if it's a generic bug, we want to
-hear about it too, but if it isn't reproducible under Unix, we won't
-be as interested.
+uunet!cos!stubby!seg. (NOTE! This is a new address.) Of course, if it's
+a generic bug, we want to hear about it too, but if it isn't reproducible
+under Unix, we won't be as interested.
diff --git a/alloca.c b/alloca.c
index cfe98f92..d825b4b6 100644
--- a/alloca.c
+++ b/alloca.c
@@ -42,8 +42,8 @@ you
lose
-- must know STACK_DIRECTION at compile-time
#endif /* STACK_DIRECTION undefined */
-#endif static
-#endif emacs
+#endif /* static */
+#endif /* emacs */
#ifdef X3J11
typedef void *pointer; /* generic pointer type */
@@ -189,3 +189,17 @@ alloca (size) /* returns pointer to storage */
}
}
+pointer xmalloc(n)
+unsigned int n;
+{
+ extern pointer malloc();
+ pointer cp;
+ static char mesg[] = "xmalloc: no memory!\n";
+
+ cp = malloc(n);
+ if (! cp) {
+ write (2, mesg, sizeof(mesg) - 1);
+ exit(1);
+ }
+ return cp;
+}
diff --git a/alloca.s b/alloca.s
index 021badbb..808b021e 100644
--- a/alloca.s
+++ b/alloca.s
@@ -233,7 +233,7 @@ alloca:
jump REGISTER(r1) /* funky return */
#endif /* ns16000 */
-#ifdef pyramid
+#ifdef pyr
.globl _alloca
@@ -254,7 +254,7 @@ __longjmp: jump _longjmp
__setjmp: jump _setjmp
#endif
-#endif /* pyramid */
+#endif /* pyr */
#ifdef ATT3B5
diff --git a/awk8.c b/array.c
index d181f06c..9bab82d6 100644
--- a/awk8.c
+++ b/array.c
@@ -1,21 +1,5 @@
/*
- * awk8.c -- routines for associative arrays.
- */
-
-/*
- * $Log: awk8.c,v $
- * Revision 1.9 89/03/31 13:20:20 david
- * GNU license; comment
- *
- * Revision 1.8 89/03/29 14:11:37 david
- * delinting
- *
- * Revision 1.7 89/03/24 15:59:22 david
- * AHASH becomes NODE
- *
- * Revision 1.6 89/03/21 10:44:17 david
- * minor cleanup
- *
+ * array.c - routines for associative arrays.
*/
/*
@@ -55,8 +39,10 @@ concat_exp(tree)
NODE *tree;
{
NODE *r;
+ char *str;
char *s;
unsigned len;
+ int offset;
int subseplen;
char *subsep;
@@ -67,23 +53,32 @@ NODE *tree;
return r;
subseplen = SUBSEP_node->lnode->stlen;
subsep = SUBSEP_node->lnode->stptr;
- len = r->stlen + subseplen;
- emalloc(s, char *, len + 1, "concat_exp");
- (void) strcpy(s, r->stptr);
+ len = r->stlen + subseplen + 1;
+ emalloc(str, char *, len, "concat_exp");
+ s = str;
+ memcpy(str, r->stptr, r->stlen+1);
+ s = str + r->stlen;
free_temp(r);
tree = tree->rnode;
while (tree) {
- (void) strcat(s, subsep);
+ if (subseplen == 1)
+ *s++ = *subsep;
+ else {
+ memcpy(s, subsep, subseplen+1);
+ s += subseplen;
+ }
r = force_string(tree_eval(tree->lnode));
len += r->stlen + subseplen;
- erealloc(s, char *, len + 1, "concat_exp");
- (void) strcat(s, r->stptr);
+ offset = s - str;
+ erealloc(str, char *, len, "concat_exp");
+ s = str + offset;
+ memcpy(s, r->stptr, r->stlen+1);
+ s += r->stlen;
free_temp(r);
tree = tree->rnode;
}
- len -= subseplen;
- r = tmp_string(s, (int) len);
- free(s);
+ r = tmp_string(str, s - str);
+ free(str);
return r;
}
@@ -231,7 +226,7 @@ NODE *symbol, *tree;
if (last)
last->ahnext = bucket->ahnext;
else
- symbol->var_array[hash1] = NULL;
+ symbol->var_array[hash1] = bucket->ahnext;
deref = bucket->ahname;
do_deref();
deref = bucket->ahvalue;
diff --git a/awk.h b/awk.h
index 22807390..ef4f9091 100644
--- a/awk.h
+++ b/awk.h
@@ -1,167 +1,26 @@
/*
* awk.h -- Definitions for gawk.
- *
- * Copyright (C) 1986 Free Software Foundation Written by Paul Rubin, August
- * 1986
- *
- * $Log: awk.h,v $
- * Revision 1.38 89/03/31 13:15:47 david
- * MSDOS support and more function prototypes
- *
- * Revision 1.37 89/03/30 10:18:22 david
- * fixed up #if around vfprintf define
- *
- * Revision 1.36 89/03/29 14:18:19 david
- * delinting
- * move struct redirect and IOBUF here
- * fix WHOLELINE
- *
- * Revision 1.35 89/03/24 15:56:35 david
- * merge HASHNODE and AHASH into NODE
- *
- * Revision 1.34 89/03/22 21:01:54 david
- * support for new newnode(); delete obsolete member in struct search
- *
- * Revision 1.33 89/03/21 19:25:06 david
- * bring some prototypes up to date
- *
- * Revision 1.32 89/03/21 11:10:44 david
- * major cleanup
- * rearrange NODE structure for space efficiency
- * add MEMDEBUG stuff for finding memory leaks
- * add STREQN define
- *
- * Revision 1.31 89/03/15 21:53:55 david
- * changes from Arnold: case-insensitive matching, BELL, delete obstack, cleanup
- *
- * Revision 1.30 89/03/15 21:28:32 david
- * add free_result to free return from tree_eval
- *
- * Revision 1.29 88/12/15 12:52:10 david
- * casetable made static elsewhere
- *
- * Revision 1.28 88/12/14 10:50:21 david
- * change FREE_TEMP macro to free_temp
- *
- * Revision 1.27 88/12/13 22:20:09 david
- * macro-front-end tree_eval, force_string and force_number
- *
- * Revision 1.25 88/12/08 15:57:11 david
- * added some #ifdef'd out debugging code
- *
- * Revision 1.24 88/12/07 19:58:37 david
- * changes for printing current source file in error messages
- *
- * Revision 1.23 88/12/01 15:07:10 david
- * changes to accomodate source line numbers in error messages
- *
- * Revision 1.22 88/11/30 15:14:59 david
- * FREE_ONE_REFERENCE macro merged inot do_deref()
- *
- * Revision 1.21 88/11/29 15:17:01 david
- * minor movement
- *
- * Revision 1.20 88/11/23 21:36:00 david
- * Arnold: portability addition
- *
- * Revision 1.19 88/11/22 15:51:23 david
- * changed order of elements in NODE decl. for better packing on sparc and
- * similar machines
- *
- * Revision 1.18 88/11/22 13:45:15 david
- * Arnold: changes for case-insensitive matching
- *
- * Revision 1.17 88/11/15 10:15:28 david
- * Arnold: move a bunch of #include's here
- *
- * Revision 1.16 88/11/14 21:50:26 david
- * Arnold: get sprintf() declaration right; correct STREQ macro
- *
- * Revision 1.15 88/11/14 21:24:50 david
- * added extern decl. for field_num
- *
- * Revision 1.14 88/11/03 15:21:03 david
- * extended flags defines; made force_number safe; added TEMP_FREE define
- *
- * Revision 1.13 88/11/01 12:52:18 david
- * allowed for vprintf code in awk5.c
- *
- * Revision 1.12 88/11/01 12:07:27 david
- * cleanup; additions of external declarations; added variable name to node;
- * moved flags from sub.val to node proper
- *
- * Revision 1.11 88/10/19 21:54:29 david
- * safe_malloc to be used by obstack_alloc
- * Node_val to replace other value types (to be done)
- * emalloc and erealloc macros
- *
- * Revision 1.10 88/10/17 19:52:50 david
- * Arnold: fix cant_happen(); improve VPRINTF; purge FAST
- *
- * Revision 1.9 88/10/13 22:02:47 david
- * added some external declarations to make life easier
- * #define VPRINTF for portable variable arg list handling
- *
- * Revision 1.8 88/10/11 22:19:05 david
- * added external decl.
- *
- * Revision 1.7 88/06/05 22:15:40 david
- * deleted level member from hashnode structure
- *
- * Revision 1.6 88/06/05 22:05:25 david
- * added cnt member to NODE structure (doesn't add to size, since val member
- * dominates)
- *
- * Revision 1.5 88/05/31 09:29:14 david
- * expunge Node_local_var
+ */
+
+/*
+ * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
*
- * Revision 1.4 88/05/27 11:04:07 david
- * changed AWKNUM to double to correspond to nawk
+ * This file is part of GAWK, the GNU implementation of the
+ * AWK Progamming Language.
*
- * Revision 1.3 88/05/13 22:07:56 david
- * moved some defines here from elsewhere
+ * GAWK is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 1, or (at your option)
+ * any later version.
*
- * Revision 1.2 88/05/04 12:17:04 david
- * make_for_loop() now returns a NODE *
+ * GAWK is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
*
- * Revision 1.1 88/04/08 15:15:25 david
- * Initial revision
- * Revision 1.6 88/04/08 14:48:25 david changes from Arnold
- * Robbins
- *
- * Revision 1.5 88/03/23 22:17:23 david mostly delinting -- a couple of bug
- * fixes
- *
- * Revision 1.4 88/03/18 21:00:05 david Baseline -- hoefully all the
- * functionality of the new awk added. Just debugging and tuning to do.
- *
- * Revision 1.3 87/11/19 14:34:12 david added a bunch of new Node types added
- * a new union entry to the expnode structure to accomodate function
- * parameter names added a level variable to the symbol structure to keep
- * track of function nesting level
- *
- * Revision 1.2 87/10/29 21:48:32 david added Node_in_array NODETYPE
- *
- * Revision 1.1 87/10/27 15:23:07 david Initial revision
- *
- */
-
-/*
- * GAWK is distributed in the hope that it will be useful, but WITHOUT ANY
- * WARRANTY. No author or distributor accepts responsibility to anyone for
- * the consequences of using it or for whether it serves any particular
- * purpose or works at all, unless he says so in writing. Refer to the GAWK
- * General Public License for full details.
- *
- * Everyone is granted permission to copy, modify and redistribute GAWK, but
- * only under the conditions described in the GAWK General Public License. A
- * copy of this license is supposed to have been given to you along with GAWK
- * so you can know your rights and responsibilities. It should be in a file
- * named COPYING. Among other things, the copyright notice and this notice
- * must be preserved on all copies.
- *
- * In other words, go ahead and share GAWK, but don't try to stop anyone else
- * from sharing it farther. Help stamp out software hoarding!
+ * You should have received a copy of the GNU General Public License
+ * along with GAWK; see the file COPYING. If not, write to
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* ------------------------------ Includes ------------------------------ */
@@ -183,197 +42,234 @@
extern char *alloca();
#endif
#else
-#ifdef __STDC__
-extern void *alloca();
-#else
extern char *alloca();
#endif
-#endif
-#if defined(USG) || defined(MSDOS)
+#ifdef SPRINTF_INT
extern int sprintf();
-#define index strchr
-#define rindex strrchr
-#define bcmp memcmp
-#define bcopy(s,d,l) memcpy((d),(s),(l))
-#define bzero(p,l) memset((p),0,(l))
-/* nasty nasty berkelixm */
-#define _setjmp setjmp
-#define _longjmp longjmp
#else /* not USG */
+/* nasty nasty berkelixm */
+#define setjmp _setjmp
+#define longjmp _longjmp
+
extern char *sprintf();
#endif
/*
* if you don't have vprintf, but you are BSD, the version defined in
- * awk5.c should do the trick. Otherwise, use this and cross your fingers.
+ * vprintf.c should do the trick. Otherwise, use this and cross your fingers.
*/
-#if defined(NOVPRINTF) && defined(HASDOPRNT)
+#if defined(VPRINTF_MISSING) && !defined(DOPRNT_MISSING) && !defined(BSDSTDIO)
#define vfprintf(fp,fmt,arg) _doprnt((fmt), (arg), (fp))
#endif
#ifdef __STDC__
-extern char *malloc(unsigned), *realloc(char *, unsigned);
+extern void *malloc(unsigned), *realloc(void *, unsigned);
extern void free(char *);
extern char *getenv(char *);
extern char *strcpy(char *, char *), *strcat(char *, char *), *strncpy(char *, char *, int);
-extern char *index(char *, int);
+extern int strcmp(char *, char *);
+extern int strncmp(char *, char *, int);
+extern int strncasecmp(char *, char *, int);
+extern char *strerror(int);
+extern char *strchr(char *, int);
+extern int strlen(char *);
+extern char *memcpy(char *, char *, int);
+extern int memcmp(char *, char *, int);
+extern char *memset(char *, int, int);
+
+/* extern int fprintf(FILE *, char *, ...); */
+extern int fprintf();
+extern int vfprintf();
+extern int fwrite(char *, int, int, FILE *);
+extern int fflush(FILE *);
+extern int fclose(FILE *);
+extern int pclose(FILE *);
+extern int fputs(char *, FILE *);
+extern void abort();
+extern int isatty(int);
+extern void exit(int);
+extern int system(char *);
+extern int sscanf(/* char *, char *, ... */);
extern double atof(char *);
+extern int fstat(int, struct stat *);
+extern off_t lseek(int, off_t, int);
+extern int fseek(FILE *, long, int);
+extern int close(int);
+extern int open();
+extern int pipe(int *);
+extern int dup2(int, int);
+extern int unlink(char *);
+extern int fork();
+extern int execl(/* char *, char *, ... */);
+extern int read(int, char *, int);
+extern int wait(int *);
+extern void _exit(int);
#else
+extern void _exit();
+extern int wait();
+extern int read();
+extern int execl();
+extern int fork();
+extern int unlink();
+extern int dup2();
+extern int pipe();
+extern int open();
+extern int close();
+extern int fseek();
+extern off_t lseek();
+extern int fstat();
+extern void exit();
+extern int system();
+extern int isatty();
+extern void abort();
+extern int fputs();
+extern int fclose();
+extern int pclose();
+extern int fflush();
+extern int fwrite();
+extern int fprintf();
+extern int vfprintf();
+extern int sscanf();
extern char *malloc(), *realloc();
extern void free();
extern char *getenv();
+extern int strcmp();
+extern int strncmp();
+extern int strncasecmp();
+extern int strlen();
extern char *strcpy(), *strcat(), *strncpy();
-extern char *index();
+extern char *memset();
+extern int memcmp();
+extern char *memcpy();
+extern char *strerror();
+extern char *strchr();
extern double atof();
#endif
extern int errno;
-extern char *sys_errlist[];
/* ------------------ Constants, Structures, Typedefs ------------------ */
#define AWKNUM double
typedef enum {
/* illegal entry == 0 */
- Node_illegal, /* 0 */
+ Node_illegal,
/* binary operators lnode and rnode are the expressions to work on */
- Node_times, /* 1 */
- Node_quotient, /* 2 */
- Node_mod, /* 3 */
- Node_plus, /* 4 */
- Node_minus, /* 5 */
- Node_cond_pair, /* 6: conditional pair (see Node_line_range) */
- Node_subscript, /* 7 */
- Node_concat, /* 8 */
+ Node_times,
+ Node_quotient,
+ Node_mod,
+ Node_plus,
+ Node_minus,
+ Node_cond_pair, /* conditional pair (see Node_line_range) */
+ Node_subscript,
+ Node_concat,
+ Node_exp,
/* unary operators subnode is the expression to work on */
- Node_preincrement, /* 9 */
- Node_predecrement, /* 10 */
- Node_postincrement, /* 11 */
- Node_postdecrement, /* 12 */
- Node_unary_minus, /* 13 */
- Node_field_spec, /* 14 */
+/*10*/ Node_preincrement,
+ Node_predecrement,
+ Node_postincrement,
+ Node_postdecrement,
+ Node_unary_minus,
+ Node_field_spec,
/* assignments lnode is the var to assign to, rnode is the exp */
- Node_assign, /* 15 */
- Node_assign_times, /* 16 */
- Node_assign_quotient, /* 17 */
- Node_assign_mod, /* 18 */
- Node_assign_plus, /* 19 */
- Node_assign_minus, /* 20 */
+ Node_assign,
+ Node_assign_times,
+ Node_assign_quotient,
+ Node_assign_mod,
+/*20*/ Node_assign_plus,
+ Node_assign_minus,
+ Node_assign_exp,
/* boolean binaries lnode and rnode are expressions */
- Node_and, /* 21 */
- Node_or, /* 22 */
+ Node_and,
+ Node_or,
/* binary relationals compares lnode and rnode */
- Node_equal, /* 23 */
- Node_notequal, /* 24 */
- Node_less, /* 25 */
- Node_greater, /* 26 */
- Node_leq, /* 27 */
- Node_geq, /* 28 */
+ Node_equal,
+ Node_notequal,
+ Node_less,
+ Node_greater,
+ Node_leq,
+/*30*/ Node_geq,
+ Node_match,
+ Node_nomatch,
/* unary relationals works on subnode */
- Node_not, /* 29 */
-
- /* match ops (binary) work on lnode and rnode ??? */
- Node_match, /* 30 */
- Node_nomatch, /* 31 */
-
- /* data items */
- Node_string, /* deprecated: 32 has stlen, stptr, and stref */
- Node_temp_string, /* deprecated: 33 has stlen, stptr, and stref */
- Node_number, /* deprecated: 34 has numbr */
+ Node_not,
/* program structures */
- Node_rule_list, /* 35 lnode is a rule, rnode is rest of list */
- Node_rule_node, /* 36 lnode is an conditional, rnode is
- * statement */
- Node_statement_list, /* 37 lnode is a statement, rnode is more
- * list */
- Node_if_branches, /* 38 lnode is to run on true, rnode on false */
- Node_expression_list, /* 39 lnode is an exp, rnode is more list */
- Node_param_list, /* 40 lnode is a variable, rnode is more list */
+ Node_rule_list, /* lnode is a rule, rnode is rest of list */
+ Node_rule_node, /* lnode is pattern, rnode is statement */
+ Node_statement_list, /* lnode is statement, rnode is more list */
+ Node_if_branches, /* lnode is to run on true, rnode on false */
+ Node_expression_list, /* lnode is an exp, rnode is more list */
+ Node_param_list, /* lnode is a variable, rnode is more list */
/* keywords */
- Node_K_BEGIN, /* 41 no stuff */
- Node_K_END, /* 42 ditto */
- Node_K_if, /* 43 lnode is conditonal, rnode is
- * if_branches */
- Node_K_while, /* 44 lnode is condtional, rnode is stuff to
- * run */
- Node_K_for, /* 45 lnode is for_struct, rnode is stuff to
- * run */
- Node_K_arrayfor, /* 46 lnode is for_struct, rnode is stuff to
- * run */
- Node_K_break, /* 47 no subs */
- Node_K_continue, /* 48 no stuff */
- Node_K_print, /* 49 lnode is exp_list, rnode is redirect */
- Node_K_printf, /* 50 lnode is exp_list, rnode is redirect */
- Node_K_next, /* 51 no subs */
- Node_K_exit, /* 52 subnode is return value, or NULL */
- Node_K_do, /* 53 lnode is conditional, rnode is stuff to
- * run */
- Node_K_return, /* 54 */
- Node_K_delete, /* 55 */
+/*40*/ Node_K_if, /* lnode is conditonal, rnode is if_branches */
+ Node_K_while, /* lnode is condtional, rnode is stuff to run */
+ Node_K_for, /* lnode is for_struct, rnode is stuff to run */
+ Node_K_arrayfor, /* lnode is for_struct, rnode is stuff to run */
+ Node_K_break, /* no subs */
+ Node_K_continue, /* no stuff */
+ Node_K_print, /* lnode is exp_list, rnode is redirect */
+ Node_K_printf, /* lnode is exp_list, rnode is redirect */
+ Node_K_next, /* no subs */
+ Node_K_exit, /* subnode is return value, or NULL */
+ Node_K_do, /* lnode is conditional, rnode stuff to run */
+ Node_K_return,
+ Node_K_delete,
+ Node_K_getline,
+ Node_K_function, /* lnode is statement list, rnode is params */
/* I/O redirection for print statements */
- Node_redirect_output, /* 56 subnode is where to redirect */
- Node_redirect_append, /* 57 subnode is where to redirect */
- Node_redirect_pipe, /* 58 subnode is where to redirect */
- Node_redirect_pipein, /* 59 subnode is where to redirect */
- Node_redirect_input, /* 60 subnode is where to redirect */
+ Node_redirect_output, /* subnode is where to redirect */
+ Node_redirect_append, /* subnode is where to redirect */
+ Node_redirect_pipe, /* subnode is where to redirect */
+ Node_redirect_pipein, /* subnode is where to redirect */
+ Node_redirect_input, /* subnode is where to redirect */
/* Variables */
- Node_var, /* 61 rnode is value, lnode is array stuff */
- Node_var_array, /* 62 array is ptr to elements, asize num of
+ Node_var, /* rnode is value, lnode is array stuff */
+ Node_var_array, /* array is ptr to elements, asize num of
* eles */
+ Node_val, /* node is a value - type in flags */
/* Builtins subnode is explist to work on, proc is func to call */
- Node_builtin, /* 63 */
+ Node_builtin,
/*
* pattern: conditional ',' conditional ; lnode of Node_line_range
* is the two conditionals (Node_cond_pair), other word (rnode place)
* is a flag indicating whether or not this range has been entered.
*/
- Node_line_range, /* 64 */
+ Node_line_range,
/*
* boolean test of membership in array lnode is string-valued
* expression rnode is array name
*/
- Node_in_array, /* 65 */
- Node_K_function, /* 66 lnode is statement list, rnode is
- * func_params */
- Node_func, /* 67 lnode is param. list, rnode is
- * statement list */
- Node_func_call, /* 68 lnode is name, rnode is expression list */
- Node_K_getline, /* 69 */
- Node_sub, /* 70 */
- Node_gsub, /* 71 */
- Node_K_match, /* 72 */
- Node_cond_exp, /* 73 lnode is conditonal, rnode is
- * if_branches */
- Node_exp, /* 74 */
- Node_assign_exp, /* 75 */
- Node_regex, /* 76 */
- Node_str_num, /* deprecated: 77 both string and numeric
- * values are valid
- */
- Node_val, /* 78 node is a value - type given by bits in
- * status - to replace Node_string, Node_num,
- * Node_temp_str and Node_str_num
- */
+ Node_in_array,
+
+ Node_func, /* lnode is param. list, rnode is body */
+ Node_func_call, /* lnode is name, rnode is argument list */
+
+ Node_cond_exp, /* lnode is conditonal, rnode is if_branches */
+ Node_regex,
Node_hashnode,
Node_ahash,
} NODETYPE;
+/*
+ * NOTE - this struct is a rather kludgey -- it is packed to minimize
+ * space usage, at the expense of cleanliness. Alter at own risk.
+ */
typedef struct exp_node {
union {
struct {
@@ -424,19 +320,19 @@ typedef struct exp_node {
} sub;
NODETYPE type;
unsigned char flags;
-# define MEM 0x7
-# define MALLOC 1 /* can be free'd */
-# define TEMP 2 /* should be free'd */
-# define PERM 4 /* can't be free'd */
-# define VAL 0x18
-# define NUM 8
-# define STR 16
+# define MEM 0x7
+# define MALLOC 1 /* can be free'd */
+# define TEMP 2 /* should be free'd */
+# define PERM 4 /* can't be free'd */
+# define VAL 0x18
+# define NUM 8 /* numeric value is valid */
+# define STR 16 /* string value is valid */
+# define NUMERIC 32 /* entire field is numeric */
} NODE;
#define lnode sub.nodep.l.lptr
#define nextp sub.nodep.l.nextnode
#define rnode sub.nodep.r.rptr
-#define varname sub.nodep.name
#define source_file sub.nodep.name
#define source_line sub.nodep.number
#define param_cnt sub.nodep.number
@@ -491,6 +387,8 @@ typedef struct iobuf {
int cnt;
char *secbuf;
int secsiz;
+ int flag;
+# define IOP_IS_TTY 1
} IOBUF;
/*
@@ -503,9 +401,12 @@ struct redirect {
# define RED_READ 4
# define RED_WRITE 8
# define RED_APPEND 16
+# define RED_NOBUF 32
char *value;
FILE *fp;
IOBUF *iop;
+ int pid;
+ int status;
long offset; /* used for dynamic management of open files */
struct redirect *prev;
struct redirect *next;
@@ -543,10 +444,6 @@ extern NODE *expression_value;
extern NODE *variables[];
extern NODE *_t; /* used as temporary in tree_eval */
-extern NODE *_result; /* Ditto */
-
-extern NODE *nextfree;
-extern NODE *lastfree;
extern char *myname;
@@ -557,18 +454,11 @@ extern int strict;
/* ------------------------- Pseudo-functions ------------------------- */
#define is_identchar(c) (isalnum(c) || (c) == '_')
-#define tree_eval(t) (_result = (_t = (t),(_t) == NULL ? Nnull_string : \
- ((_t)->type == Node_val ? (_t) : r_tree_eval((_t)))))
#define free_temp(n) if ((n)->flags&TEMP) { deref = (n); do_deref(); } else
-#define free_result() if (_result) free_temp(_result); else
-
-/*
- * the loop_tag_valid variable allows continue/break-out-of-context to be
- * caught and diagnosed
- */
-#define PUSH_BINDING(stack, x, val) (bcopy ((char *)(x), (char *)(stack), sizeof (jmp_buf)), val++)
-#define RESTORE_BINDING(stack, x, val) (bcopy ((char *)(stack), (char *)(x), sizeof (jmp_buf)), val--)
+#define tree_eval(t) (_t = (t),(_t) == NULL ? Nnull_string : \
+ ((_t)->type == Node_val ? (_t) : r_tree_eval((_t))))
+#define make_string(s,l) make_str_node((s),(l),0)
#define cant_happen() fatal("line %d, file: %s; bailing out", \
__LINE__, __FILE__);
@@ -581,12 +471,12 @@ extern int strict;
#define emalloc(var,ty,x,str) if ((var = (ty) malloc((unsigned)(x))) == NULL)\
fatal("%s: %s: can't allocate memory (%s)",\
- (str), "var", sys_errlist[errno]); else\
+ (str), "var", strerror(errno)); else\
memmsg("var", x, str, var)
#define erealloc(var,ty,x,str) if((var=(ty)realloc((char *)var,\
(unsigned)(x)))==NULL)\
fatal("%s: %s: can't allocate memory (%s)",\
- (str), "var", sys_errlist[errno]); else\
+ (str), "var", strerror(errno)); else\
memmsg("re: var", x, str, var)
#ifdef DEBUG
#define force_number r_force_number
@@ -611,6 +501,7 @@ extern double _msc51bug;
/* ------------- Function prototypes or defs (as appropriate) ------------- */
#ifdef __STDC__
+extern int parse_escape(char **);
extern int devopen(char *, char *);
extern struct re_pattern_buffer *make_regexp(NODE *, int);
extern struct re_pattern_buffer *mk_re_parse(char *, int);
@@ -622,12 +513,13 @@ extern int interpret(NODE *);
extern NODE *r_tree_eval(NODE *);
extern void assign_number(NODE **, double);
extern int cmp_nodes(NODE *, NODE *);
-extern char *get_fs(void);
extern struct redirect *redirect(NODE *, int *);
extern int flush_io(void);
extern void print_simple(NODE *, FILE *);
/* extern void warning(char *,...); */
+extern void warning();
/* extern void fatal(char *,...); */
+extern void fatal();
extern void set_record(char *, int);
extern NODE **get_field(int, int);
extern NODE **get_lhs(NODE *, int);
@@ -641,12 +533,15 @@ extern NODE *newnode(NODETYPE);
extern NODE *dupnode(NODE *);
extern NODE *make_number(double);
extern NODE *tmp_number(double);
-extern NODE *make_string(char *, int);
+extern NODE *make_str_node(char *, int, int);
extern NODE *tmp_string(char *, int);
extern char *re_compile_pattern(char *, int, struct re_pattern_buffer *);
extern int re_search(struct re_pattern_buffer *, char *, int, int, int, struct re_registers *);
+extern void freenode(NODE *);
#else
+extern int parse_escape();
+extern void freenode();
extern int devopen();
extern struct re_pattern_buffer *make_regexp();
extern struct re_pattern_buffer *mk_re_parse();
@@ -657,7 +552,6 @@ extern int interpret();
extern NODE *r_tree_eval();
extern void assign_number();
extern int cmp_nodes();
-extern char *get_fs();
extern struct redirect *redirect();
extern int flush_io();
extern void print_simple();
@@ -676,12 +570,16 @@ extern NODE *newnode();
extern NODE *dupnode();
extern NODE *make_number();
extern NODE *tmp_number();
-extern NODE *make_string();
+extern NODE *make_str_node();
extern NODE *tmp_string();
extern char *re_compile_pattern();
extern int re_search();
#endif
+#if !defined(__STDC__) || __STDC__ <= 0
+#define volatile
+#endif
+
/* Figure out what '\a' really is. */
#ifdef __STDC__
#define BELL '\a' /* sure makes life easy, don't it? */
diff --git a/awk.tab.c b/awk.tab.c
deleted file mode 100644
index 02ef8a21..00000000
--- a/awk.tab.c
+++ /dev/null
@@ -1,3050 +0,0 @@
-
-/* A Bison parser, made from awk.y */
-
-#define FUNC_CALL 258
-#define NAME 259
-#define REGEXP 260
-#define YSTRING 261
-#define ERROR 262
-#define INCDEC 263
-#define NUMBER 264
-#define RELOP 265
-#define APPEND_OP 266
-#define ASSIGNOP 267
-#define MATCHOP 268
-#define NEWLINE 269
-#define CONCAT_OP 270
-#define LEX_BEGIN 271
-#define LEX_END 272
-#define LEX_IF 273
-#define LEX_ELSE 274
-#define LEX_RETURN 275
-#define LEX_DELETE 276
-#define LEX_WHILE 277
-#define LEX_DO 278
-#define LEX_FOR 279
-#define LEX_BREAK 280
-#define LEX_CONTINUE 281
-#define LEX_PRINT 282
-#define LEX_PRINTF 283
-#define LEX_NEXT 284
-#define LEX_EXIT 285
-#define LEX_FUNCTION 286
-#define LEX_GETLINE 287
-#define LEX_SUB 288
-#define LEX_MATCH 289
-#define LEX_IN 290
-#define LEX_AND 291
-#define LEX_OR 292
-#define INCREMENT 293
-#define DECREMENT 294
-#define LEX_BUILTIN 295
-#define UNARY 296
-
-#line 197 "awk.y"
-
-#ifdef DEBUG
-#define YYDEBUG 12
-#endif
-#define YYIMPROVE
-
-#include "awk.h"
-
-extern void msg();
-extern struct re_pattern_buffer *mk_re_parse();
-
-NODE *node();
-NODE *lookup();
-NODE *install();
-
-static NODE *snode();
-static NODE *mkrangenode();
-static FILE *pathopen();
-static NODE *make_for_loop();
-static NODE *append_right();
-static void func_install();
-static NODE *make_param();
-static int hashf();
-static void pop_params();
-static void pop_var();
-static int yylex ();
-static void yyerror();
-
-static int want_regexp; /* lexical scanning kludge */
-static int lineno = 1; /* for error msgs */
-static char *lexptr; /* pointer to next char during parsing */
-static char *lexptr_begin; /* keep track of where we were for error msgs */
-static int curinfile = -1; /* index into sourcefiles[] */
-
-NODE *variables[HASHSIZE];
-
-extern int errcount;
-extern NODE *begin_block;
-extern NODE *end_block;
-extern int param_counter;
-
-#line 239 "awk.y"
-typedef union {
- long lval;
- AWKNUM fval;
- NODE *nodeval;
- NODETYPE nodetypeval;
- char *sval;
- NODE *(*ptrval)();
-} YYSTYPE;
-
-#ifndef YYLTYPE
-typedef
- struct yyltype
- {
- int timestamp;
- int first_line;
- int first_column;
- int last_line;
- int last_column;
- char *text;
- }
- yyltype;
-
-#define YYLTYPE yyltype
-#endif
-
-#define YYACCEPT return(0)
-#define YYABORT return(1)
-#define YYERROR goto yyerrlab
-#include <stdio.h>
-
-#ifndef __STDC__
-#define const
-#endif
-
-
-
-#define YYFINAL 312
-#define YYFLAG -32768
-#define YYNTBASE 63
-
-#define YYTRANSLATE(x) ((unsigned)(x) <= 296 ? yytranslate[x] : 103)
-
-static const char yytranslate[] = { 0,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 53, 2, 2, 56, 52, 2, 2, 46,
- 47, 50, 48, 62, 49, 2, 51, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 42, 61, 43,
- 2, 44, 41, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 57, 2, 58, 55, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 59, 45, 60, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 1, 2, 3, 4, 5,
- 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
- 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
- 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
- 36, 37, 38, 39, 40, 54
-};
-
-static const short yyrline[] = { 0,
- 300, 305, 313, 329, 330, 334, 348, 362, 368, 374,
- 376, 378, 380, 389, 391, 396, 400, 407, 413, 415,
- 417, 419, 421, 423, 428, 430, 435, 448, 450, 461,
- 466, 471, 473, 481, 483, 488, 490, 496, 498, 500,
- 502, 504, 506, 511, 515, 520, 523, 526, 528, 530,
- 532, 534, 536, 538, 543, 545, 550, 555, 562, 564,
- 569, 571, 576, 578, 583, 585, 587, 589, 594, 596,
- 601, 603, 605, 607, 609, 615, 617, 622, 624, 629,
- 631, 637, 639, 641, 643, 648, 650, 655, 657, 663,
- 665, 667, 669, 674, 676, 678, 683, 687, 689, 691,
- 693, 695, 697, 699, 701, 703, 705, 707, 712, 714,
- 716, 718, 722, 724, 726, 728, 730, 732, 734, 739,
- 741, 743, 745, 747, 749, 751, 753, 755, 759, 761,
- 763, 765, 767, 769, 771, 775, 777, 779, 781, 783,
- 785, 787, 789, 794, 796, 801, 803, 805, 810, 814,
- 818, 822, 823, 827, 830
-};
-
-static const char * const yytname[] = { 0,
-"error","$illegal.","FUNC_CALL","NAME","REGEXP","YSTRING","ERROR","INCDEC","NUMBER","RELOP",
-"APPEND_OP","ASSIGNOP","MATCHOP","NEWLINE","CONCAT_OP","LEX_BEGIN","LEX_END","LEX_IF","LEX_ELSE","LEX_RETURN",
-"LEX_DELETE","LEX_WHILE","LEX_DO","LEX_FOR","LEX_BREAK","LEX_CONTINUE","LEX_PRINT","LEX_PRINTF","LEX_NEXT","LEX_EXIT",
-"LEX_FUNCTION","LEX_GETLINE","LEX_SUB","LEX_MATCH","LEX_IN","LEX_AND","LEX_OR","INCREMENT","DECREMENT","LEX_BUILTIN",
-"'?'","':'","'<'","'>'","'|'","'('","')'","'+'","'-'","'*'",
-"'/'","'%'","'!'","UNARY","'^'","'$'","'['","']'","'{'","'}'",
-"';'","','","start"
-};
-
-static const short yyr1[] = { 0,
- 63, 64, 64, 64, 64, 65, 65, 65, 65, 65,
- 65, 65, 65, 66, 66, 68, 67, 69, 70, 70,
- 70, 70, 70, 70, 71, 71, 72, 74, 73, 75,
- 75, 76, 76, 76, 76, 77, 77, 78, 78, 78,
- 78, 78, 78, 78, 78, 78, 78, 78, 78, 78,
- 78, 78, 78, 78, 79, 79, 80, 80, 81, 81,
- 82, 82, 83, 83, 84, 84, 84, 84, 85, 85,
- 86, 86, 86, 86, 86, 87, 87, 88, 88, 89,
- 89, 89, 89, 89, 89, 90, 90, 91, 91, 91,
- 91, 91, 91, 92, 92, 92, 92, 92, 92, 92,
- 92, 92, 92, 92, 92, 92, 92, 92, 93, 93,
- 93, 93, 93, 93, 93, 93, 93, 93, 93, 94,
- 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
- 94, 94, 94, 94, 94, 94, 94, 94, 94, 94,
- 94, 94, 94, 95, 95, 96, 96, 96, 97, 98,
- 99, 100, 100, 101, 102
-};
-
-static const short yyr2[] = { 0,
- 2, 1, 2, 1, 2, 2, 2, 2, 2, 2,
- 1, 2, 2, 1, 1, 0, 7, 3, 1, 1,
- 3, 3, 2, 3, 1, 3, 1, 0, 4, 3,
- 4, 1, 2, 1, 2, 1, 2, 2, 3, 1,
- 6, 8, 8, 10, 9, 2, 2, 6, 4, 2,
- 3, 3, 6, 2, 1, 1, 6, 9, 1, 2,
- 0, 1, 0, 2, 0, 2, 2, 2, 0, 1,
- 1, 3, 1, 2, 3, 0, 1, 0, 1, 1,
- 3, 1, 2, 3, 3, 0, 1, 1, 3, 1,
- 2, 3, 3, 3, 5, 4, 3, 3, 3, 3,
- 3, 3, 3, 3, 3, 5, 2, 1, 3, 3,
- 3, 3, 3, 3, 3, 3, 5, 2, 1, 2,
- 3, 4, 1, 6, 6, 6, 6, 4, 2, 2,
- 2, 2, 1, 1, 1, 3, 3, 3, 3, 3,
- 3, 2, 2, 0, 1, 1, 4, 2, 2, 2,
- 1, 0, 1, 1, 2
-};
-
-static const short yydefact[] = { 61,
- 59, 62, 0, 60, 4, 0, 146, 135, 134, 0,
- 0, 16, 144, 0, 0, 0, 0, 123, 0, 0,
- 0, 28, 0, 0, 61, 0, 2, 0, 25, 0,
- 20, 27, 11, 19, 108, 133, 0, 0, 0, 154,
- 6, 8, 36, 61, 7, 9, 0, 63, 145, 0,
- 0, 129, 130, 0, 90, 0, 0, 0, 0, 88,
- 0, 143, 133, 142, 0, 23, 120, 148, 149, 5,
- 3, 13, 0, 61, 0, 10, 12, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 107, 0,
- 0, 0, 0, 0, 0, 0, 131, 132, 34, 0,
- 76, 0, 0, 61, 0, 0, 0, 55, 56, 0,
- 76, 61, 0, 32, 0, 40, 0, 0, 152, 61,
- 0, 0, 88, 0, 37, 15, 14, 0, 0, 97,
- 0, 0, 0, 0, 151, 24, 91, 0, 0, 121,
- 0, 0, 0, 155, 26, 21, 22, 103, 100, 101,
- 102, 98, 99, 0, 104, 105, 144, 140, 141, 137,
- 138, 139, 136, 94, 0, 0, 77, 0, 0, 0,
- 76, 46, 47, 50, 0, 150, 35, 33, 152, 82,
- 144, 0, 65, 0, 80, 119, 133, 54, 0, 30,
- 153, 38, 128, 147, 0, 64, 0, 0, 0, 122,
- 92, 0, 93, 89, 29, 18, 0, 96, 0, 52,
- 0, 0, 0, 146, 0, 51, 31, 63, 0, 0,
- 0, 0, 0, 83, 0, 0, 0, 0, 0, 0,
- 0, 118, 0, 39, 73, 71, 0, 0, 0, 0,
- 0, 0, 95, 106, 61, 0, 61, 0, 0, 0,
- 112, 65, 67, 66, 68, 49, 84, 85, 81, 116,
- 113, 114, 115, 110, 111, 0, 109, 61, 74, 0,
- 124, 125, 126, 127, 0, 0, 0, 0, 0, 0,
- 76, 0, 0, 17, 75, 72, 57, 53, 41, 0,
- 61, 76, 0, 48, 117, 61, 61, 0, 0, 61,
- 0, 42, 43, 61, 0, 58, 0, 45, 44, 0,
- 0, 0
-};
-
-static const short yydefgoto[] = { 310,
- 26, 27, 128, 28, 47, 72, 29, 30, 31, 32,
- 65, 33, 113, 42, 114, 115, 116, 2, 3, 130,
- 223, 237, 238, 166, 183, 184, 121, 59, 89, 232,
- 35, 48, 36, 118, 119, 140, 190, 120, 139
-};
-
-static const short yypact[] = { 1,
--32768, 17, 1006,-32768,-32768, -17, 31,-32768,-32768, -5,
- -5,-32768, 4, 11, 19, 4, 4, 57, 1085, 1933,
- 1933,-32768, 1798, 1933, 1, 809,-32768, 50, 55, -5,
- 58,-32768,-32768, 1396, 191, 80, 535, 1126, 1177,-32768,
--32768,-32768, 17, 1,-32768,-32768, 93, 86,-32768, 1701,
- 1836,-32768,-32768, 1126,-32768, 1177, 1933, 88, 5, 1300,
- 1836, 82, 68, 82, 136,-32768, 82,-32768,-32768,-32768,
--32768,-32768, 663, 1, 1739,-32768,-32768, 1739, 1739, 1836,
- 1701, 140, 1836, 1836, 1836, 1836, 1836, 117, 176, 1933,
- 1933, 1933, 1933, 1933, 1933, 1836,-32768,-32768,-32768, 110,
- 1836, 149, 111, 1, 112, 0, 0,-32768,-32768, 0,
- 1836, 1, 602,-32768, 704,-32768, 901, 663, 98, 1,
- 88, 24, 1396, 6,-32768,-32768,-32768, 115, 1933,-32768,
- 55, 758, 758, 88,-32768,-32768, 1836, 119, 1218,-32768,
- 1300, 122, 602,-32768,-32768,-32768,-32768, 1949,-32768, 1193,
--32768, 1533, 1444, 1348, 1949, 1949, 4, 96, 96, 82,
- 82, 82, 82, 1396, 1836, 0, 1396, 106, 1836, 860,
- 1874,-32768,-32768,-32768, 0,-32768,-32768,-32768, 98,-32768,
- 4, 1177, 94, 29, 1581, 191, 104,-32768, 602,-32768,
--32768,-32768,-32768,-32768, 16, 191, 1177, 1177, 1701,-32768,
- 1396, 170,-32768, 1396,-32768,-32768, 1836,-32768, 1300,-32768,
- 1177, 1300, 153, -13, 98,-32768,-32768, 86, 5, 1933,
- 1933, 1933, 0, 1912, 1259, 1912, 1777, 172, 1912, 1912,
- 1912, 176, 1912,-32768,-32768,-32768, 88, 40, 5, 5,
- 88, 1300,-32768, 1396, 1, 27, 1, 131, 181, 1044,
--32768, 94, 191, 191, 191,-32768, 1581,-32768, 1581, 1997,
--32768, 1060,-32768, 1663, 1622, 1492, 1581, 1,-32768, 38,
--32768,-32768,-32768,-32768, 860, 0, 860, 1836, 88, 955,
- 1836, 0, 1912,-32768,-32768,-32768, 173,-32768,-32768, 1300,
- 1, 1836, 88,-32768, 1581, 1, 1, 860, 88, 1,
- 860,-32768,-32768, 1, 860,-32768, 860,-32768,-32768, 189,
- 193,-32768
-};
-
-static const short yypgoto[] = {-32768,
--32768, 165,-32768,-32768,-32768,-32768, -29,-32768, 36, -49,
--32768, 8, -52, 15, -44,-32768,-32768, -6, 108, -12,
- -43,-32768,-32768, -109,-32768,-32768, 157, -27, -3, 156,
- 228, -144, 107, 177, -110, 225, 34, 367, -19
-};
-
-
-#define YYLAST 2053
-
-
-static const short yytable[] = { 34,
- 131, 175, 179, 43, 43, 137, 137, 7, 1, 75,
- 122, 124, 208, 1, 1, 60, 235, 41, 45, 236,
- 143, 249, 34, 43, 137, 46, 122, 137, 38, 224,
- 4, 149, 206, 117, 123, 123, 218, 76, 285, -79,
- 269, 286, -79, 39, 77, 145, 132, 133, 146, 147,
- 123, 135, 60, 25, 58, 40, 50, 141, 66, 24,
- 40, 215, -69, 194, 51, 189, 74, 74, 178, 117,
- -87, 34, -79, -79, 34, 34, 148, 150, 234, 152,
- 153, 154, 155, 156, 276, 74, -70, 39, 74, -79,
- 74, 96, 164, 78, 79, 126, 127, 167, 178, 43,
- 43, 74, 54, 43, 220, 97, 98, 167, 25, 117,
- 43, 197, 198, 199, 117, 233, 74, 97, 98, 49,
- 172, 173, 52, 53, 174, 213, 63, 63, 129, 63,
- 63, 188, 69, 201, 135, 204, 95, 221, 222, 117,
- 142, 97, 98, 151, 178, 92, 93, 94, 157, 241,
- 95, 125, 168, 202, 219, 165, 169, 171, 40, 43,
- 195, 209, 211, 63, 225, 212, 117, 167, 43, 239,
- 240, 293, 205, 243, 248, 263, 278, 261, 60, 37,
- 210, 144, 299, 246, 279, 117, 37, 37, 311, 216,
- 71, 296, 312, 123, 123, 242, 63, 63, 63, 63,
- 63, 63, 37, 244, 73, 251, 37, 123, 282, 0,
- 134, 170, 217, 16, 17, 0, 43, 0, 270, 176,
- 0, 187, 0, 20, 21, 0, 0, 192, 57, 0,
- 287, 24, 289, 0, 0, 63, 0, 256, 90, 91,
- 92, 93, 94, 0, 0, 95, 280, 62, 64, 0,
- 67, 68, 0, 303, 0, 0, 306, 0, 0, 0,
- 308, 0, 309, 49, 0, 0, 0, 0, 0, 43,
- 185, 117, 0, 117, 290, 43, 0, 167, 0, 0,
- 0, 0, 136, 138, 67, 0, 0, 49, 167, 0,
- 288, 187, 0, 0, 117, 0, 294, 117, 0, 0,
- 0, 117, 0, 117, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 158, 159, 160,
- 161, 162, 163, 0, 0, 0, 63, 63, 63, 0,
- 187, 187, 187, 187, 0, 187, 187, 187, 187, 187,
- 0, 0, 186, 0, 0, 193, 0, 0, 0, 0,
- 0, 0, 275, 0, 277, 0, 196, 0, 200, 0,
- 0, 0, 0, 187, 0, 187, 187, 0, 187, 0,
- 187, 187, 187, 187, 0, 284, 44, 44, 0, 257,
- 259, 260, 262, 0, 264, 265, 266, 0, 267, 187,
- 0, 0, 0, 0, 0, 0, 44, 0, 298, 0,
- 0, 187, 0, 301, 302, 0, 0, 305, 0, 0,
- 0, 307, 186, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 245, 0, 0, 247, 0, 295, 0,
- 0, 0, 0, 252, 0, 0, 0, 253, 254, 255,
- 0, 186, 186, 186, 186, 0, 186, 186, 186, 186,
- 186, 268, 0, 271, 272, 273, 274, 0, 0, 0,
- 0, 0, 44, 44, 0, 0, 44, 0, 0, 0,
- 0, 0, 0, 44, 186, 191, 186, 186, 0, 186,
- 0, 186, 186, 186, 186, 0, 0, 0, 0, 0,
- 0, 0, 0, 291, 0, 0, 0, 0, 0, 0,
- 186, 0, 0, 0, 297, 0, 0, 300, 0, 0,
- 0, 0, 186, 304, 0, 0, 0, 0, 0, 0,
- 0, 0, 44, 0, 0, 99, 0, 6, 7, 0,
- 8, 44, 0, 9, 0, 191, 0, 0, 0, 0,
- 0, 0, 100, 0, 101, 102, 103, 104, 105, 106,
- 107, 108, 109, 110, 111, 0, 13, 14, 15, 0,
- 0, 0, 16, 17, 18, 0, 0, 0, 0, 0,
- 56, 250, 20, 21, 0, 0, 0, 57, 0, 44,
- 24, 0, 0, 25, 112, 40, 0, 0, 0, 0,
- 0, 0, 177, 0, 6, 7, 0, 8, 0, 0,
- 9, 0, 0, 0, 0, 0, 281, 0, 0, 100,
- 0, 101, 102, 103, 104, 105, 106, 107, 108, 109,
- 110, 111, 0, 13, 14, 15, 0, 0, 0, 16,
- 17, 18, 44, 0, 0, 0, 292, 56, 44, 20,
- 21, 0, 0, 0, 57, 0, 0, 24, 0, 0,
- 25, 112, 40, 99, 0, 6, 7, 0, 8, 0,
- 0, 9, 0, 0, 0, 0, 0, 0, 0, 0,
- 100, 0, 101, 102, 103, 104, 105, 106, 107, 108,
- 109, 110, 111, 0, 13, 14, 15, 0, 0, 0,
- 16, 17, 18, 0, 180, 0, 6, 7, 56, 8,
- 20, 21, 9, 0, -78, 57, 0, -78, 24, 0,
- 0, 25, 0, 40, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 181, 14, 15, 0, 0,
- 0, 16, 17, 18, 0, 0, 0, -78, -78, 182,
- 0, 20, 21, 0, 0, 0, 57, 0, 0, 24,
- 6, 7, 0, 8, -78, 0, 9, 80, 0, 0,
- 81, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 13,
- 14, 15, 82, 83, 84, 16, 17, 18, 85, 0,
- 86, 87, 88, 56, 0, 20, 21, 0, -1, 70,
- 57, 6, 7, 24, 8, 0, 0, 9, 0, 74,
- 0, 0, 0, 0, 10, 11, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 12,
- 13, 14, 15, 0, 0, 0, 16, 17, 18, 0,
- 0, 0, 0, 0, 19, 0, 20, 21, 0, 22,
- 0, 23, 6, 7, 24, 8, 0, 25, 9, 0,
- 0, 0, 0, 0, 0, 0, 0, 100, 0, 101,
- 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
- 0, 13, 14, 15, 0, 0, 0, 16, 17, 18,
- 0, 0, 0, 6, 7, 56, 8, 20, 21, 9,
- 80, 0, 57, 81, 1, 24, 0, 0, 25, 0,
- 40, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 13, 14, 15, 82, 83, 84, 16, 17,
- 18, 85, 0, 86, 87, 88, 56, 0, 20, 21,
- 0, 0, 0, 57, 0, 0, 24, 6, 7, 0,
- 8, 40, 0, 9, 80, 0, 0, 81, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 13, 14, 15, 82,
- 83, 84, 16, 17, 18, 85, 0, 86, 87, 88,
- 56, 0, 20, 21, 0, 0, 5, 57, 6, 7,
- 24, 8, 0, 0, 9, 40, 0, 0, 0, 0,
- 0, 10, 11, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 12, 13, 14, 15,
- 0, 0, 0, 16, 17, 18, 6, 7, 0, 8,
- 0, 19, 9, 20, 21, 0, 22, 0, 23, 0,
- 0, 24, 0, 7, 25, 8, 0, 0, 0, 226,
- 0, 0,-32768, 0, 0, 13, 14, 15, 0, 0,
- 0, 16, 17, 18, 0, 55, 0, 6, 7, 56,
- 8, 20, 21, 9, 228, 0, 57, 16, 17, 24,
- 0, 0, 0, 0, 40, 61, 0, 20, 21, 0,
- 0, 0, 57, 0, 0, 24, 13, 14, 15, 0,
- 0, 0, 16, 17, 18, 0, 55, 0, 6, 7,
- 56, 8, 20, 21, 9, 22, 0, 57, 0, 0,
- 24, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 13, 14, 15,
- 0, 0, 0, 16, 17, 18, 0, 0, 0, 0,
- 0, 56, -86, 20, 21, 0, 0, 55, 57, 6,
- 7, 24, 8, 0, 0, 9, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 7, 0, 8, 0,
- 0, 0, 80, 0, 0,-32768, 0, 0, 13, 14,
- 15, 0, 0, 0, 16, 17, 18, 0, 203, 0,
- 6, 7, 56, 8, 20, 21, 9, 82, 0, 57,
- 16, 17, 24, 0, 0, 86, 87, 88, 56, 0,
- 20, 21, 0, 0, 0, 57, 0, 0, 24, 13,
- 14, 15, 0, 0, 0, 16, 17, 18, 0, 258,
- 0, 6, 7, 56, 8, 20, 21, 9, 0, 0,
- 57, 0, 0, 24, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 181, 14, 15, 0, 0, 0, 16, 17, 18, 0,
- 0, 0, 6, 7, 61, 8, 20, 21, 9, 80,
- 0, 57, 81, 0, 24, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 13, 14, 15, 82, 83, 84, 16, 17, 18,
- 85, 0, 86, 87, 88, 56, 135, 20, 21, 0,
- 6, 7, 57, 8, 0, 24, 9, 80, 0, 0,
- 81, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 13,
- 14, 15, 82, 83, 84, 16, 17, 18, 85, 207,
- 86, 87, 88, 56, 0, 20, 21, 0, 6, 7,
- 57, 8, 0, 24, 9, 80, 0, 0, 81, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 13, 14, 15,
- 82, 83, 84, 16, 17, 18, 85, 0, 86, 87,
- 88, 56, 0, 20, 21, 0, 6, 7, 57, 8,
- 0, 24, 9, 80, 0, 0, 81, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 13, 14, 15, 82, 83,
- 0, 16, 17, 18, 0, 0, 86, 87, 88, 56,
- 0, 20, 21, 0, 6, 7, 57, 8, 0, 24,
- 9, 226, 0, 0, 227, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 181, 14, 15, 228, 229, 230, 16,
- 17, 18, 231, 283, 0, 6, 7, 61, 8, 20,
- 21, 9, 80, 0, 57, 81, 0, 24, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 13, 14, 15, 82, 0, 0,
- 16, 17, 18, 0, 0, 86, 87, 88, 56, 0,
- 20, 21, 0, 6, 7, 57, 8, 0, 24, 9,
- 226, 0, 0, 227, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 181, 14, 15, 228, 229, 230, 16, 17,
- 18, 231, 0, 0, 6, 7, 61, 8, 20, 21,
- 9, 226, 0, 57, 227, 0, 24, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 181, 14, 15, 228, 229, 0, 16,
- 17, 18, 0, 0, 0, 6, 7, 61, 8, 20,
- 21, 9, 226, 0, 57, 227, 0, 24, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 181, 14, 15, 228, 0, 0,
- 16, 17, 18, 6, 7, 0, 8, 0, 61, 9,
- 20, 21, 0, 0, 0, 57, 0, 0, 24, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 13, 14, 15, 0, 0, 0, 16, 17,
- 18, 6, 7, 0, 8, 0, 56, 9, 20, 21,
- 0, 22, 0, 57, 0, 0, 24, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 13, 14, 15, 0, 0, 0, 16, 17, 18, 6,
- 7, 0, 8, 0, 19, 9, 20, 21, 0, 22,
- 0, 23, 0, 0, 24, 0, 0, 0, 0, 0,
- 6, 7, 0, 8, 0, 0, 9, 0, 181, 14,
- 15, 0, 0, 0, 16, 17, 18, 0, 0, 0,
- 0, 0, 61, 0, 20, 21, 0, 22, 0, 57,
- 14, 15, 24, 0, 0, 16, 17, 18, 6, 7,
- 0, 8, 0, 61, 9, 20, 21, 0, 22, 0,
- 57, 0, 0, 24, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 13, 14, 15,
- 0, 0, 0, 16, 17, 18, 6, 214, 0, 8,
- 0, 56, 9, 20, 21, 0, 0, 0, 57, 0,
- 0, 24, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 13, 14, 15, 0, 0,
- 0, 16, 17, 18, 6, 7, 0, 8, 0, 56,
- 9, 20, 21, 0, 0, 0, 57, 0, 0, 24,
- 0, 0, 0, 0, 0, 6, 7, 0, 8, 0,
- 0, 9, 0, 181, 14, 15, 0, 0, 0, 16,
- 17, 18, 7, 0, 8, 0, 0, 61,-32768, 20,
- 21, 0, 0, 0, 57, 14, 15, 24, 0, 0,
- 16, 17, 18, 0, 0, 0, 0, 0, 61, 0,
- 20, 21, 0, 82, 0, 57, 16, 17, 24, 0,
- 0,-32768,-32768,-32768, 56, 0, 20, 21, 0, 0,
- 7, 57, 8, 0, 24, 0,-32768, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 228, 0, 0, 16, 17, 0, 0, 0, 0,
- 0, 0, 61, 0, 20, 21, 0, 0, 0, 57,
- 0, 0, 24
-};
-
-static const short yycheck[] = { 3,
- 50, 111, 113, 10, 11, 1, 1, 4, 14, 29,
- 38, 39, 157, 14, 14, 19, 1, 10, 11, 4,
- 73, 35, 26, 30, 1, 11, 54, 1, 46, 1,
- 14, 81, 143, 37, 38, 39, 181, 30, 1, 11,
- 1, 4, 14, 57, 30, 75, 50, 51, 78, 79,
- 54, 47, 56, 59, 19, 61, 46, 61, 23, 56,
- 61, 171, 47, 58, 46, 118, 62, 62, 113, 73,
- 47, 75, 44, 45, 78, 79, 80, 81, 189, 83,
- 84, 85, 86, 87, 58, 62, 47, 57, 62, 61,
- 62, 12, 96, 36, 37, 3, 4, 101, 143, 106,
- 107, 62, 46, 110, 11, 38, 39, 111, 59, 113,
- 117, 131, 132, 133, 118, 12, 62, 38, 39, 13,
- 106, 107, 16, 17, 110, 170, 20, 21, 43, 23,
- 24, 117, 25, 137, 47, 139, 55, 44, 45, 143,
- 5, 38, 39, 4, 189, 50, 51, 52, 32, 199,
- 55, 44, 4, 35, 182, 46, 46, 46, 61, 166,
- 46, 165, 57, 57, 184, 169, 170, 171, 175, 197,
- 198, 281, 51, 4, 22, 4, 46, 227, 182, 3,
- 166, 74, 292, 211, 4, 189, 10, 11, 0, 175,
- 26, 19, 0, 197, 198, 199, 90, 91, 92, 93,
- 94, 95, 26, 207, 28, 218, 30, 211, 252, -1,
- 54, 104, 179, 38, 39, -1, 223, -1, 238, 112,
- -1, 115, -1, 48, 49, -1, -1, 120, 53, -1,
- 275, 56, 277, -1, -1, 129, -1, 223, 48, 49,
- 50, 51, 52, -1, -1, 55, 250, 20, 21, -1,
- 23, 24, -1, 298, -1, -1, 301, -1, -1, -1,
- 305, -1, 307, 157, -1, -1, -1, -1, -1, 276,
- 115, 275, -1, 277, 278, 282, -1, 281, -1, -1,
- -1, -1, 58, 59, 57, -1, -1, 181, 292, -1,
- 276, 185, -1, -1, 298, -1, 282, 301, -1, -1,
- -1, 305, -1, 307, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 90, 91, 92,
- 93, 94, 95, -1, -1, -1, 220, 221, 222, -1,
- 224, 225, 226, 227, -1, 229, 230, 231, 232, 233,
- -1, -1, 115, -1, -1, 121, -1, -1, -1, -1,
- -1, -1, 245, -1, 247, -1, 129, -1, 134, -1,
- -1, -1, -1, 257, -1, 259, 260, -1, 262, -1,
- 264, 265, 266, 267, -1, 268, 10, 11, -1, 224,
- 225, 226, 227, -1, 229, 230, 231, -1, 233, 283,
- -1, -1, -1, -1, -1, -1, 30, -1, 291, -1,
- -1, 295, -1, 296, 297, -1, -1, 300, -1, -1,
- -1, 304, 185, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 209, -1, -1, 212, -1, 283, -1,
- -1, -1, -1, 219, -1, -1, -1, 220, 221, 222,
- -1, 224, 225, 226, 227, -1, 229, 230, 231, 232,
- 233, 237, -1, 239, 240, 241, 242, -1, -1, -1,
- -1, -1, 106, 107, -1, -1, 110, -1, -1, -1,
- -1, -1, -1, 117, 257, 119, 259, 260, -1, 262,
- -1, 264, 265, 266, 267, -1, -1, -1, -1, -1,
- -1, -1, -1, 279, -1, -1, -1, -1, -1, -1,
- 283, -1, -1, -1, 290, -1, -1, 293, -1, -1,
- -1, -1, 295, 299, -1, -1, -1, -1, -1, -1,
- -1, -1, 166, -1, -1, 1, -1, 3, 4, -1,
- 6, 175, -1, 9, -1, 179, -1, -1, -1, -1,
- -1, -1, 18, -1, 20, 21, 22, 23, 24, 25,
- 26, 27, 28, 29, 30, -1, 32, 33, 34, -1,
- -1, -1, 38, 39, 40, -1, -1, -1, -1, -1,
- 46, 215, 48, 49, -1, -1, -1, 53, -1, 223,
- 56, -1, -1, 59, 60, 61, -1, -1, -1, -1,
- -1, -1, 1, -1, 3, 4, -1, 6, -1, -1,
- 9, -1, -1, -1, -1, -1, 250, -1, -1, 18,
- -1, 20, 21, 22, 23, 24, 25, 26, 27, 28,
- 29, 30, -1, 32, 33, 34, -1, -1, -1, 38,
- 39, 40, 276, -1, -1, -1, 280, 46, 282, 48,
- 49, -1, -1, -1, 53, -1, -1, 56, -1, -1,
- 59, 60, 61, 1, -1, 3, 4, -1, 6, -1,
- -1, 9, -1, -1, -1, -1, -1, -1, -1, -1,
- 18, -1, 20, 21, 22, 23, 24, 25, 26, 27,
- 28, 29, 30, -1, 32, 33, 34, -1, -1, -1,
- 38, 39, 40, -1, 1, -1, 3, 4, 46, 6,
- 48, 49, 9, -1, 11, 53, -1, 14, 56, -1,
- -1, 59, -1, 61, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 32, 33, 34, -1, -1,
- -1, 38, 39, 40, -1, -1, -1, 44, 45, 46,
- -1, 48, 49, -1, -1, -1, 53, -1, -1, 56,
- 3, 4, -1, 6, 61, -1, 9, 10, -1, -1,
- 13, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, -1,
- 43, 44, 45, 46, -1, 48, 49, -1, 0, 1,
- 53, 3, 4, 56, 6, -1, -1, 9, -1, 62,
- -1, -1, -1, -1, 16, 17, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, 31,
- 32, 33, 34, -1, -1, -1, 38, 39, 40, -1,
- -1, -1, -1, -1, 46, -1, 48, 49, -1, 51,
- -1, 53, 3, 4, 56, 6, -1, 59, 9, -1,
- -1, -1, -1, -1, -1, -1, -1, 18, -1, 20,
- 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
- -1, 32, 33, 34, -1, -1, -1, 38, 39, 40,
- -1, -1, -1, 3, 4, 46, 6, 48, 49, 9,
- 10, -1, 53, 13, 14, 56, -1, -1, 59, -1,
- 61, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 32, 33, 34, 35, 36, 37, 38, 39,
- 40, 41, -1, 43, 44, 45, 46, -1, 48, 49,
- -1, -1, -1, 53, -1, -1, 56, 3, 4, -1,
- 6, 61, -1, 9, 10, -1, -1, 13, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 32, 33, 34, 35,
- 36, 37, 38, 39, 40, 41, -1, 43, 44, 45,
- 46, -1, 48, 49, -1, -1, 1, 53, 3, 4,
- 56, 6, -1, -1, 9, 61, -1, -1, -1, -1,
- -1, 16, 17, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 31, 32, 33, 34,
- -1, -1, -1, 38, 39, 40, 3, 4, -1, 6,
- -1, 46, 9, 48, 49, -1, 51, -1, 53, -1,
- -1, 56, -1, 4, 59, 6, -1, -1, -1, 10,
- -1, -1, 13, -1, -1, 32, 33, 34, -1, -1,
- -1, 38, 39, 40, -1, 1, -1, 3, 4, 46,
- 6, 48, 49, 9, 35, -1, 53, 38, 39, 56,
- -1, -1, -1, -1, 61, 46, -1, 48, 49, -1,
- -1, -1, 53, -1, -1, 56, 32, 33, 34, -1,
- -1, -1, 38, 39, 40, -1, 1, -1, 3, 4,
- 46, 6, 48, 49, 9, 51, -1, 53, -1, -1,
- 56, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 32, 33, 34,
- -1, -1, -1, 38, 39, 40, -1, -1, -1, -1,
- -1, 46, 47, 48, 49, -1, -1, 1, 53, 3,
- 4, 56, 6, -1, -1, 9, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 4, -1, 6, -1,
- -1, -1, 10, -1, -1, 13, -1, -1, 32, 33,
- 34, -1, -1, -1, 38, 39, 40, -1, 1, -1,
- 3, 4, 46, 6, 48, 49, 9, 35, -1, 53,
- 38, 39, 56, -1, -1, 43, 44, 45, 46, -1,
- 48, 49, -1, -1, -1, 53, -1, -1, 56, 32,
- 33, 34, -1, -1, -1, 38, 39, 40, -1, 1,
- -1, 3, 4, 46, 6, 48, 49, 9, -1, -1,
- 53, -1, -1, 56, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- 32, 33, 34, -1, -1, -1, 38, 39, 40, -1,
- -1, -1, 3, 4, 46, 6, 48, 49, 9, 10,
- -1, 53, 13, -1, 56, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 32, 33, 34, 35, 36, 37, 38, 39, 40,
- 41, -1, 43, 44, 45, 46, 47, 48, 49, -1,
- 3, 4, 53, 6, -1, 56, 9, 10, -1, -1,
- 13, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, 32,
- 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46, -1, 48, 49, -1, 3, 4,
- 53, 6, -1, 56, 9, 10, -1, -1, 13, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 32, 33, 34,
- 35, 36, 37, 38, 39, 40, 41, -1, 43, 44,
- 45, 46, -1, 48, 49, -1, 3, 4, 53, 6,
- -1, 56, 9, 10, -1, -1, 13, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 32, 33, 34, 35, 36,
- -1, 38, 39, 40, -1, -1, 43, 44, 45, 46,
- -1, 48, 49, -1, 3, 4, 53, 6, -1, 56,
- 9, 10, -1, -1, 13, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 32, 33, 34, 35, 36, 37, 38,
- 39, 40, 41, 42, -1, 3, 4, 46, 6, 48,
- 49, 9, 10, -1, 53, 13, -1, 56, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 32, 33, 34, 35, -1, -1,
- 38, 39, 40, -1, -1, 43, 44, 45, 46, -1,
- 48, 49, -1, 3, 4, 53, 6, -1, 56, 9,
- 10, -1, -1, 13, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 32, 33, 34, 35, 36, 37, 38, 39,
- 40, 41, -1, -1, 3, 4, 46, 6, 48, 49,
- 9, 10, -1, 53, 13, -1, 56, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, 32, 33, 34, 35, 36, -1, 38,
- 39, 40, -1, -1, -1, 3, 4, 46, 6, 48,
- 49, 9, 10, -1, 53, 13, -1, 56, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, 32, 33, 34, 35, -1, -1,
- 38, 39, 40, 3, 4, -1, 6, -1, 46, 9,
- 48, 49, -1, -1, -1, 53, -1, -1, 56, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, 32, 33, 34, -1, -1, -1, 38, 39,
- 40, 3, 4, -1, 6, -1, 46, 9, 48, 49,
- -1, 51, -1, 53, -1, -1, 56, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- 32, 33, 34, -1, -1, -1, 38, 39, 40, 3,
- 4, -1, 6, -1, 46, 9, 48, 49, -1, 51,
- -1, 53, -1, -1, 56, -1, -1, -1, -1, -1,
- 3, 4, -1, 6, -1, -1, 9, -1, 32, 33,
- 34, -1, -1, -1, 38, 39, 40, -1, -1, -1,
- -1, -1, 46, -1, 48, 49, -1, 51, -1, 53,
- 33, 34, 56, -1, -1, 38, 39, 40, 3, 4,
- -1, 6, -1, 46, 9, 48, 49, -1, 51, -1,
- 53, -1, -1, 56, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 32, 33, 34,
- -1, -1, -1, 38, 39, 40, 3, 4, -1, 6,
- -1, 46, 9, 48, 49, -1, -1, -1, 53, -1,
- -1, 56, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, 32, 33, 34, -1, -1,
- -1, 38, 39, 40, 3, 4, -1, 6, -1, 46,
- 9, 48, 49, -1, -1, -1, 53, -1, -1, 56,
- -1, -1, -1, -1, -1, 3, 4, -1, 6, -1,
- -1, 9, -1, 32, 33, 34, -1, -1, -1, 38,
- 39, 40, 4, -1, 6, -1, -1, 46, 10, 48,
- 49, -1, -1, -1, 53, 33, 34, 56, -1, -1,
- 38, 39, 40, -1, -1, -1, -1, -1, 46, -1,
- 48, 49, -1, 35, -1, 53, 38, 39, 56, -1,
- -1, 43, 44, 45, 46, -1, 48, 49, -1, -1,
- 4, 53, 6, -1, 56, -1, 10, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 35, -1, -1, 38, 39, -1, -1, -1, -1,
- -1, -1, 46, -1, 48, 49, -1, -1, -1, 53,
- -1, -1, 56
-};
-#define YYPURE 1
-
-#line 2 "bison.simple"
-#ifdef sun
-#include <alloca.h>
-#endif
-
-/* Skeleton output parser for bison,
- copyright (C) 1984 Bob Corbett and Richard Stallman
-
- NO WARRANTY
-
- BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
-NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT
-WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
-RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
-WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
-BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY
-AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
-DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
-CORRECTION.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
-STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
-WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
-LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
-OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
-DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
-A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
-PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
-
- GENERAL PUBLIC LICENSE TO COPY
-
- 1. You may copy and distribute verbatim copies of this source file
-as you receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy a valid copyright notice "Copyright
-(C) 1985 Free Software Foundation, Inc."; and include following the
-copyright notice a verbatim copy of the above disclaimer of warranty
-and of this License. You may charge a distribution fee for the
-physical act of transferring a copy.
-
- 2. You may modify your copy or copies of this source file or
-any portion of it, and copy and distribute such modifications under
-the terms of Paragraph 1 above, provided that you also do the following:
-
- a) cause the modified files to carry prominent notices stating
- that you changed the files and the date of any change; and
-
- b) cause the whole of any work that you distribute or publish,
- that in whole or in part contains or is a derivative of this
- program or any part thereof, to be licensed at no charge to all
- third parties on terms identical to those contained in this
- License Agreement (except that you may choose to grant more extensive
- warranty protection to some or all third parties, at your option).
-
- c) You may charge a distribution fee for the physical act of
- transferring a copy, and you may at your option offer warranty
- protection in exchange for a fee.
-
-Mere aggregation of another unrelated program with this program (or its
-derivative) on a volume of a storage or distribution medium does not bring
-the other program under the scope of these terms.
-
- 3. You may copy and distribute this program (or a portion or derivative
-of it, under Paragraph 2) in object code or executable form under the terms
-of Paragraphs 1 and 2 above provided that you also do one of the following:
-
- a) accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of
- Paragraphs 1 and 2 above; or,
-
- b) accompany it with a written offer, valid for at least three
- years, to give any third party free (except for a nominal
- shipping charge) a complete machine-readable copy of the
- corresponding source code, to be distributed under the terms of
- Paragraphs 1 and 2 above; or,
-
- c) accompany it with the information you received as to where the
- corresponding source code may be obtained. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form alone.)
-
-For an executable file, complete source code means all the source code for
-all modules it contains; but, as a special exception, it need not include
-source code for modules which are standard libraries that accompany the
-operating system on which the executable file runs.
-
- 4. You may not copy, sublicense, distribute or transfer this program
-except as expressly provided under this License Agreement. Any attempt
-otherwise to copy, sublicense, distribute or transfer this program is void and
-your rights to use the program under this License agreement shall be
-automatically terminated. However, parties who have received computer
-software programs from you with this License Agreement will not have
-their licenses terminated so long as such parties remain in full compliance.
-
- 5. If you wish to incorporate parts of this program into other free
-programs whose distribution conditions are different, write to the Free
-Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet
-worked out a simple rule that can be stated here, but we will often permit
-this. We will be guided by the two goals of preserving the free status of
-all derivatives of our free software and of promoting the sharing and reuse of
-software.
-
-
-In other words, you are welcome to use, share and improve this program.
-You are forbidden to forbid anyone else to use, share and improve
-what you give them. Help stamp out software-hoarding! */
-
-/* This is the parser code that is written into each bison parser
- when the %semantic_parser declaration is not specified in the grammar.
- It was written by Richard Stallman by simplifying the hairy parser
- used when %semantic_parser is specified. */
-
-/* Note: there must be only one dollar sign in this file.
- It is replaced by the list of actions, each action
- as one case of the switch. */
-
-#define yyerrok (yyerrstatus = 0)
-#define yyclearin (yychar = YYEMPTY)
-#define YYEMPTY -2
-#define YYEOF 0
-#define YYFAIL goto yyerrlab;
-
-#define YYTERROR 1
-
-#ifndef YYIMPURE
-#define YYLEX yylex()
-#endif
-
-#ifndef YYPURE
-#define YYLEX yylex(&yylval, &yylloc)
-#endif
-
-/* If nonreentrant, generate the variables here */
-
-#ifndef YYIMPURE
-
-int yychar; /* the lookahead symbol */
-YYSTYPE yylval; /* the semantic value of the */
- /* lookahead symbol */
-
-YYLTYPE yylloc; /* location data for the lookahead */
- /* symbol */
-
-int yynerr; /* number of parse errors so far */
-
-#ifdef YYDEBUG
-int yydebug = 0; /* nonzero means print parse trace */
-#endif
-
-#endif /* YYIMPURE */
-
-
-/* YYMAXDEPTH indicates the initial size of the parser's stacks */
-
-#ifndef YYMAXDEPTH
-#define YYMAXDEPTH 200
-#endif
-
-/* YYMAXLIMIT is the maximum size the stacks can grow to
- (effective only if the built-in stack extension method is used). */
-
-#ifndef YYMAXLIMIT
-#define YYMAXLIMIT 10000
-#endif
-
-
-#line 167 "bison.simple"
-int
-yyparse()
-{
- register int yystate;
- register int yyn;
- register short *yyssp;
- register YYSTYPE *yyvsp;
- YYLTYPE *yylsp;
- int yyerrstatus; /* number of tokens to shift before error messages enabled */
- int yychar1; /* lookahead token as an internal (translated) token number */
-
- short yyssa[YYMAXDEPTH]; /* the state stack */
- YYSTYPE yyvsa[YYMAXDEPTH]; /* the semantic value stack */
- YYLTYPE yylsa[YYMAXDEPTH]; /* the location stack */
-
- short *yyss = yyssa; /* refer to the stacks thru separate pointers */
- YYSTYPE *yyvs = yyvsa; /* to allow yyoverflow to reallocate them elsewhere */
- YYLTYPE *yyls = yylsa;
-
- int yymaxdepth = YYMAXDEPTH;
-
-#ifndef YYPURE
- int yychar;
- YYSTYPE yylval;
- YYLTYPE yylloc;
-#endif
-
-#ifdef YYDEBUG
- extern int yydebug;
-#endif
-
-
- YYSTYPE yyval; /* the variable used to return */
- /* semantic values from the action */
- /* routines */
-
- int yylen;
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Starting parse\n");
-#endif
-
- yystate = 0;
- yyerrstatus = 0;
- yynerr = 0;
- yychar = YYEMPTY; /* Cause a token to be read. */
-
- /* Initialize stack pointers.
- Waste one element of value and location stack
- so that they stay on the same level as the state stack. */
-
- yyssp = yyss - 1;
- yyvsp = yyvs;
- yylsp = yyls;
-
-/* Push a new state, which is found in yystate . */
-/* In all cases, when you get here, the value and location stacks
- have just been pushed. so pushing a state here evens the stacks. */
-yynewstate:
-
- *++yyssp = yystate;
-
- if (yyssp >= yyss + yymaxdepth - 1)
- {
- /* Give user a chance to reallocate the stack */
- /* Use copies of these so that the &'s don't force the real ones into memory. */
- YYSTYPE *yyvs1 = yyvs;
- YYLTYPE *yyls1 = yyls;
- short *yyss1 = yyss;
-
- /* Get the current used size of the three stacks, in elements. */
- int size = yyssp - yyss + 1;
-
-#ifdef yyoverflow
- /* Each stack pointer address is followed by the size of
- the data in use in that stack, in bytes. */
- yyoverflow("parser stack overflow",
- &yyss1, size * sizeof (*yyssp),
- &yyvs1, size * sizeof (*yyvsp),
- &yyls1, size * sizeof (*yylsp),
- &yymaxdepth);
-
- yyss = yyss1; yyvs = yyvs1; yyls = yyls1;
-#else /* no yyoverflow */
- /* Extend the stack our own way. */
- if (yymaxdepth >= YYMAXLIMIT)
- yyerror("parser stack overflow");
- yymaxdepth *= 2;
- if (yymaxdepth > YYMAXLIMIT)
- yymaxdepth = YYMAXLIMIT;
- yyss = (short *) alloca (yymaxdepth * sizeof (*yyssp));
- bcopy ((char *)yyss1, (char *)yyss, size * sizeof (*yyssp));
- yyvs = (YYSTYPE *) alloca (yymaxdepth * sizeof (*yyvsp));
- bcopy ((char *)yyvs1, (char *)yyvs, size * sizeof (*yyvsp));
-#ifdef YYLSP_NEEDED
- yyls = (YYLTYPE *) alloca (yymaxdepth * sizeof (*yylsp));
- bcopy ((char *)yyls1, (char *)yyls, size * sizeof (*yylsp));
-#endif
-#endif /* no yyoverflow */
-
- yyssp = yyss + size - 1;
- yyvsp = yyvs + size - 1;
-#ifdef YYLSP_NEEDED
- yylsp = yyls + size - 1;
-#endif
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Stack size increased to %d\n", yymaxdepth);
-#endif
-
- if (yyssp >= yyss + yymaxdepth - 1)
- YYABORT;
- }
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Entering state %d\n", yystate);
-#endif
-
-/* Do appropriate processing given the current state. */
-/* Read a lookahead token if we need one and don't already have one. */
-yyresume:
-
- /* First try to decide what to do without reference to lookahead token. */
-
- yyn = yypact[yystate];
- if (yyn == YYFLAG)
- goto yydefault;
-
- /* Not known => get a lookahead token if don't already have one. */
-
- /* yychar is either YYEMPTY or YYEOF
- or a valid token in external form. */
-
- if (yychar == YYEMPTY)
- {
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Reading a token: ");
-#endif
- yychar = YYLEX;
- }
-
- /* Convert token to internal form (in yychar1) for indexing tables with */
-
- if (yychar <= 0) /* This means end of input. */
- {
- yychar1 = 0;
- yychar = YYEOF; /* Don't call YYLEX any more */
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Now at end of input.\n");
-#endif
- }
- else
- {
- yychar1 = YYTRANSLATE(yychar);
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Next token is %d (%s)\n", yychar, yytname[yychar1]);
-#endif
- }
-
- yyn += yychar1;
- if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != yychar1)
- goto yydefault;
-
- yyn = yytable[yyn];
-
- /* yyn is what to do for this token type in this state.
- Negative => reduce, -yyn is rule number.
- Positive => shift, yyn is new state.
- New state is final state => don't bother to shift,
- just return success.
- 0, or most negative number => error. */
-
- if (yyn < 0)
- {
- if (yyn == YYFLAG)
- goto yyerrlab;
- yyn = -yyn;
- goto yyreduce;
- }
- else if (yyn == 0)
- goto yyerrlab;
-
- if (yyn == YYFINAL)
- YYACCEPT;
-
- /* Shift the lookahead token. */
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Shifting token %d (%s), ", yychar, yytname[yychar1]);
-#endif
-
- /* Discard the token being shifted unless it is eof. */
- if (yychar != YYEOF)
- yychar = YYEMPTY;
-
- *++yyvsp = yylval;
-#ifdef YYLSP_NEEDED
- *++yylsp = yylloc;
-#endif
-
- /* count tokens shifted since error; after three, turn off error status. */
- if (yyerrstatus) yyerrstatus--;
-
- yystate = yyn;
- goto yynewstate;
-
-/* Do the default action for the current state. */
-yydefault:
-
- yyn = yydefact[yystate];
- if (yyn == 0)
- goto yyerrlab;
-
-/* Do a reduction. yyn is the number of a rule to reduce with. */
-yyreduce:
- yylen = yyr2[yyn];
- yyval = yyvsp[1-yylen]; /* implement default value of the action */
-
-#ifdef YYDEBUG
- if (yydebug)
- {
- if (yylen == 1)
- fprintf (stderr, "Reducing 1 value via line %d, ",
- yyrline[yyn]);
- else
- fprintf (stderr, "Reducing %d values via line %d, ",
- yylen, yyrline[yyn]);
- }
-#endif
-
-
- switch (yyn) {
-
-case 1:
-#line 301 "awk.y"
-{ expression_value = yyvsp[0].nodeval; ;
- break;}
-case 2:
-#line 306 "awk.y"
-{
- if (yyvsp[0].nodeval != NULL)
- yyval.nodeval = yyvsp[0].nodeval;
- else
- yyval.nodeval = NULL;
- yyerrok;
- ;
- break;}
-case 3:
-#line 315 "awk.y"
-{
- if (yyvsp[0].nodeval == NULL)
- yyval.nodeval = yyvsp[-1].nodeval;
- else if (yyvsp[-1].nodeval == NULL)
- yyval.nodeval = yyvsp[0].nodeval;
- else {
- if (yyvsp[-1].nodeval->type != Node_rule_list)
- yyvsp[-1].nodeval = node(yyvsp[-1].nodeval, Node_rule_list,
- (NODE*)NULL);
- yyval.nodeval = append_right (yyvsp[-1].nodeval,
- node(yyvsp[0].nodeval, Node_rule_list,(NODE *) NULL));
- }
- yyerrok;
- ;
- break;}
-case 4:
-#line 329 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 5:
-#line 330 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 6:
-#line 335 "awk.y"
-{
- if (begin_block) {
- if (begin_block->type != Node_rule_list)
- begin_block = node(begin_block, Node_rule_list,
- (NODE *)NULL);
- append_right (begin_block, node(
- node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval),
- Node_rule_list, (NODE *)NULL) );
- } else
- begin_block = node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval);
- yyval.nodeval = NULL;
- yyerrok;
- ;
- break;}
-case 7:
-#line 349 "awk.y"
-{
- if (end_block) {
- if (end_block->type != Node_rule_list)
- end_block = node(end_block, Node_rule_list,
- (NODE *)NULL);
- append_right (end_block, node(
- node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval),
- Node_rule_list, (NODE *)NULL));
- } else
- end_block = node((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval);
- yyval.nodeval = NULL;
- yyerrok;
- ;
- break;}
-case 8:
-#line 363 "awk.y"
-{
- msg ("error near line %d: BEGIN blocks must have an action part", lineno);
- errcount++;
- yyerrok;
- ;
- break;}
-case 9:
-#line 369 "awk.y"
-{
- msg ("error near line %d: END blocks must have an action part", lineno);
- errcount++;
- yyerrok;
- ;
- break;}
-case 10:
-#line 375 "awk.y"
-{ yyval.nodeval = node (yyvsp[-1].nodeval, Node_rule_node, yyvsp[0].nodeval); yyerrok; ;
- break;}
-case 11:
-#line 377 "awk.y"
-{ yyval.nodeval = node ((NODE *)NULL, Node_rule_node, yyvsp[0].nodeval); yyerrok; ;
- break;}
-case 12:
-#line 379 "awk.y"
-{ if(yyvsp[-1].nodeval) yyval.nodeval = node (yyvsp[-1].nodeval, Node_rule_node, (NODE *)NULL); yyerrok; ;
- break;}
-case 13:
-#line 381 "awk.y"
-{
- func_install(yyvsp[-1].nodeval, yyvsp[0].nodeval);
- yyval.nodeval = NULL;
- yyerrok;
- ;
- break;}
-case 14:
-#line 390 "awk.y"
-{ yyval.sval = yyvsp[0].sval; ;
- break;}
-case 15:
-#line 392 "awk.y"
-{ yyval.sval = yyvsp[0].sval; ;
- break;}
-case 16:
-#line 397 "awk.y"
-{
- param_counter = 0;
- ;
- break;}
-case 17:
-#line 401 "awk.y"
-{
- yyval.nodeval = append_right(make_param(yyvsp[-4].sval), yyvsp[-2].nodeval);
- ;
- break;}
-case 18:
-#line 408 "awk.y"
-{ yyval.nodeval = yyvsp[-1].nodeval; ;
- break;}
-case 19:
-#line 414 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 20:
-#line 416 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 21:
-#line 418 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_and, yyvsp[0].nodeval); ;
- break;}
-case 22:
-#line 420 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_or, yyvsp[0].nodeval); ;
- break;}
-case 23:
-#line 422 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_not,(NODE *) NULL); ;
- break;}
-case 24:
-#line 424 "awk.y"
-{ yyval.nodeval = yyvsp[-1].nodeval; ;
- break;}
-case 25:
-#line 429 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 26:
-#line 431 "awk.y"
-{ yyval.nodeval = mkrangenode ( node(yyvsp[-2].nodeval, Node_cond_pair, yyvsp[0].nodeval) ); ;
- break;}
-case 27:
-#line 436 "awk.y"
-{
- yyval.nodeval = node(
- node(make_number((AWKNUM)0),Node_field_spec,(NODE*)NULL),
- Node_match, yyvsp[0].nodeval);
- ;
- break;}
-case 28:
-#line 449 "awk.y"
-{ ++want_regexp; ;
- break;}
-case 29:
-#line 451 "awk.y"
-{
- want_regexp = 0;
- yyval.nodeval = node((NODE *)NULL,Node_regex,(NODE *)mk_re_parse(yyvsp[-1].sval, 0));
- yyval.nodeval -> re_case = 0;
- emalloc (yyval.nodeval -> re_text, char *, strlen(yyvsp[-1].sval)+1, "regexp");
- strcpy (yyval.nodeval -> re_text, yyvsp[-1].sval);
- ;
- break;}
-case 30:
-#line 462 "awk.y"
-{
- /* empty actions are different from missing actions */
- yyval.nodeval = node ((NODE *) NULL, Node_illegal, (NODE *) NULL);
- ;
- break;}
-case 31:
-#line 467 "awk.y"
-{ yyval.nodeval = yyvsp[-2].nodeval ; ;
- break;}
-case 32:
-#line 472 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 33:
-#line 474 "awk.y"
-{
- if (yyvsp[-1].nodeval->type != Node_statement_list)
- yyvsp[-1].nodeval = node(yyvsp[-1].nodeval, Node_statement_list,(NODE *)NULL);
- yyval.nodeval = append_right(yyvsp[-1].nodeval,
- node( yyvsp[0].nodeval, Node_statement_list, (NODE *)NULL));
- yyerrok;
- ;
- break;}
-case 34:
-#line 482 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 35:
-#line 484 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 36:
-#line 489 "awk.y"
-{ yyval.nodetypeval = Node_illegal; ;
- break;}
-case 37:
-#line 491 "awk.y"
-{ yyval.nodetypeval = Node_illegal; ;
- break;}
-case 38:
-#line 497 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 39:
-#line 499 "awk.y"
-{ yyval.nodeval = yyvsp[-1].nodeval; ;
- break;}
-case 40:
-#line 501 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 41:
-#line 503 "awk.y"
-{ yyval.nodeval = node (yyvsp[-3].nodeval, Node_K_while, yyvsp[0].nodeval); ;
- break;}
-case 42:
-#line 505 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_K_do, yyvsp[-5].nodeval); ;
- break;}
-case 43:
-#line 507 "awk.y"
-{
- yyval.nodeval = node (yyvsp[0].nodeval, Node_K_arrayfor, make_for_loop(variable(yyvsp[-5].sval),
- (NODE *)NULL, variable(yyvsp[-3].sval)));
- ;
- break;}
-case 44:
-#line 512 "awk.y"
-{
- yyval.nodeval = node(yyvsp[0].nodeval, Node_K_for, (NODE *)make_for_loop(yyvsp[-7].nodeval, yyvsp[-5].nodeval, yyvsp[-3].nodeval));
- ;
- break;}
-case 45:
-#line 516 "awk.y"
-{
- yyval.nodeval = node (yyvsp[0].nodeval, Node_K_for,
- (NODE *)make_for_loop(yyvsp[-6].nodeval, (NODE *)NULL, yyvsp[-3].nodeval));
- ;
- break;}
-case 46:
-#line 522 "awk.y"
-{ yyval.nodeval = node ((NODE *)NULL, Node_K_break, (NODE *)NULL); ;
- break;}
-case 47:
-#line 525 "awk.y"
-{ yyval.nodeval = node ((NODE *)NULL, Node_K_continue, (NODE *)NULL); ;
- break;}
-case 48:
-#line 527 "awk.y"
-{ yyval.nodeval = node (yyvsp[-3].nodeval, yyvsp[-5].nodetypeval, yyvsp[-1].nodeval); ;
- break;}
-case 49:
-#line 529 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-3].nodetypeval, yyvsp[-1].nodeval); ;
- break;}
-case 50:
-#line 531 "awk.y"
-{ yyval.nodeval = node ((NODE *)NULL, Node_K_next, (NODE *)NULL); ;
- break;}
-case 51:
-#line 533 "awk.y"
-{ yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_exit, (NODE *)NULL); ;
- break;}
-case 52:
-#line 535 "awk.y"
-{ yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_return, (NODE *)NULL); ;
- break;}
-case 53:
-#line 537 "awk.y"
-{ yyval.nodeval = node (variable(yyvsp[-4].sval), Node_K_delete, yyvsp[-2].nodeval); ;
- break;}
-case 54:
-#line 539 "awk.y"
-{ yyval.nodeval = yyvsp[-1].nodeval; ;
- break;}
-case 55:
-#line 544 "awk.y"
-{ yyval.nodetypeval = yyvsp[0].nodetypeval; ;
- break;}
-case 56:
-#line 546 "awk.y"
-{ yyval.nodetypeval = yyvsp[0].nodetypeval; ;
- break;}
-case 57:
-#line 551 "awk.y"
-{
- yyval.nodeval = node(yyvsp[-3].nodeval, Node_K_if,
- node(yyvsp[0].nodeval, Node_if_branches, (NODE *)NULL));
- ;
- break;}
-case 58:
-#line 557 "awk.y"
-{ yyval.nodeval = node (yyvsp[-6].nodeval, Node_K_if,
- node (yyvsp[-3].nodeval, Node_if_branches, yyvsp[0].nodeval)); ;
- break;}
-case 59:
-#line 563 "awk.y"
-{ yyval.nodetypeval = NULL; ;
- break;}
-case 60:
-#line 565 "awk.y"
-{ yyval.nodetypeval = NULL; ;
- break;}
-case 61:
-#line 570 "awk.y"
-{ yyval.nodetypeval = NULL; ;
- break;}
-case 62:
-#line 572 "awk.y"
-{ yyval.nodetypeval = NULL; ;
- break;}
-case 63:
-#line 577 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 64:
-#line 579 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_input, (NODE *)NULL); ;
- break;}
-case 65:
-#line 584 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 66:
-#line 586 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_output, (NODE *)NULL); ;
- break;}
-case 67:
-#line 588 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_append, (NODE *)NULL); ;
- break;}
-case 68:
-#line 590 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_redirect_pipe, (NODE *)NULL); ;
- break;}
-case 69:
-#line 595 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 70:
-#line 597 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 71:
-#line 602 "awk.y"
-{ yyval.nodeval = make_param(yyvsp[0].sval); ;
- break;}
-case 72:
-#line 604 "awk.y"
-{ yyval.nodeval = append_right(yyvsp[-2].nodeval, make_param(yyvsp[0].sval)); yyerrok; ;
- break;}
-case 73:
-#line 606 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 74:
-#line 608 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 75:
-#line 610 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 76:
-#line 616 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 77:
-#line 618 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 78:
-#line 623 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 79:
-#line 625 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 80:
-#line 630 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL); ;
- break;}
-case 81:
-#line 632 "awk.y"
-{
- yyval.nodeval = append_right(yyvsp[-2].nodeval,
- node( yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL));
- yyerrok;
- ;
- break;}
-case 82:
-#line 638 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 83:
-#line 640 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 84:
-#line 642 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 85:
-#line 644 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 86:
-#line 649 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 87:
-#line 651 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 88:
-#line 656 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL); ;
- break;}
-case 89:
-#line 658 "awk.y"
-{
- yyval.nodeval = append_right(yyvsp[-2].nodeval,
- node( yyvsp[0].nodeval, Node_expression_list, (NODE *)NULL));
- yyerrok;
- ;
- break;}
-case 90:
-#line 664 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 91:
-#line 666 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 92:
-#line 668 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 93:
-#line 670 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 94:
-#line 675 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 95:
-#line 677 "awk.y"
-{ yyval.nodeval = node (variable(yyvsp[0].sval), Node_in_array, yyvsp[-3].nodeval); ;
- break;}
-case 96:
-#line 679 "awk.y"
-{
- yyval.nodeval = node (yyvsp[0].nodeval, Node_K_getline,
- node (yyvsp[-3].nodeval, Node_redirect_pipein, (NODE *)NULL));
- ;
- break;}
-case 97:
-#line 684 "awk.y"
-{
- yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_getline, yyvsp[0].nodeval);
- ;
- break;}
-case 98:
-#line 688 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_and, yyvsp[0].nodeval); ;
- break;}
-case 99:
-#line 690 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_or, yyvsp[0].nodeval); ;
- break;}
-case 100:
-#line 692 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 101:
-#line 694 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 102:
-#line 696 "awk.y"
-{ yyval.nodeval = node (variable(yyvsp[0].sval), Node_in_array, yyvsp[-2].nodeval); ;
- break;}
-case 103:
-#line 698 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 104:
-#line 700 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_less, yyvsp[0].nodeval); ;
- break;}
-case 105:
-#line 702 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_greater, yyvsp[0].nodeval); ;
- break;}
-case 106:
-#line 704 "awk.y"
-{ yyval.nodeval = node(yyvsp[-4].nodeval, Node_cond_exp, node(yyvsp[-2].nodeval, Node_if_branches, yyvsp[0].nodeval));;
- break;}
-case 107:
-#line 706 "awk.y"
-{ yyval.nodeval = node (yyvsp[-1].nodeval, Node_concat, yyvsp[0].nodeval); ;
- break;}
-case 108:
-#line 708 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 109:
-#line 713 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 110:
-#line 715 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_and, yyvsp[0].nodeval); ;
- break;}
-case 111:
-#line 717 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_or, yyvsp[0].nodeval); ;
- break;}
-case 112:
-#line 719 "awk.y"
-{
- yyval.nodeval = node (yyvsp[-1].nodeval, Node_K_getline, yyvsp[0].nodeval);
- ;
- break;}
-case 113:
-#line 723 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 114:
-#line 725 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 115:
-#line 727 "awk.y"
-{ yyval.nodeval = node (variable(yyvsp[0].sval), Node_in_array, yyvsp[-2].nodeval); ;
- break;}
-case 116:
-#line 729 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, yyvsp[-1].nodetypeval, yyvsp[0].nodeval); ;
- break;}
-case 117:
-#line 731 "awk.y"
-{ yyval.nodeval = node(yyvsp[-4].nodeval, Node_cond_exp, node(yyvsp[-2].nodeval, Node_if_branches, yyvsp[0].nodeval));;
- break;}
-case 118:
-#line 733 "awk.y"
-{ yyval.nodeval = node (yyvsp[-1].nodeval, Node_concat, yyvsp[0].nodeval); ;
- break;}
-case 119:
-#line 735 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 120:
-#line 740 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_not,(NODE *) NULL); ;
- break;}
-case 121:
-#line 742 "awk.y"
-{ yyval.nodeval = yyvsp[-1].nodeval; ;
- break;}
-case 122:
-#line 744 "awk.y"
-{ yyval.nodeval = snode (yyvsp[-1].nodeval, Node_builtin, yyvsp[-3].ptrval); ;
- break;}
-case 123:
-#line 746 "awk.y"
-{ yyval.nodeval = snode ((NODE *)NULL, Node_builtin, yyvsp[0].ptrval); ;
- break;}
-case 124:
-#line 748 "awk.y"
-{ yyval.nodeval = node(yyvsp[-1].nodeval, yyvsp[-5].nodetypeval, yyvsp[-3].nodeval); ;
- break;}
-case 125:
-#line 750 "awk.y"
-{ yyval.nodeval = node(yyvsp[-1].nodeval, yyvsp[-5].nodetypeval, yyvsp[-3].nodeval); ;
- break;}
-case 126:
-#line 752 "awk.y"
-{ yyval.nodeval = node(yyvsp[-3].nodeval, yyvsp[-5].nodetypeval, yyvsp[-1].nodeval); ;
- break;}
-case 127:
-#line 754 "awk.y"
-{ yyval.nodeval = node(yyvsp[-3].nodeval, yyvsp[-5].nodetypeval, yyvsp[-1].nodeval); ;
- break;}
-case 128:
-#line 756 "awk.y"
-{
- yyval.nodeval = node (yyvsp[-1].nodeval, Node_func_call, make_string(yyvsp[-3].sval, strlen(yyvsp[-3].sval)));
- ;
- break;}
-case 129:
-#line 760 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_preincrement, (NODE *)NULL); ;
- break;}
-case 130:
-#line 762 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_predecrement, (NODE *)NULL); ;
- break;}
-case 131:
-#line 764 "awk.y"
-{ yyval.nodeval = node (yyvsp[-1].nodeval, Node_postincrement, (NODE *)NULL); ;
- break;}
-case 132:
-#line 766 "awk.y"
-{ yyval.nodeval = node (yyvsp[-1].nodeval, Node_postdecrement, (NODE *)NULL); ;
- break;}
-case 133:
-#line 768 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 134:
-#line 770 "awk.y"
-{ yyval.nodeval = make_number (yyvsp[0].fval); ;
- break;}
-case 135:
-#line 772 "awk.y"
-{ yyval.nodeval = make_string (yyvsp[0].sval, -1); ;
- break;}
-case 136:
-#line 776 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_exp, yyvsp[0].nodeval); ;
- break;}
-case 137:
-#line 778 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_times, yyvsp[0].nodeval); ;
- break;}
-case 138:
-#line 780 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_quotient, yyvsp[0].nodeval); ;
- break;}
-case 139:
-#line 782 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_mod, yyvsp[0].nodeval); ;
- break;}
-case 140:
-#line 784 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_plus, yyvsp[0].nodeval); ;
- break;}
-case 141:
-#line 786 "awk.y"
-{ yyval.nodeval = node (yyvsp[-2].nodeval, Node_minus, yyvsp[0].nodeval); ;
- break;}
-case 142:
-#line 788 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_unary_minus, (NODE *)NULL); ;
- break;}
-case 143:
-#line 790 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 144:
-#line 795 "awk.y"
-{ yyval.nodeval = NULL; ;
- break;}
-case 145:
-#line 797 "awk.y"
-{ yyval.nodeval = yyvsp[0].nodeval; ;
- break;}
-case 146:
-#line 802 "awk.y"
-{ yyval.nodeval = variable (yyvsp[0].sval); ;
- break;}
-case 147:
-#line 804 "awk.y"
-{ yyval.nodeval = node (variable(yyvsp[-3].sval), Node_subscript, yyvsp[-1].nodeval); ;
- break;}
-case 148:
-#line 806 "awk.y"
-{ yyval.nodeval = node (yyvsp[0].nodeval, Node_field_spec, (NODE *)NULL); ;
- break;}
-case 150:
-#line 814 "awk.y"
-{ yyerrok; ;
- break;}
-case 151:
-#line 818 "awk.y"
-{ yyval.nodetypeval = Node_illegal; yyerrok; ;
- break;}
-case 154:
-#line 827 "awk.y"
-{ yyerrok; ;
- break;}
-case 155:
-#line 830 "awk.y"
-{ yyval.nodetypeval = Node_illegal; yyerrok; ;
- break;}
-}
- /* the action file gets copied in in place of this dollarsign */
-#line 408 "bison.simple"
-
- yyvsp -= yylen;
- yyssp -= yylen;
-#ifdef YYLSP_NEEDED
- yylsp -= yylen;
-#endif
-
-#ifdef YYDEBUG
- if (yydebug)
- {
- short *ssp1 = yyss - 1;
- fprintf (stderr, "state stack now");
- while (ssp1 != yyssp)
- fprintf (stderr, " %d", *++ssp1);
- fprintf (stderr, "\n");
- }
-#endif
-
- *++yyvsp = yyval;
-
-#ifdef YYLSP_NEEDED
- yylsp++;
- if (yylen == 0)
- {
- yylsp->first_line = yylloc.first_line;
- yylsp->first_column = yylloc.first_column;
- yylsp->last_line = (yylsp-1)->last_line;
- yylsp->last_column = (yylsp-1)->last_column;
- yylsp->text = 0;
- }
- else
- {
- yylsp->last_line = (yylsp+yylen-1)->last_line;
- yylsp->last_column = (yylsp+yylen-1)->last_column;
- }
-#endif
-
- /* Now "shift" the result of the reduction.
- Determine what state that goes to,
- based on the state we popped back to
- and the rule number reduced by. */
-
- yyn = yyr1[yyn];
-
- yystate = yypgoto[yyn - YYNTBASE] + *yyssp;
- if (yystate >= 0 && yystate <= YYLAST && yycheck[yystate] == *yyssp)
- yystate = yytable[yystate];
- else
- yystate = yydefgoto[yyn - YYNTBASE];
-
- goto yynewstate;
-
-yyerrlab: /* here on detecting error */
-
- if (! yyerrstatus)
- /* If not already recovering from an error, report this error. */
- {
- ++yynerr;
- yyerror("parse error");
- }
-
- if (yyerrstatus == 3)
- {
- /* if just tried and failed to reuse lookahead token after an error, discard it. */
-
- /* return failure if at end of input */
- if (yychar == YYEOF)
- YYABORT;
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Discarding token %d (%s).\n", yychar, yytname[yychar1]);
-#endif
-
- yychar = YYEMPTY;
- }
-
- /* Else will try to reuse lookahead token
- after shifting the error token. */
-
- yyerrstatus = 3; /* Each real token shifted decrements this */
-
- goto yyerrhandle;
-
-yyerrdefault: /* current state does not do anything special for the error token. */
-
-#if 0
- /* This is wrong; only states that explicitly want error tokens
- should shift them. */
- yyn = yydefact[yystate]; /* If its default is to accept any token, ok. Otherwise pop it.*/
- if (yyn) goto yydefault;
-#endif
-
-yyerrpop: /* pop the current state because it cannot handle the error token */
-
- if (yyssp == yyss) YYABORT;
- yyvsp--;
- yystate = *--yyssp;
-#ifdef YYLSP_NEEDED
- yylsp--;
-#endif
-
-#ifdef YYDEBUG
- if (yydebug)
- {
- short *ssp1 = yyss - 1;
- fprintf (stderr, "Error: state stack now");
- while (ssp1 != yyssp)
- fprintf (stderr, " %d", *++ssp1);
- fprintf (stderr, "\n");
- }
-#endif
-
-yyerrhandle:
-
- yyn = yypact[yystate];
- if (yyn == YYFLAG)
- goto yyerrdefault;
-
- yyn += YYTERROR;
- if (yyn < 0 || yyn > YYLAST || yycheck[yyn] != YYTERROR)
- goto yyerrdefault;
-
- yyn = yytable[yyn];
- if (yyn < 0)
- {
- if (yyn == YYFLAG)
- goto yyerrpop;
- yyn = -yyn;
- goto yyreduce;
- }
- else if (yyn == 0)
- goto yyerrpop;
-
- if (yyn == YYFINAL)
- YYACCEPT;
-
-#ifdef YYDEBUG
- if (yydebug)
- fprintf(stderr, "Shifting error token, ");
-#endif
-
- *++yyvsp = yylval;
-#ifdef YYLSP_NEEDED
- *++yylsp = yylloc;
-#endif
-
- yystate = yyn;
- goto yynewstate;
-}
-#line 833 "awk.y"
-
-
-struct token {
- char *operator; /* text to match */
- NODETYPE value; /* node type */
- int class; /* lexical class */
- short nostrict; /* ignore if in strict compatibility mode */
- NODE *(*ptr) (); /* function that implements this keyword */
-};
-
-#ifndef NULL
-#define NULL 0
-#endif
-
-extern NODE
- *do_exp(), *do_getline(), *do_index(), *do_length(),
- *do_sqrt(), *do_log(), *do_sprintf(), *do_substr(),
- *do_split(), *do_system(), *do_int(), *do_close(),
- *do_atan2(), *do_sin(), *do_cos(), *do_rand(),
- *do_srand(), *do_match(), *do_tolower(), *do_toupper();
-
-/* Special functions for debugging */
-#ifdef DEBUG
-NODE *do_prvars(), *do_bp();
-#endif
-
-/* Tokentab is sorted ascii ascending order, so it can be binary searched. */
-
-static struct token tokentab[] = {
- { "BEGIN", Node_illegal, LEX_BEGIN, 0, 0 },
- { "END", Node_illegal, LEX_END, 0, 0 },
- { "atan2", Node_builtin, LEX_BUILTIN, 0, do_atan2 },
-#ifdef DEBUG
- { "bp", Node_builtin, LEX_BUILTIN, 0, do_bp },
-#endif
- { "break", Node_K_break, LEX_BREAK, 0, 0 },
- { "close", Node_builtin, LEX_BUILTIN, 0, do_close },
- { "continue", Node_K_continue, LEX_CONTINUE, 0, 0 },
- { "cos", Node_builtin, LEX_BUILTIN, 0, do_cos },
- { "delete", Node_K_delete, LEX_DELETE, 0, 0 },
- { "do", Node_K_do, LEX_DO, 0, 0 },
- { "else", Node_illegal, LEX_ELSE, 0, 0 },
- { "exit", Node_K_exit, LEX_EXIT, 0, 0 },
- { "exp", Node_builtin, LEX_BUILTIN, 0, do_exp },
- { "for", Node_K_for, LEX_FOR, 0, 0 },
- { "func", Node_K_function, LEX_FUNCTION, 0, 0 },
- { "function", Node_K_function, LEX_FUNCTION, 0, 0 },
- { "getline", Node_K_getline, LEX_GETLINE, 0, 0 },
- { "gsub", Node_gsub, LEX_SUB, 0, 0 },
- { "if", Node_K_if, LEX_IF, 0, 0 },
- { "in", Node_illegal, LEX_IN, 0, 0 },
- { "index", Node_builtin, LEX_BUILTIN, 0, do_index },
- { "int", Node_builtin, LEX_BUILTIN, 0, do_int },
- { "length", Node_builtin, LEX_BUILTIN, 0, do_length },
- { "log", Node_builtin, LEX_BUILTIN, 0, do_log },
- { "match", Node_K_match, LEX_MATCH, 0, 0 },
- { "next", Node_K_next, LEX_NEXT, 0, 0 },
- { "print", Node_K_print, LEX_PRINT, 0, 0 },
- { "printf", Node_K_printf, LEX_PRINTF, 0, 0 },
-#ifdef DEBUG
- { "prvars", Node_builtin, LEX_BUILTIN, 0, do_prvars },
-#endif
- { "rand", Node_builtin, LEX_BUILTIN, 0, do_rand },
- { "return", Node_K_return, LEX_RETURN, 0, 0 },
- { "sin", Node_builtin, LEX_BUILTIN, 0, do_sin },
- { "split", Node_builtin, LEX_BUILTIN, 0, do_split },
- { "sprintf", Node_builtin, LEX_BUILTIN, 0, do_sprintf },
- { "sqrt", Node_builtin, LEX_BUILTIN, 0, do_sqrt },
- { "srand", Node_builtin, LEX_BUILTIN, 0, do_srand },
- { "sub", Node_sub, LEX_SUB, 0, 0 },
- { "substr", Node_builtin, LEX_BUILTIN, 0, do_substr },
- { "system", Node_builtin, LEX_BUILTIN, 0, do_system },
- { "tolower", Node_builtin, LEX_BUILTIN, 1, do_tolower },
- { "toupper", Node_builtin, LEX_BUILTIN, 1, do_toupper },
- { "while", Node_K_while, LEX_WHILE, 0, 0 },
-};
-
-/* VARARGS0 */
-static void
-yyerror(va_alist)
-va_dcl
-{
- va_list args;
- char *mesg;
- char *a1;
- register char *ptr, *beg;
- static int list = 0;
- char *scan;
-
- errcount++;
- va_start(args);
- mesg = va_arg(args, char *);
- if (! list)
- a1 = va_arg(args, char *);
- va_end(args);
- if (mesg || !list) {
- /* Find the current line in the input file */
- if (!lexptr) {
- beg = "(END OF FILE)";
- ptr = beg + 13;
- } else {
- if (*lexptr == '\n' && lexptr != lexptr_begin)
- --lexptr;
- for (beg = lexptr; beg != lexptr_begin && *beg != '\n'; --beg)
- ;
- /* NL isn't guaranteed */
- for (ptr = lexptr; *ptr && *ptr != '\n'; ptr++)
- ;
- if (beg != lexptr_begin)
- beg++;
- }
- msg("syntax error near line %d:\n%.*s", lineno, ptr - beg, beg);
- scan = beg;
- while (scan <= lexptr)
- if (*scan++ == '\t')
- putc('\t', stderr);
- else
- putc(' ', stderr);
- putc('^', stderr);
- putc(' ', stderr);
- if (mesg) {
- vfprintf(stderr, mesg, args);
- putc('\n', stderr);
- exit(1);
- } else {
- if (a1) {
- fputs("expecting: ", stderr);
- fputs(a1, stderr);
- list = 1;
- return;
- }
- }
- return;
- }
- if (a1) {
- fputs(" or ", stderr);
- fputs(a1, stderr);
- putc('\n', stderr);
- return;
- }
- putc('\n', stderr);
- list = 0;
-}
-
-/*
- * Parse a C escape sequence. STRING_PTR points to a variable containing a
- * pointer to the string to parse. That pointer is updated past the
- * characters we use. The value of the escape sequence is returned.
- *
- * A negative value means the sequence \ newline was seen, which is supposed to
- * be equivalent to nothing at all.
- *
- * If \ is followed by a null character, we return a negative value and leave
- * the string pointer pointing at the null character.
- *
- * If \ is followed by 000, we return 0 and leave the string pointer after the
- * zeros. A value of 0 does not mean end of string.
- */
-
-static int
-parse_escape(string_ptr)
-char **string_ptr;
-{
- register int c = *(*string_ptr)++;
- register int i;
-
- switch (c) {
- case 'a':
- if (strict)
- goto def;
- else
- return BELL;
- case 'b':
- return '\b';
- case 'f':
- return '\f';
- case 'n':
- return '\n';
- case 'r':
- return '\r';
- case 't':
- return '\t';
- case 'v':
- if (strict)
- goto def;
- else
- return '\v';
- case '\n':
- return -2;
- case 0:
- (*string_ptr)--;
- return 0;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- {
- register int i = c - '0';
- register int count = 0;
-
- while (++count < 3) {
- if ((c = *(*string_ptr)++) >= '0' && c <= '7') {
- i *= 8;
- i += c - '0';
- } else {
- (*string_ptr)--;
- break;
- }
- }
- return i;
- }
- case 'x':
- if (strict)
- goto def;
-
- i = 0;
- while (1) {
- if (isxdigit((c = *(*string_ptr)++))) {
- if (isdigit(c))
- i += c - '0';
- else if (isupper(c))
- i += c - 'A' + 10;
- else
- i += c - 'a' + 10;
- } else {
- (*string_ptr)--;
- break;
- }
- }
- return i;
- default:
- def:
- return c;
- }
-}
-
-/*
- * Read the input and turn it into tokens. Input is now read from a file
- * instead of from malloc'ed memory. The main program takes a program
- * passed as a command line argument and writes it to a temp file. Otherwise
- * the file name is made available in an external variable.
- */
-
-static int
-yylex()
-{
- register int c;
- register int namelen;
- register char *tokstart;
- char *tokkey;
- static did_newline = 0; /* the grammar insists that actions end
- * with newlines. This was easier than
- * hacking the grammar. */
- int seen_e = 0; /* These are for numbers */
- int seen_point = 0;
- extern char **sourcefile;
- extern int tempsource, numfiles;
- static int file_opened = 0;
- static FILE *fin;
- static char cbuf[BUFSIZ];
- int low, mid, high;
-#ifdef DEBUG
- extern int debugging;
-#endif
-
- if (! file_opened) {
- file_opened = 1;
-#ifdef DEBUG
- if (debugging) {
- int i;
-
- for (i = 0; i <= numfiles; i++)
- fprintf (stderr, "sourcefile[%d] = %s\n", i,
- sourcefile[i]);
- }
-#endif
- nextfile:
- if ((fin = pathopen (sourcefile[++curinfile])) == NULL)
- fatal("cannot open `%s' for reading (%s)",
- sourcefile[curinfile],
- sys_errlist[errno]);
- *(lexptr = cbuf) = '\0';
- /*
- * immediately unlink the tempfile so that it will
- * go away cleanly if we bomb.
- */
- if (tempsource && curinfile == 0)
- (void) unlink (sourcefile[curinfile]);
- }
-
-retry:
- if (! *lexptr)
- if (fgets (cbuf, sizeof cbuf, fin) == NULL) {
- if (fin != NULL)
- fclose (fin); /* be neat and clean */
- if (curinfile < numfiles)
- goto nextfile;
- return 0;
- } else
- lexptr = lexptr_begin = cbuf;
-
- if (want_regexp) {
- want_regexp = 0;
-
- /*
- * there is a potential bug if a regexp is followed by an
- * equal sign: "/foo/=bar" would result in assign_quotient
- * being returned as the next token. Nothing is done about
- * it since it is not valid awk, but maybe something should
- * be done anyway.
- */
-
- tokstart = lexptr;
- while (c = *lexptr++) {
- switch (c) {
- case '\\':
- if (*lexptr++ == '\0') {
- yyerror("unterminated regexp ends with \\");
- return ERROR;
- } else if (lexptr[-1] == '\n')
- goto retry;
- break;
- case '/': /* end of the regexp */
- lexptr--;
- yylval.sval = tokstart;
- return REGEXP;
- case '\n':
- lineno++;
- case '\0':
- lexptr--; /* so error messages work */
- yyerror("unterminated regexp");
- return ERROR;
- }
- }
- }
-
- if (*lexptr == '\n') {
- lexptr++;
- lineno++;
- return NEWLINE;
- }
-
- while (*lexptr == ' ' || *lexptr == '\t')
- lexptr++;
-
- tokstart = lexptr;
-
- switch (c = *lexptr++) {
- case 0:
- return 0;
-
- case '\n':
- lineno++;
- return NEWLINE;
-
- case '#': /* it's a comment */
- while (*lexptr != '\n' && *lexptr != '\0')
- lexptr++;
- goto retry;
-
- case '\\':
- if (*lexptr == '\n') {
- lineno++;
- lexptr++;
- goto retry;
- } else
- break;
- case ')':
- case ']':
- case '(':
- case '[':
- case '$':
- case ';':
- case ':':
- case '?':
-
- /*
- * set node type to ILLEGAL because the action should set it
- * to the right thing
- */
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '{':
- case ',':
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '*':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_assign_times;
- lexptr++;
- return ASSIGNOP;
- } else if (*lexptr == '*') { /* make ** and **= aliases
- * for ^ and ^= */
- if (lexptr[1] == '=') {
- yylval.nodetypeval = Node_assign_exp;
- lexptr += 2;
- return ASSIGNOP;
- } else {
- yylval.nodetypeval = Node_illegal;
- lexptr++;
- return '^';
- }
- }
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '/':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_assign_quotient;
- lexptr++;
- return ASSIGNOP;
- }
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '%':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_assign_mod;
- lexptr++;
- return ASSIGNOP;
- }
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '^':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_assign_exp;
- lexptr++;
- return ASSIGNOP;
- }
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '+':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_assign_plus;
- lexptr++;
- return ASSIGNOP;
- }
- if (*lexptr == '+') {
- yylval.nodetypeval = Node_illegal;
- lexptr++;
- return INCREMENT;
- }
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '!':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_notequal;
- lexptr++;
- return RELOP;
- }
- if (*lexptr == '~') {
- yylval.nodetypeval = Node_nomatch;
- lexptr++;
- return MATCHOP;
- }
- yylval.nodetypeval = Node_illegal;
- return c;
-
- case '<':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_leq;
- lexptr++;
- return RELOP;
- }
- yylval.nodetypeval = Node_less;
- return c;
-
- case '=':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_equal;
- lexptr++;
- return RELOP;
- }
- yylval.nodetypeval = Node_assign;
- return ASSIGNOP;
-
- case '>':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_geq;
- lexptr++;
- return RELOP;
- } else if (*lexptr == '>') {
- yylval.nodetypeval = Node_redirect_append;
- lexptr++;
- return APPEND_OP;
- }
- yylval.nodetypeval = Node_greater;
- return c;
-
- case '~':
- yylval.nodetypeval = Node_match;
- return MATCHOP;
-
- case '}':
- /*
- * Added did newline stuff. Easier than
- * hacking the grammar
- */
- if (did_newline) {
- did_newline = 0;
- return c;
- }
- did_newline++;
- --lexptr;
- return NEWLINE;
-
- case '"':
- while (*lexptr != '\0') {
- switch (*lexptr++) {
- case '\\':
- if (*lexptr++ != '\0')
- break;
- /* fall through */
- case '\n':
- yyerror("unterminated string");
- return ERROR;
- case '\"':
- /* Skip the doublequote */
- yylval.sval = tokstart + 1;
- return YSTRING;
- }
- }
- return ERROR;
-
- case '-':
- if (*lexptr == '=') {
- yylval.nodetypeval = Node_assign_minus;
- lexptr++;
- return ASSIGNOP;
- }
- if (*lexptr == '-') {
- yylval.nodetypeval = Node_illegal;
- lexptr++;
- return DECREMENT;
- }
-
- /*
- * It looks like space tab comma and newline are the legal
- * places for a UMINUS. Have we missed any?
- */
- if ((! isdigit(*lexptr) && *lexptr != '.') ||
- (lexptr > lexptr_begin + 1 &&
- ! index(" \t,\n", lexptr[-2]))) {
-
- /*
- * set node type to ILLEGAL because the action should
- * set it to the right thing
- */
- yylval.nodetypeval = Node_illegal;
- return c;
- }
- /* FALL through into number code */
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- case '.':
- /* It's a number */
- if (c == '-')
- namelen = 1;
- else
- namelen = 0;
- for (; (c = tokstart[namelen]) != '\0'; namelen++) {
- switch (c) {
- case '.':
- if (seen_point)
- goto got_number;
- ++seen_point;
- break;
- case 'e':
- case 'E':
- if (seen_e)
- goto got_number;
- ++seen_e;
- if (tokstart[namelen + 1] == '-' ||
- tokstart[namelen + 1] == '+')
- namelen++;
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- break;
- default:
- goto got_number;
- }
- }
-
-got_number:
- lexptr = tokstart + namelen;
- yylval.fval = atof(tokstart);
- return NUMBER;
-
- case '&':
- if (*lexptr == '&') {
- yylval.nodetypeval = Node_and;
- while (c = *++lexptr) {
- if (c == '#')
- while ((c = *++lexptr) != '\n'
- && c != '\0')
- ;
- if (c == '\n')
- lineno++;
- else if (!isspace(c))
- break;
- }
- return LEX_AND;
- }
- return ERROR;
-
- case '|':
- if (*lexptr == '|') {
- yylval.nodetypeval = Node_or;
- while (c = *++lexptr) {
- if (c == '#')
- while ((c = *++lexptr) != '\n'
- && c != '\0')
- ;
- if (c == '\n')
- lineno++;
- else if (!isspace(c))
- break;
- }
- return LEX_OR;
- }
- yylval.nodetypeval = Node_illegal;
- return c;
- }
-
- if (c != '_' && !isalpha(c)) {
- yyerror("Invalid char '%c' in expression\n", c);
- return ERROR;
- }
-
- /* it's some type of name-type-thing. Find its length */
- for (namelen = 0; is_identchar(tokstart[namelen]); namelen++)
- /* null */ ;
- emalloc(tokkey, char *, namelen+1, "yylex");
- (void) strncpy (tokkey, tokstart, namelen);
- tokkey[namelen] = '\0';
-
- /* See if it is a special token. */
- low = 0;
- high = (sizeof (tokentab) / sizeof (tokentab[0])) - 1;
- while (low <= high) {
- int i, c;
-
- mid = (low + high) / 2;
-
- compare:
- c = *tokstart - tokentab[mid].operator[0];
- i = c ? c : strcmp (tokkey, tokentab[mid].operator);
-
- if (i < 0) { /* token < mid */
- high = mid - 1;
- } else if (i > 0) { /* token > mid */
- low = mid + 1;
- } else {
- lexptr = tokstart + namelen;
- if (strict && tokentab[mid].nostrict)
- break;
- if (tokentab[mid].class == LEX_BUILTIN)
- yylval.ptrval = tokentab[mid].ptr;
- else
- yylval.nodetypeval = tokentab[mid].value;
- return tokentab[mid].class;
- }
- }
-
- /* It's a name. See how long it is. */
- yylval.sval = tokkey;
- lexptr = tokstart + namelen;
- if (*lexptr == '(')
- return FUNC_CALL;
- else
- return NAME;
-}
-
-#ifndef DEFPATH
-#ifdef MSDOS
-#define DEFPATH "."
-#define ENVSEP ';'
-#else
-#define DEFPATH ".:/usr/lib/awk:/usr/local/lib/awk"
-#define ENVSEP ':'
-#endif
-#endif
-
-static FILE *
-pathopen (file)
-char *file;
-{
- static char *savepath = DEFPATH;
- static int first = 1;
- char *awkpath, *cp;
- char trypath[BUFSIZ];
- FILE *fp;
- extern int debugging;
-
- if (strcmp (file, "-") == 0)
- return (stdin);
-
- if (strict)
- return (fopen (file, "r"));
-
- if (first) {
- first = 0;
- if ((awkpath = getenv ("AWKPATH")) != NULL && *awkpath)
- savepath = awkpath; /* used for restarting */
-#ifdef MSDOS
- else if ((awkpath = getenv ("INIT")) != NULL && *awkpath)
- savepath = awkpath; /* MSC 5.1 users may prefer */
- /* to use INIT */
-#endif
- }
- awkpath = savepath;
-
- /* some kind of path name, no search */
-#ifndef MSDOS
- if (index (file, '/') != NULL)
-#else
- if (index (file, '/') != NULL || index (file, '\\') != NULL
- || index (file, ':') != NULL)
-#endif
- return (fdopen(devopen (file, "r"), "r"));
-
- do {
- /* this should take into account limits on size of trypath */
- for (cp = trypath; *awkpath && *awkpath != ENVSEP; )
- *cp++ = *awkpath++;
- *cp++ = '/';
- *cp = '\0'; /* clear left over junk */
- strcat (cp, file);
- if ((fp = fdopen(devopen (trypath, "r"), "r")) != NULL)
- return (fp);
-
- /* no luck, keep going */
- awkpath++; /* skip colon */
- } while (*awkpath);
- return (NULL);
-}
-
-static NODE *
-node_common(op)
-NODETYPE op;
-{
- register NODE *r;
- extern int numfiles;
- extern int tempsource;
- extern char **sourcefile;
-
- r = newnode(op);
- r->source_line = lineno;
- if (numfiles > 1 && !tempsource)
- r->source_file = sourcefile[curinfile];
- else
- r->source_file = NULL;
- return r;
-}
-
-/*
- * This allocates a node with defined lnode and rnode.
- * This should only be used by yyparse+co while reading in the program
- */
-NODE *
-node(left, op, right)
-NODE *left, *right;
-NODETYPE op;
-{
- register NODE *r;
-
- r = node_common(op);
- r->lnode = left;
- r->rnode = right;
- return r;
-}
-
-/*
- * This allocates a node with defined subnode and proc
- * Otherwise like node()
- */
-static NODE *
-snode(subn, op, procp)
-NODETYPE op;
-NODE *(*procp) ();
-NODE *subn;
-{
- register NODE *r;
-
- r = node_common(op);
- r->subnode = subn;
- r->proc = procp;
- return r;
-}
-
-/*
- * This allocates a Node_line_range node with defined condpair and
- * zeroes the trigger word to avoid the temptation of assuming that calling
- * 'node( foo, Node_line_range, 0)' will properly initialize 'triggered'.
- */
-/* Otherwise like node() */
-static NODE *
-mkrangenode(cpair)
-NODE *cpair;
-{
- register NODE *r;
-
- r = newnode(Node_line_range);
- r->condpair = cpair;
- r->triggered = 0;
- return r;
-}
-
-/* Build a for loop */
-static NODE *
-make_for_loop(init, cond, incr)
-NODE *init, *cond, *incr;
-{
- register FOR_LOOP_HEADER *r;
- NODE *n;
-
- emalloc(r, FOR_LOOP_HEADER *, sizeof(FOR_LOOP_HEADER), "make_for_loop");
- n = newnode(Node_illegal);
- r->init = init;
- r->cond = cond;
- r->incr = incr;
- n->sub.nodep.r.hd = r;
- return n;
-}
-
-/*
- * Install a name in the hash table specified, even if it is already there.
- * Name stops with first non alphanumeric. Caller must check against
- * redefinition if that is desired.
- */
-NODE *
-install(table, name, value)
-NODE **table;
-char *name;
-NODE *value;
-{
- register NODE *hp;
- register int len, bucket;
- register char *p;
-
- len = 0;
- p = name;
- while (is_identchar(*p))
- p++;
- len = p - name;
-
- hp = newnode(Node_hashnode);
- bucket = hashf(name, len, HASHSIZE);
- hp->hnext = table[bucket];
- table[bucket] = hp;
- hp->hlength = len;
- hp->hvalue = value;
- emalloc(hp->hname, char *, len + 1, "install");
- bcopy(name, hp->hname, len);
- hp->hname[len] = '\0';
- hp->hvalue->varname = hp->hname;
- return hp->hvalue;
-}
-
-/*
- * find the most recent hash node for name name (ending with first
- * non-identifier char) installed by install
- */
-NODE *
-lookup(table, name)
-NODE **table;
-char *name;
-{
- register char *bp;
- register NODE *bucket;
- register int len;
-
- for (bp = name; is_identchar(*bp); bp++)
- ;
- len = bp - name;
- bucket = table[hashf(name, len, HASHSIZE)];
- while (bucket) {
- if (bucket->hlength == len && STREQN(bucket->hname, name, len))
- return bucket->hvalue;
- bucket = bucket->hnext;
- }
- return NULL;
-}
-
-#define HASHSTEP(old, c) ((old << 1) + c)
-#define MAKE_POS(v) (v & ~0x80000000) /* make number positive */
-
-/*
- * return hash function on name.
- */
-static int
-hashf(name, len, hashsize)
-register char *name;
-register int len;
-int hashsize;
-{
- register int r = 0;
-
- while (len--)
- r = HASHSTEP(r, *name++);
-
- r = MAKE_POS(r) % hashsize;
- return r;
-}
-
-/*
- * Add new to the rightmost branch of LIST. This uses n^2 time, but doesn't
- * get used enough to make optimizing worth it. . .
- */
-/* You don't believe me? Profile it yourself! */
-static NODE *
-append_right(list, new)
-NODE *list, *new;
-
-{
- register NODE *oldlist;
-
- oldlist = list;
- while (list->rnode != NULL)
- list = list->rnode;
- list->rnode = new;
- return oldlist;
-}
-
-/*
- * check if name is already installed; if so, it had better have Null value,
- * in which case def is added as the value. Otherwise, install name with def
- * as value.
- */
-static void
-func_install(params, def)
-NODE *params;
-NODE *def;
-{
- NODE *r;
-
- pop_params(params->rnode);
- pop_var(params, 0);
- r = lookup(variables, params->param);
- if (r != NULL) {
- fatal("function name `%s' previously defined", params->param);
- } else
- (void) install(variables, params->param,
- node(params, Node_func, def));
-}
-
-static void
-pop_var(np, freeit)
-NODE *np;
-int freeit;
-{
- register char *bp;
- register NODE *bucket, **save;
- register int len;
- char *name;
-
- name = np->param;
- for (bp = name; is_identchar(*bp); bp++)
- ;
- len = bp - name;
- save = &(variables[hashf(name, len, HASHSIZE)]);
- for (bucket = *save; bucket; bucket = bucket->hnext) {
- if (len == bucket->hlength && STREQN(bucket->hname, name, len)) {
- *save = bucket->hnext;
- freenode(bucket);
- free(bucket->hname);
- if (freeit)
- free(np->param);
- return;
- }
- save = &(bucket->hnext);
- }
-}
-
-static void
-pop_params(params)
-NODE *params;
-{
- register NODE *np;
-
- for (np = params; np != NULL; np = np->rnode)
- pop_var(np, 1);
-}
-
-static NODE *
-make_param(name)
-char *name;
-{
- NODE *r;
-
- r = newnode(Node_param_list);
- r->param = name;
- r->rnode = NULL;
- r->param_cnt = param_counter++;
- return (install(variables, name, r));
-}
-
-/* Name points to a variable name. Make sure its in the symbol table */
-NODE *
-variable(name)
-char *name;
-{
- register NODE *r;
-
- if ((r = lookup(variables, name)) == NULL)
- r = install(variables, name,
- node(Nnull_string, Node_var, (NODE *) NULL));
- return r;
-}
diff --git a/awk.y b/awk.y
index 854bbec5..32093e7f 100644
--- a/awk.y
+++ b/awk.y
@@ -1,176 +1,5 @@
/*
- * gawk -- GNU version of awk
- * awk.y --- yacc/bison parser for awk
- *
- * $Log: awk.y,v $
- * Revision 1.35 89/03/31 13:24:41 david
- * GNU license; MSDOS support; YYDEBUG inside #ifdef DEBUG
- *
- * Revision 1.34 89/03/30 20:55:55 david
- * avoid constructing lists in the case of one instance of a rule, statement
- * or BEGIN or END clause
- *
- * Revision 1.33 89/03/29 21:53:26 david
- * wierd: this stuff worked just fine with cc, but I had to add a lot
- * of $$ = $1 lines for it to work with gcc -- I thought that $$ = $1
- * was the default action
- *
- * Revision 1.32 89/03/29 14:16:08 david
- * grammar fix
- * delinting
- * some code movement -- devopen to awk7.c, variable() to here
- * change interface to devopen()
- *
- * Revision 1.31 89/03/24 21:08:13 david
- * STREQN takes care of extra test
- *
- * Revision 1.30 89/03/24 15:52:15 david
- * add getline production to rexp
- * merge HASHNODE with NODE
- *
- * Revision 1.29 89/03/21 11:57:49 david
- * substantial cleanup and code movement from awk1.c
- * this and previous two changes represent a major reworking of the grammar
- * to fix a number of bugs; two general problems were in I/O redirection
- * specifications and in the handling of whitespace -- the general strategies
- * in fixing these problems were to define some more specific grammatical
- * elements (e.g. simp_exp and rexp) and use these in particular places;
- * also got rid of want_concat and want_redirect kludges
- *
- * Revision 1.28 89/03/15 21:58:01 david
- * more grammar changes (explanation to come) plus changes from Arnold:
- * new case stuff added and old removed
- * tolower and toupper added
- * fix vararg stuff
- * add new escape sequences
- * fix bug in reporting unterminated regexps
- * fix to allow -f -
- * /dev/fd/N etc special files added
- *
- * Revision 1.27 89/03/02 21:10:09 david
- * intermediate step in major revision -- description later
- *
- * Revision 1.26 89/01/18 20:39:58 david
- * allow regexp && regexp as pattern and get rid of remaining reduce/reduce conflicts
- *
- * Revision 1.25 89/01/04 21:53:21 david
- * purge obstack remnants
- *
- * Revision 1.24 88/12/15 12:52:58 david
- * changes from Jay to get rid of some reduce/reduce conflicts - some remain
- *
- * Revision 1.23 88/12/07 19:59:25 david
- * changes for incorporating source filename in error messages
- *
- * Revision 1.22 88/11/23 21:37:24 david
- * Arnold: refinements of AWKPATH code
- *
- * Revision 1.21 88/11/22 13:46:45 david
- * Arnold: changes for case-insensitive matching
- *
- * Revision 1.20 88/11/15 10:13:37 david
- * Arnold: allow multiple -f options and search in directories for awk libraries,
- * directories specified by AWKPATH env. variable; cleanupo of comments and
- * #includes
- *
- * Revision 1.19 88/11/14 21:51:30 david
- * Arnold: added error message for BEGIN or END without any action at all;
- * unlink temporary source file right after creation so it goes away on bomb
- *
- * Revision 1.18 88/10/19 22:00:56 david
- * generalize (and correct) what pattern can be in pattern {action}; this
- * introduces quite a few new conflicts that should be checked thoroughly
- * at some point, but they don't seem to do any harm at first glance
- * replace malloc with emalloc
- *
- * Revision 1.17 88/10/17 19:52:01 david
- * Arnold: cleanup, purge FAST
- *
- * Revision 1.16 88/10/13 22:02:16 david
- * cleanup of yyerror and other error messages
- *
- * Revision 1.15 88/10/06 23:24:57 david
- * accept var space ++var
- * accept underscore as first character of a variable name
- *
- * Revision 1.14 88/06/13 18:01:46 david
- * delete \a (change from Arnold)
- *
- * Revision 1.13 88/06/08 00:29:42 david
- * better attempt at keeping track of line numbers
- * change grammar to properly handle newlines after && or ||
- *
- * Revision 1.12 88/06/07 23:39:02 david
- * little delint
- *
- * Revision 1.11 88/06/05 22:17:40 david
- * make_name() becomes make_param() (again!)
- * func_level goes away, param_counter makes entrance
- *
- * Revision 1.10 88/05/30 09:49:02 david
- * obstack_free was being called at end of function definition, freeing
- * memory that might be part of global variables referenced only inside
- * functions; commented out for now, will have to selectively free later.
- * cleanup: regexp now returns a NODE *
- *
- * Revision 1.9 88/05/27 11:04:53 david
- * added print[f] '(' ... ')' (optional parentheses)
- * for some reason want_redirect wasn't getting set for PRINT, so I set it in
- * yylex()
- *
- * Revision 1.8 88/05/26 22:52:14 david
- * fixed cmd | getline
- * added compound patterns (they got lost somewhere along the line)
- * fixed error message in yylex()
- * added null statement
- *
- * Revision 1.7 88/05/13 22:05:29 david
- * moved BEGIN and END block merging here
- * BEGIN, END and function defs. are no longer incorporated into main parse tree
- * fixed command | getline
- * fixed function install and definition
- *
- * Revision 1.6 88/05/09 17:47:50 david
- * Arnold's coded binary search
- *
- * Revision 1.5 88/05/04 12:31:13 david
- * be a bit more careful about types
- * make_for_loop() now returns a NODE *
- * keyword search now uses bsearch() -- need a public domain version of this
- * added back stuff in yylex() that got lost somewhere along the line
- * malloc() tokens in yylex() since they were previously just pointers into
- * current line that got overwritten by the next fgets() -- these need to get
- * freed at some point
- * fixed backslash line continuation interaction with CONCAT
- *
- * Revision 1.4 88/04/14 17:03:51 david
- * reinstalled a fix to do with line continuation
- *
- * Revision 1.3 88/04/14 14:41:01 david
- * Arnold's changes to yylex to read program from a file
- *
- * Revision 1.5 88/03/18 21:00:07 david
- * Baseline -- hoefully all the functionality of the new awk added.
- * Just debugging and tuning to do.
- *
- * Revision 1.4 87/11/19 14:37:20 david
- * added a bunch of ew builtin functions
- * added new rules for getline to provide new functionality
- * minor cleanup of redirection handling
- * generalized make_param into make_name
- *
- * Revision 1.3 87/11/09 21:22:33 david
- * added macinery for user-defined functions (including return)
- * added delete, do-while and system
- * reformatted and revised grammer to improve error-handling
- * changes to yyerror to give improved error messages
- *
- * Revision 1.2 87/10/29 21:33:28 david
- * added test for membership in an array, as in: if ("yes" in answers) ...
- *
- * Revision 1.1 87/10/27 15:23:21 david
- * Initial revision
- *
+ * awk.y --- yacc/bison parser
*/
/*
@@ -198,10 +27,16 @@
#ifdef DEBUG
#define YYDEBUG 12
#endif
-#define YYIMPROVE
#include "awk.h"
+/*
+ * This line is necessary since the Bison parser skeleton uses bcopy.
+ * Systems without memcpy should use -DMEMCPY_MISSING, per the Makefile.
+ * It should not hurt anything if Yacc is being used instead of Bison.
+ */
+#define bcopy(s,d,n) memcpy((d),(s),(n))
+
extern void msg();
extern struct re_pattern_buffer *mk_re_parse();
@@ -223,17 +58,20 @@ static int yylex ();
static void yyerror();
static int want_regexp; /* lexical scanning kludge */
+static int want_assign; /* lexical scanning kludge */
+static int can_return; /* lexical scanning kludge */
+static int io_allowed = 1; /* lexical scanning kludge */
static int lineno = 1; /* for error msgs */
static char *lexptr; /* pointer to next char during parsing */
static char *lexptr_begin; /* keep track of where we were for error msgs */
static int curinfile = -1; /* index into sourcefiles[] */
+static int param_counter;
NODE *variables[HASHSIZE];
extern int errcount;
extern NODE *begin_block;
extern NODE *end_block;
-extern int param_counter;
%}
%union {
@@ -247,28 +85,28 @@ extern int param_counter;
%type <nodeval> function_prologue function_body
%type <nodeval> rexp exp start program rule simp_exp
-%type <nodeval> simp_pattern pattern
+%type <nodeval> pattern
%type <nodeval> action variable param_list
%type <nodeval> rexpression_list opt_rexpression_list
%type <nodeval> expression_list opt_expression_list
%type <nodeval> statements statement if_statement opt_param_list
-%type <nodeval> opt_exp opt_variable regexp p_regexp
+%type <nodeval> opt_exp opt_variable regexp
%type <nodeval> input_redir output_redir
%type <nodetypeval> r_paren comma nls opt_nls print
%type <sval> func_name
-%token <sval> FUNC_CALL NAME REGEXP YSTRING
-%token <lval> ERROR INCDEC
-%token <fval> NUMBER
+%token <sval> FUNC_CALL NAME REGEXP
+%token <lval> ERROR
+%token <nodeval> NUMBER YSTRING
%token <nodetypeval> RELOP APPEND_OP
%token <nodetypeval> ASSIGNOP MATCHOP NEWLINE CONCAT_OP
%token <nodetypeval> LEX_BEGIN LEX_END LEX_IF LEX_ELSE LEX_RETURN LEX_DELETE
%token <nodetypeval> LEX_WHILE LEX_DO LEX_FOR LEX_BREAK LEX_CONTINUE
%token <nodetypeval> LEX_PRINT LEX_PRINTF LEX_NEXT LEX_EXIT LEX_FUNCTION
-%token <nodetypeval> LEX_GETLINE LEX_SUB LEX_MATCH
+%token <nodetypeval> LEX_GETLINE
%token <nodetypeval> LEX_IN
%token <lval> LEX_AND LEX_OR INCREMENT DECREMENT
-%token <ptrval> LEX_BUILTIN
+%token <ptrval> LEX_BUILTIN LEX_LENGTH
/* these are just yylval numbers */
@@ -278,26 +116,24 @@ extern int param_counter;
%left LEX_OR
%left LEX_AND
%left LEX_GETLINE
-%left NUMBER
-%left FUNC_CALL LEX_SUB LEX_BUILTIN LEX_MATCH
+%nonassoc LEX_IN
+%left FUNC_CALL LEX_BUILTIN LEX_LENGTH
%nonassoc MATCHOP
%nonassoc RELOP '<' '>' '|' APPEND_OP
-%left NAME
-%nonassoc LEX_IN
-%left YSTRING
-%left '(' ')'
%left CONCAT_OP
+%left YSTRING NUMBER
%left '+' '-'
%left '*' '/' '%'
%right '!' UNARY
%right '^'
%left INCREMENT DECREMENT
%left '$'
+%left '(' ')'
%%
start
- : opt_nls program
+ : opt_nls program opt_nls
{ expression_value = $2; }
;
@@ -331,32 +167,36 @@ program
;
rule
- : LEX_BEGIN action
+ : LEX_BEGIN { io_allowed = 0; }
+ action
{
if (begin_block) {
if (begin_block->type != Node_rule_list)
begin_block = node(begin_block, Node_rule_list,
(NODE *)NULL);
append_right (begin_block, node(
- node((NODE *)NULL, Node_rule_node, $2),
+ node((NODE *)NULL, Node_rule_node, $3),
Node_rule_list, (NODE *)NULL) );
} else
- begin_block = node((NODE *)NULL, Node_rule_node, $2);
+ begin_block = node((NODE *)NULL, Node_rule_node, $3);
$$ = NULL;
+ io_allowed = 1;
yyerrok;
}
- | LEX_END action
+ | LEX_END { io_allowed = 0; }
+ action
{
if (end_block) {
if (end_block->type != Node_rule_list)
end_block = node(end_block, Node_rule_list,
(NODE *)NULL);
append_right (end_block, node(
- node((NODE *)NULL, Node_rule_node, $2),
+ node((NODE *)NULL, Node_rule_node, $3),
Node_rule_list, (NODE *)NULL));
} else
- end_block = node((NODE *)NULL, Node_rule_node, $2);
+ end_block = node((NODE *)NULL, Node_rule_node, $3);
$$ = NULL;
+ io_allowed = 1;
yyerrok;
}
| LEX_BEGIN statement_term
@@ -400,46 +240,26 @@ function_prologue
func_name '(' opt_param_list r_paren opt_nls
{
$$ = append_right(make_param($3), $5);
+ can_return = 1;
}
;
function_body
: l_brace statements r_brace
- { $$ = $2; }
+ {
+ $$ = $2;
+ can_return = 0;
+ }
;
-simp_pattern
- : exp
- { $$ = $1; }
- | p_regexp
- { $$ = $1; }
- | p_regexp LEX_AND simp_pattern
- { $$ = node ($1, Node_and, $3); }
- | p_regexp LEX_OR simp_pattern
- { $$ = node ($1, Node_or, $3); }
- | '!' p_regexp %prec UNARY
- { $$ = node ($2, Node_not,(NODE *) NULL); }
- | '(' p_regexp r_paren
- { $$ = $2; }
- ;
-
pattern
- : simp_pattern
+ : exp
{ $$ = $1; }
- | simp_pattern comma simp_pattern
+ | exp comma exp
{ $$ = mkrangenode ( node($1, Node_cond_pair, $3) ); }
;
-p_regexp
- : regexp
- {
- $$ = node(
- node(make_number((AWKNUM)0),Node_field_spec,(NODE*)NULL),
- Node_match, $1);
- }
- ;
-
regexp
/*
* In this rule, want_regexp tells yylex that the next thing
@@ -472,7 +292,7 @@ statements
{ $$ = $1; }
| statements statement
{
- if ($1->type != Node_statement_list)
+ if ($1 == NULL || $1->type != Node_statement_list)
$1 = node($1, Node_statement_list,(NODE *)NULL);
$$ = append_right($1,
node( $2, Node_statement_list, (NODE *)NULL));
@@ -495,6 +315,8 @@ statement_term
statement
: semi opt_nls
{ $$ = NULL; }
+ | l_brace r_brace
+ { $$ = NULL; }
| l_brace statements r_brace
{ $$ = $2; }
| if_statement
@@ -527,12 +349,16 @@ statement
{ $$ = node ($3, $1, $5); }
| print opt_rexpression_list output_redir statement_term
{ $$ = node ($2, $1, $3); }
- | LEX_NEXT statement_term
+ | LEX_NEXT
+ { if (! io_allowed) yyerror("next used in BEGIN or END action"); }
+ statement_term
{ $$ = node ((NODE *)NULL, Node_K_next, (NODE *)NULL); }
| LEX_EXIT opt_exp statement_term
{ $$ = node ($2, Node_K_exit, (NODE *)NULL); }
- | LEX_RETURN opt_exp statement_term
- { $$ = node ($2, Node_K_return, (NODE *)NULL); }
+ | LEX_RETURN
+ { if (! can_return) yyerror("return used outside function context"); }
+ opt_exp statement_term
+ { $$ = node ($3, Node_K_return, (NODE *)NULL); }
| LEX_DELETE NAME '[' expression_list ']' statement_term
{ $$ = node (variable($2), Node_K_delete, $4); }
| exp statement_term
@@ -582,11 +408,11 @@ input_redir
output_redir
: /* empty */
{ $$ = NULL; }
- | '>' simp_exp
+ | '>' exp
{ $$ = node ($2, Node_redirect_output, (NODE *)NULL); }
- | APPEND_OP simp_exp
+ | APPEND_OP exp
{ $$ = node ($2, Node_redirect_append, (NODE *)NULL); }
- | '|' simp_exp
+ | '|' exp
{ $$ = node ($2, Node_redirect_pipe, (NODE *)NULL); }
;
@@ -671,8 +497,10 @@ expression_list
;
/* Expressions, not including the comma operator. */
-exp : variable ASSIGNOP exp
- { $$ = node ($1, $2, $3); }
+exp : variable ASSIGNOP
+ { want_assign = 0; }
+ exp
+ { $$ = node ($1, $2, $4); }
| '(' expression_list r_paren LEX_IN NAME
{ $$ = node (variable($5), Node_in_array, $2); }
| exp '|' LEX_GETLINE opt_variable
@@ -682,16 +510,23 @@ exp : variable ASSIGNOP exp
}
| LEX_GETLINE opt_variable input_redir
{
+ /* "too painful to do right" */
+ /*
+ if (! io_allowed && $3 == NULL)
+ yyerror("non-redirected getline illegal inside BEGIN or END action");
+ */
$$ = node ($2, Node_K_getline, $3);
}
| exp LEX_AND exp
{ $$ = node ($1, Node_and, $3); }
| exp LEX_OR exp
{ $$ = node ($1, Node_or, $3); }
- | exp MATCHOP regexp
- { $$ = node ($1, $2, $3); }
| exp MATCHOP exp
{ $$ = node ($1, $2, $3); }
+ | regexp
+ { $$ = $1; }
+ | '!' regexp %prec UNARY
+ { $$ = node((NODE *) NULL, Node_nomatch, $2); }
| exp LEX_IN NAME
{ $$ = node (variable($3), Node_in_array, $1); }
| exp RELOP exp
@@ -702,25 +537,34 @@ exp : variable ASSIGNOP exp
{ $$ = node ($1, Node_greater, $3); }
| exp '?' exp ':' exp
{ $$ = node($1, Node_cond_exp, node($3, Node_if_branches, $5));}
- | exp exp %prec CONCAT_OP
- { $$ = node ($1, Node_concat, $2); }
| simp_exp
{ $$ = $1; }
+ | exp exp %prec CONCAT_OP
+ { $$ = node ($1, Node_concat, $2); }
;
rexp
- : variable ASSIGNOP rexp
- { $$ = node ($1, $2, $3); }
+ : variable ASSIGNOP
+ { want_assign = 0; }
+ rexp
+ { $$ = node ($1, $2, $4); }
| rexp LEX_AND rexp
{ $$ = node ($1, Node_and, $3); }
| rexp LEX_OR rexp
{ $$ = node ($1, Node_or, $3); }
| LEX_GETLINE opt_variable input_redir
{
+ /* "too painful to do right" */
+ /*
+ if (! io_allowed && $3 == NULL)
+ yyerror("non-redirected getline illegal inside BEGIN or END action");
+ */
$$ = node ($2, Node_K_getline, $3);
}
- | rexp MATCHOP regexp
- { $$ = node ($1, $2, $3); }
+ | regexp
+ { $$ = $1; }
+ | '!' regexp %prec UNARY
+ { $$ = node((NODE *) NULL, Node_nomatch, $2); }
| rexp MATCHOP rexp
{ $$ = node ($1, $2, $3); }
| rexp LEX_IN NAME
@@ -729,10 +573,10 @@ rexp
{ $$ = node ($1, $2, $3); }
| rexp '?' rexp ':' rexp
{ $$ = node($1, Node_cond_exp, node($3, Node_if_branches, $5));}
- | rexp rexp %prec CONCAT_OP
- { $$ = node ($1, Node_concat, $2); }
| simp_exp
{ $$ = $1; }
+ | rexp rexp %prec CONCAT_OP
+ { $$ = node ($1, Node_concat, $2); }
;
simp_exp
@@ -742,16 +586,10 @@ simp_exp
{ $$ = $2; }
| LEX_BUILTIN '(' opt_expression_list r_paren
{ $$ = snode ($3, Node_builtin, $1); }
- | LEX_BUILTIN
+ | LEX_LENGTH '(' opt_expression_list r_paren
+ { $$ = snode ($3, Node_builtin, $1); }
+ | LEX_LENGTH
{ $$ = snode ((NODE *)NULL, Node_builtin, $1); }
- | LEX_SUB '(' regexp comma expression_list r_paren
- { $$ = node($5, $1, $3); }
- | LEX_SUB '(' exp comma expression_list r_paren
- { $$ = node($5, $1, $3); }
- | LEX_MATCH '(' exp comma regexp r_paren
- { $$ = node($3, $1, $5); }
- | LEX_MATCH '(' exp comma exp r_paren
- { $$ = node($3, $1, $5); }
| FUNC_CALL '(' opt_expression_list r_paren
{
$$ = node ($3, Node_func_call, make_string($1, strlen($1)));
@@ -767,9 +605,9 @@ simp_exp
| variable
{ $$ = $1; }
| NUMBER
- { $$ = make_number ($1); }
+ { $$ = $1; }
| YSTRING
- { $$ = make_string ($1, -1); }
+ { $$ = $1; }
/* Binary operators in order of decreasing precedence. */
| simp_exp '^' simp_exp
@@ -799,11 +637,11 @@ opt_variable
variable
: NAME
- { $$ = variable ($1); }
+ { want_assign = 1; $$ = variable ($1); }
| NAME '[' expression_list ']'
- { $$ = node (variable($1), Node_subscript, $3); }
+ { want_assign = 1; $$ = node (variable($1), Node_subscript, $3); }
| '$' simp_exp
- { $$ = node ($2, Node_field_spec, (NODE *)NULL); }
+ { want_assign = 1; $$ = node ($2, Node_field_spec, (NODE *)NULL); }
;
l_brace
@@ -840,16 +678,13 @@ struct token {
NODE *(*ptr) (); /* function that implements this keyword */
};
-#ifndef NULL
-#define NULL 0
-#endif
-
extern NODE
*do_exp(), *do_getline(), *do_index(), *do_length(),
*do_sqrt(), *do_log(), *do_sprintf(), *do_substr(),
*do_split(), *do_system(), *do_int(), *do_close(),
*do_atan2(), *do_sin(), *do_cos(), *do_rand(),
- *do_srand(), *do_match(), *do_tolower(), *do_toupper();
+ *do_srand(), *do_match(), *do_tolower(), *do_toupper(),
+ *do_sub(), *do_gsub();
/* Special functions for debugging */
#ifdef DEBUG
@@ -878,14 +713,14 @@ static struct token tokentab[] = {
{ "func", Node_K_function, LEX_FUNCTION, 0, 0 },
{ "function", Node_K_function, LEX_FUNCTION, 0, 0 },
{ "getline", Node_K_getline, LEX_GETLINE, 0, 0 },
- { "gsub", Node_gsub, LEX_SUB, 0, 0 },
+ { "gsub", Node_builtin, LEX_BUILTIN, 0, do_gsub },
{ "if", Node_K_if, LEX_IF, 0, 0 },
{ "in", Node_illegal, LEX_IN, 0, 0 },
{ "index", Node_builtin, LEX_BUILTIN, 0, do_index },
{ "int", Node_builtin, LEX_BUILTIN, 0, do_int },
- { "length", Node_builtin, LEX_BUILTIN, 0, do_length },
+ { "length", Node_builtin, LEX_LENGTH, 0, do_length },
{ "log", Node_builtin, LEX_BUILTIN, 0, do_log },
- { "match", Node_K_match, LEX_MATCH, 0, 0 },
+ { "match", Node_builtin, LEX_BUILTIN, 0, do_match },
{ "next", Node_K_next, LEX_NEXT, 0, 0 },
{ "print", Node_K_print, LEX_PRINT, 0, 0 },
{ "printf", Node_K_printf, LEX_PRINTF, 0, 0 },
@@ -899,14 +734,16 @@ static struct token tokentab[] = {
{ "sprintf", Node_builtin, LEX_BUILTIN, 0, do_sprintf },
{ "sqrt", Node_builtin, LEX_BUILTIN, 0, do_sqrt },
{ "srand", Node_builtin, LEX_BUILTIN, 0, do_srand },
- { "sub", Node_sub, LEX_SUB, 0, 0 },
+ { "sub", Node_builtin, LEX_BUILTIN, 0, do_sub },
{ "substr", Node_builtin, LEX_BUILTIN, 0, do_substr },
{ "system", Node_builtin, LEX_BUILTIN, 0, do_system },
- { "tolower", Node_builtin, LEX_BUILTIN, 1, do_tolower },
- { "toupper", Node_builtin, LEX_BUILTIN, 1, do_toupper },
+ { "tolower", Node_builtin, LEX_BUILTIN, 0, do_tolower },
+ { "toupper", Node_builtin, LEX_BUILTIN, 0, do_toupper },
{ "while", Node_K_while, LEX_WHILE, 0, 0 },
};
+static char *token_start;
+
/* VARARGS0 */
static void
yyerror(va_alist)
@@ -914,64 +751,40 @@ va_dcl
{
va_list args;
char *mesg;
- char *a1;
register char *ptr, *beg;
- static int list = 0;
char *scan;
errcount++;
va_start(args);
mesg = va_arg(args, char *);
- if (! list)
- a1 = va_arg(args, char *);
va_end(args);
- if (mesg || !list) {
- /* Find the current line in the input file */
- if (!lexptr) {
- beg = "(END OF FILE)";
- ptr = beg + 13;
- } else {
- if (*lexptr == '\n' && lexptr != lexptr_begin)
- --lexptr;
- for (beg = lexptr; beg != lexptr_begin && *beg != '\n'; --beg)
- ;
- /* NL isn't guaranteed */
- for (ptr = lexptr; *ptr && *ptr != '\n'; ptr++)
- ;
- if (beg != lexptr_begin)
- beg++;
- }
- msg("syntax error near line %d:\n%.*s", lineno, ptr - beg, beg);
- scan = beg;
- while (scan <= lexptr)
- if (*scan++ == '\t')
- putc('\t', stderr);
- else
- putc(' ', stderr);
- putc('^', stderr);
- putc(' ', stderr);
- if (mesg) {
- vfprintf(stderr, mesg, args);
- putc('\n', stderr);
- exit(1);
- } else {
- if (a1) {
- fputs("expecting: ", stderr);
- fputs(a1, stderr);
- list = 1;
- return;
- }
- }
- return;
- }
- if (a1) {
- fputs(" or ", stderr);
- fputs(a1, stderr);
- putc('\n', stderr);
- return;
+ /* Find the current line in the input file */
+ if (! lexptr) {
+ beg = "(END OF FILE)";
+ ptr = beg + 13;
+ } else {
+ if (*lexptr == '\n' && lexptr != lexptr_begin)
+ --lexptr;
+ for (beg = lexptr; beg != lexptr_begin && *beg != '\n'; --beg)
+ ;
+ /* NL isn't guaranteed */
+ for (ptr = lexptr; *ptr && *ptr != '\n'; ptr++)
+ ;
+ if (beg != lexptr_begin)
+ beg++;
}
+ msg("syntax error near line %d:\n%.*s", lineno, ptr - beg, beg);
+ scan = beg;
+ while (scan < token_start)
+ if (*scan++ == '\t')
+ putc('\t', stderr);
+ else
+ putc(' ', stderr);
+ putc('^', stderr);
+ putc(' ', stderr);
+ vfprintf(stderr, mesg, args);
putc('\n', stderr);
- list = 0;
+ exit(1);
}
/*
@@ -989,19 +802,17 @@ va_dcl
* zeros. A value of 0 does not mean end of string.
*/
-static int
+int
parse_escape(string_ptr)
char **string_ptr;
{
register int c = *(*string_ptr)++;
register int i;
+ register int count = 0;
switch (c) {
case 'a':
- if (strict)
- goto def;
- else
- return BELL;
+ return BELL;
case 'b':
return '\b';
case 'f':
@@ -1013,15 +824,12 @@ char **string_ptr;
case 't':
return '\t';
case 'v':
- if (strict)
- goto def;
- else
- return '\v';
+ return '\v';
case '\n':
return -2;
case 0:
(*string_ptr)--;
- return 0;
+ return -1;
case '0':
case '1':
case '2':
@@ -1030,25 +838,19 @@ char **string_ptr;
case '5':
case '6':
case '7':
- {
- register int i = c - '0';
- register int count = 0;
-
- while (++count < 3) {
- if ((c = *(*string_ptr)++) >= '0' && c <= '7') {
- i *= 8;
- i += c - '0';
- } else {
- (*string_ptr)--;
- break;
- }
+ i = c - '0';
+ count = 0;
+ while (++count < 3) {
+ if ((c = *(*string_ptr)++) >= '0' && c <= '7') {
+ i *= 8;
+ i += c - '0';
+ } else {
+ (*string_ptr)--;
+ break;
}
- return i;
}
+ return i;
case 'x':
- if (strict)
- goto def;
-
i = 0;
while (1) {
if (isxdigit((c = *(*string_ptr)++))) {
@@ -1065,7 +867,6 @@ char **string_ptr;
}
return i;
default:
- def:
return c;
}
}
@@ -1089,6 +890,7 @@ yylex()
* hacking the grammar. */
int seen_e = 0; /* These are for numbers */
int seen_point = 0;
+ int esc_seen;
extern char **sourcefile;
extern int tempsource, numfiles;
static int file_opened = 0;
@@ -1114,7 +916,7 @@ yylex()
if ((fin = pathopen (sourcefile[++curinfile])) == NULL)
fatal("cannot open `%s' for reading (%s)",
sourcefile[curinfile],
- sys_errlist[errno]);
+ strerror(errno));
*(lexptr = cbuf) = '\0';
/*
* immediately unlink the tempfile so that it will
@@ -1136,19 +938,18 @@ retry:
lexptr = lexptr_begin = cbuf;
if (want_regexp) {
- want_regexp = 0;
+ int in_brack = 0;
- /*
- * there is a potential bug if a regexp is followed by an
- * equal sign: "/foo/=bar" would result in assign_quotient
- * being returned as the next token. Nothing is done about
- * it since it is not valid awk, but maybe something should
- * be done anyway.
- */
-
- tokstart = lexptr;
+ want_regexp = 0;
+ token_start = tokstart = lexptr;
while (c = *lexptr++) {
switch (c) {
+ case '[':
+ in_brack = 1;
+ break;
+ case ']':
+ in_brack = 0;
+ break;
case '\\':
if (*lexptr++ == '\0') {
yyerror("unterminated regexp ends with \\");
@@ -1157,6 +958,9 @@ retry:
goto retry;
break;
case '/': /* end of the regexp */
+ if (in_brack)
+ break;
+
lexptr--;
yylval.sval = tokstart;
return REGEXP;
@@ -1179,7 +983,7 @@ retry:
while (*lexptr == ' ' || *lexptr == '\t')
lexptr++;
- tokstart = lexptr;
+ token_start = tokstart = lexptr;
switch (c = *lexptr++) {
case 0:
@@ -1243,7 +1047,7 @@ retry:
return c;
case '/':
- if (*lexptr == '=') {
+ if (want_assign && *lexptr == '=') {
yylval.nodetypeval = Node_assign_quotient;
lexptr++;
return ASSIGNOP;
@@ -1346,18 +1150,24 @@ retry:
return NEWLINE;
case '"':
+ esc_seen = 0;
while (*lexptr != '\0') {
switch (*lexptr++) {
case '\\':
+ esc_seen = 1;
+ if (*lexptr == '\n')
+ yyerror("newline in string");
if (*lexptr++ != '\0')
break;
/* fall through */
case '\n':
+ lexptr--;
yyerror("unterminated string");
return ERROR;
- case '\"':
- /* Skip the doublequote */
- yylval.sval = tokstart + 1;
+ case '"':
+ yylval.nodeval = make_str_node(tokstart + 1,
+ lexptr-tokstart-2, esc_seen);
+ yylval.nodeval->flags |= PERM;
return YSTRING;
}
}
@@ -1374,23 +1184,9 @@ retry:
lexptr++;
return DECREMENT;
}
+ yylval.nodetypeval = Node_illegal;
+ return c;
- /*
- * It looks like space tab comma and newline are the legal
- * places for a UMINUS. Have we missed any?
- */
- if ((! isdigit(*lexptr) && *lexptr != '.') ||
- (lexptr > lexptr_begin + 1 &&
- ! index(" \t,\n", lexptr[-2]))) {
-
- /*
- * set node type to ILLEGAL because the action should
- * set it to the right thing
- */
- yylval.nodetypeval = Node_illegal;
- return c;
- }
- /* FALL through into number code */
case '0':
case '1':
case '2':
@@ -1403,11 +1199,7 @@ retry:
case '9':
case '.':
/* It's a number */
- if (c == '-')
- namelen = 1;
- else
- namelen = 0;
- for (; (c = tokstart[namelen]) != '\0'; namelen++) {
+ for (namelen = 0; (c = tokstart[namelen]) != '\0'; namelen++) {
switch (c) {
case '.':
if (seen_point)
@@ -1441,7 +1233,12 @@ retry:
got_number:
lexptr = tokstart + namelen;
- yylval.fval = atof(tokstart);
+ /*
+ yylval.nodeval = make_string(tokstart, namelen);
+ (void) force_number(yylval.nodeval);
+ */
+ yylval.nodeval = make_number(atof(tokstart));
+ yylval.nodeval->flags |= PERM;
return NUMBER;
case '&':
@@ -1454,7 +1251,7 @@ got_number:
;
if (c == '\n')
lineno++;
- else if (!isspace(c))
+ else if (! isspace(c))
break;
}
return LEX_AND;
@@ -1471,16 +1268,16 @@ got_number:
;
if (c == '\n')
lineno++;
- else if (!isspace(c))
+ else if (! isspace(c))
break;
}
return LEX_OR;
}
- yylval.nodetypeval = Node_illegal;
- return c;
- }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+ }
- if (c != '_' && !isalpha(c)) {
+ if (c != '_' && ! isalpha(c)) {
yyerror("Invalid char '%c' in expression\n", c);
return ERROR;
}
@@ -1489,7 +1286,7 @@ got_number:
for (namelen = 0; is_identchar(tokstart[namelen]); namelen++)
/* null */ ;
emalloc(tokkey, char *, namelen+1, "yylex");
- (void) strncpy (tokkey, tokstart, namelen);
+ memcpy(tokkey, tokstart, namelen);
tokkey[namelen] = '\0';
/* See if it is a special token. */
@@ -1499,8 +1296,6 @@ got_number:
int i, c;
mid = (low + high) / 2;
-
- compare:
c = *tokstart - tokentab[mid].operator[0];
i = c ? c : strcmp (tokkey, tokentab[mid].operator);
@@ -1512,7 +1307,8 @@ got_number:
lexptr = tokstart + namelen;
if (strict && tokentab[mid].nostrict)
break;
- if (tokentab[mid].class == LEX_BUILTIN)
+ if (tokentab[mid].class == LEX_BUILTIN
+ || tokentab[mid].class == LEX_LENGTH)
yylval.ptrval = tokentab[mid].ptr;
else
yylval.nodetypeval = tokentab[mid].value;
@@ -1548,7 +1344,10 @@ char *file;
char *awkpath, *cp;
char trypath[BUFSIZ];
FILE *fp;
+#ifdef DEBUG
extern int debugging;
+#endif
+ int fd;
if (strcmp (file, "-") == 0)
return (stdin);
@@ -1560,37 +1359,53 @@ char *file;
first = 0;
if ((awkpath = getenv ("AWKPATH")) != NULL && *awkpath)
savepath = awkpath; /* used for restarting */
-#ifdef MSDOS
- else if ((awkpath = getenv ("INIT")) != NULL && *awkpath)
- savepath = awkpath; /* MSC 5.1 users may prefer */
- /* to use INIT */
-#endif
}
awkpath = savepath;
/* some kind of path name, no search */
#ifndef MSDOS
- if (index (file, '/') != NULL)
+ if (strchr (file, '/') != NULL)
#else
- if (index (file, '/') != NULL || index (file, '\\') != NULL
- || index (file, ':') != NULL)
+ if (strchr (file, '/') != NULL || strchr (file, '\\') != NULL
+ || strchr (file, ':') != NULL)
#endif
- return (fdopen(devopen (file, "r"), "r"));
+ return ( (fd = devopen (file, "r")) >= 0 ?
+ fdopen(fd, "r") :
+ NULL);
do {
+ trypath[0] = '\0';
/* this should take into account limits on size of trypath */
for (cp = trypath; *awkpath && *awkpath != ENVSEP; )
*cp++ = *awkpath++;
- *cp++ = '/';
- *cp = '\0'; /* clear left over junk */
- strcat (cp, file);
- if ((fp = fdopen(devopen (trypath, "r"), "r")) != NULL)
+
+ if (cp != trypath) { /* nun-null element in path */
+ *cp++ = '/';
+ strcpy (cp, file);
+ } else
+ strcpy (trypath, file);
+#ifdef DEBUG
+ if (debugging)
+ fprintf(stderr, "trying: %s\n", trypath);
+#endif
+ if ((fd = devopen (trypath, "r")) >= 0
+ && (fp = fdopen(fd, "r")) != NULL)
return (fp);
/* no luck, keep going */
- awkpath++; /* skip colon */
+ if(*awkpath == ENVSEP && awkpath[1] != '\0')
+ awkpath++; /* skip colon */
} while (*awkpath);
+#ifdef MSDOS
+ /*
+ * Under DOS (and probably elsewhere) you might have one of the awk
+ * paths defined, WITHOUT the current working directory in it.
+ * Therefore you should try to open the file in the current directory.
+ */
+ return ( (fd = devopen(file, "r")) >= 0 ? fdopen(fd, "r") : NULL);
+#else
return (NULL);
+#endif
}
static NODE *
@@ -1604,7 +1419,7 @@ NODETYPE op;
r = newnode(op);
r->source_line = lineno;
- if (numfiles > 1 && !tempsource)
+ if (numfiles > -1 && ! tempsource)
r->source_file = sourcefile[curinfile];
else
r->source_file = NULL;
@@ -1709,9 +1524,8 @@ NODE *value;
hp->hlength = len;
hp->hvalue = value;
emalloc(hp->hname, char *, len + 1, "install");
- bcopy(name, hp->hname, len);
+ memcpy(hp->hname, name, len);
hp->hname[len] = '\0';
- hp->hvalue->varname = hp->hname;
return hp->hvalue;
}
@@ -1762,21 +1576,26 @@ int hashsize;
}
/*
- * Add new to the rightmost branch of LIST. This uses n^2 time, but doesn't
- * get used enough to make optimizing worth it. . .
+ * Add new to the rightmost branch of LIST. This uses n^2 time, so we make
+ * a simple attempt at optimizing it.
*/
-/* You don't believe me? Profile it yourself! */
static NODE *
append_right(list, new)
NODE *list, *new;
{
register NODE *oldlist;
+ static NODE *savefront = NULL, *savetail = NULL;
oldlist = list;
+ if (savefront == oldlist) {
+ savetail = savetail->rnode = new;
+ return oldlist;
+ } else
+ savefront = oldlist;
while (list->rnode != NULL)
list = list->rnode;
- list->rnode = new;
+ savetail = list->rnode = new;
return oldlist;
}
diff --git a/awk1.c b/awk1.c
deleted file mode 100644
index 0a02f376..00000000
--- a/awk1.c
+++ /dev/null
@@ -1,558 +0,0 @@
-/*
- * awk1 -- Expression tree constructors and main program for gawk.
- *
- * $Log: awk1.c,v $
- * Revision 1.39 89/03/31 13:16:33 david
- * GNU public license, MSDOS support, -V opt.
- *
- * Revision 1.38 89/03/30 10:19:13 david
- * moved awk_opts outside main() because cc doesn't like initialized autos
- * delete flush_io() since close_io() comes next
- *
- * Revision 1.37 89/03/29 21:54:53 david
- * to get this to work with gcc, awk_opts must be a character array rather
- * than a pointer (it is not readonly)
- *
- * Revision 1.36 89/03/29 14:17:23 david
- * delinting and code movement
- *
- * Revision 1.35 89/03/26 13:32:15 david
- * moved nextfile to awk7.c
- *
- * Revision 1.34 89/03/24 15:57:21 david
- * hashnode changes to NODE
- *
- * Revision 1.33 89/03/21 10:58:26 david
- * cleanup and movement of code to awk.y
- *
- * Revision 1.32 89/03/15 22:00:35 david
- * old case stuff removed
- * new case stuff added
- * add new escape sequences
- *
- * Revision 1.31 89/03/15 21:31:10 david
- * purge obstack stuff
- *
- * Revision 1.30 88/12/15 12:56:18 david
- * changes from Jay to compile under gcc and fixing a bug in treatment of
- * input files
- *
- * Revision 1.29 88/12/08 15:57:41 david
- * *** empty log message ***
- *
- * Revision 1.28 88/12/07 20:00:15 david
- * changes for incorporating source filename into error messages
- *
- * Revision 1.27 88/12/01 15:05:26 david
- * changes to allow source line number printing in error messages
- *
- * Revision 1.26 88/11/28 20:12:30 david
- * unbuffer stdout if compiled with DEBUG
- *
- * Revision 1.25 88/11/23 21:39:57 david
- * Arnold: set strict if invoked as "awk"
- *
- * Revision 1.24 88/11/22 13:47:40 david
- * Arnold: changes for case-insensitive matching
- *
- * Revision 1.23 88/11/15 10:18:57 david
- * Arnold: cleanup; allow multiple -f options; if invoked as awk disable
- * -v option for compatability
- *
- * Revision 1.22 88/11/14 21:54:27 david
- * Arnold: cleanup
- *
- * Revision 1.21 88/11/03 15:22:22 david
- * revised flags
- *
- * Revision 1.20 88/11/01 11:47:24 david
- * mostly cleanup and code movement
- *
- * Revision 1.19 88/10/19 21:56:00 david
- * replace malloc with emalloc
- *
- * Revision 1.18 88/10/17 20:57:19 david
- * Arnold: purge FAST
- *
- * Revision 1.17 88/10/14 22:11:24 david
- * pathc from Hack to get gcc to work
- *
- * Revision 1.16 88/10/13 21:55:08 david
- * purge FAST; clean up error messages
- *
- * Revision 1.15 88/10/06 21:55:20 david
- * be more careful about I/O errors on exit
- * Arnold's fixes for command line processing
- *
- * Revision 1.14 88/10/06 15:52:24 david
- * changes from Arnold: use getopt; ifdef -v option; change semantics of = args.
- *
- * Revision 1.13 88/09/26 10:16:35 david
- * cleanup from Arnold
- *
- * Revision 1.12 88/09/19 20:38:29 david
- * added -v option
- * set FILENAME to "-" if stdin
- *
- * Revision 1.11 88/08/09 14:49:23 david
- * reorganized handling of command-line arguments and files
- *
- * Revision 1.10 88/06/13 18:08:25 david
- * delete \a and -R options
- * separate exit value from flag indicating that exit has been called
- * [from Arnold]
- *
- * Revision 1.9 88/06/05 22:19:41 david
- * func_level goes away; param_counter is used to count order of local vars.
- *
- * Revision 1.8 88/05/31 09:21:56 david
- * Arnold's portability changes (vprintf)
- * fixed handling of function parameter use inside function
- *
- * Revision 1.7 88/05/30 09:51:17 david
- * exit after yyparse() if any errors were encountered
- * mk_re_parse() parses C escapes in regexps.
- * do panic() properly with varargs
- * clean up and simplify pop_var()
- *
- * Revision 1.6 88/05/26 22:46:19 david
- * minor changes: break out separate case for making regular expressions
- * from parser vs. from strings
- *
- * Revision 1.5 88/05/13 22:02:31 david
- * moved BEGIN and END block merging into parse-phase (sorry Arnold)
- * if there is only a BEGIN block and nothing else, don't read any files
- * cleaned up func_install a bit
- *
- * Revision 1.4 88/05/04 12:18:28 david
- * make_for_loop() now returns a NODE *
- * pop_var() now returns the value of the node being popped, to be used
- * in func_call() if the variable is an array (call by reference)
- *
- * Revision 1.3 88/04/15 13:12:19 david
- * small fix to arg reading code
- *
- * Revision 1.2 88/04/14 14:40:25 david
- * Arnold's changes to read program from a file
- *
- * Revision 1.1 88/04/08 15:14:52 david
- * Initial revision
- * Revision 1.6 88/04/08 14:48:30 david changes from
- * Arnold Robbins
- *
- * Revision 1.5 88/03/28 14:13:33 david *** empty log message ***
- *
- * Revision 1.4 88/03/23 22:17:33 david mostly delinting -- a couple of bug
- * fixes
- *
- * Revision 1.3 88/03/18 21:00:09 david Baseline -- hoefully all the
- * functionality of the new awk added. Just debugging and tuning to do.
- *
- * Revision 1.2 87/11/19 14:40:17 david added support for user-defined
- * functions
- *
- * Revision 1.1 87/10/27 15:23:26 david Initial revision
- *
- */
-
-/*
- * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
- *
- * This file is part of GAWK, the GNU implementation of the
- * AWK Progamming Language.
- *
- * GAWK is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 1, or (at your option)
- * any later version.
- *
- * GAWK is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GAWK; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include "awk.h"
-
-extern int yyparse();
-extern void do_input();
-extern void init_vars();
-extern void set_fs();
-extern int close_io();
-extern void init_args();
-extern void init_fields();
-extern int getopt();
-extern int re_set_syntax();
-
-static void usage();
-
-/*
- * The parse tree and field nodes are stored here. Parse_end is a dummy item
- * used to free up unneeded fields without freeing the program being run
- */
-int errcount = 0; /* error counter, used by yyerror() */
-int param_counter;
-
-/* The global null string */
-NODE *Nnull_string;
-
-/* The name the program was invoked under, for error messages */
-char *myname;
-
-/* A block of AWK code to be run before running the program */
-NODE *begin_block = 0;
-
-/* A block of AWK code to be run after the last input file */
-NODE *end_block = 0;
-
-int exiting = 0; /* Was an "exit" statement executed? */
-int exit_val = 0; /* optional exit value */
-
-#ifdef DEBUG
-/* non-zero means in debugging is enabled. Probably not very useful */
-int debugging = 0;
-#endif
-
-int tempsource = 0; /* source is in a temp file */
-char **sourcefile = NULL; /* source file name(s) */
-int numfiles = -1; /* how many source files */
-
-int strict = 0; /* turn off gnu extensions */
-
-NODE *expression_value;
-
-/*
- * for strict to work, legal options must be first
- */
-#define EXTENSIONS 5 /* where to clear */
-#ifdef DEBUG
-char awk_opts[] = "F:f:vVdD";
-#else
-char awk_opts[] = "F:f:vV";
-#endif
-
-#ifdef MSDOS
-#define TEMPLATE "%s/gaXXXXXX.tmp"
-#else
-#define TEMPLATE "/tmp/gawk.XXXXX"
-#endif
-
-main(argc, argv)
-int argc;
-char **argv;
-{
-#ifdef DEBUG
- /* Print out the parse tree. For debugging */
- register int dotree = 0;
- extern int yydebug;
-#endif
- extern char *version_string;
- FILE *fp;
- static char template[255];
-#ifdef MSDOS
- char *ptr;
-#endif
- int c;
- extern int opterr, optind;
- extern char *optarg;
- char *cp;
- extern char *rindex();
- extern char *mktemp();
-
- myname = argv[0];
- if (argc < 2)
- usage();
-
- /* Tell the regex routines how they should work. . . */
- (void) re_set_syntax(RE_SYNTAX_AWK);
-
- /* initialize the null string */
- Nnull_string = make_string("", 0);
- Nnull_string->numbr = 0.0;
- Nnull_string->type = Node_val;
- Nnull_string->flags = (PERM|STR|NUM);
-
- /* Set up the special variables */
-
- /*
- * Note that this must be done BEFORE arg parsing else -F
- * breaks horribly
- */
- init_vars();
-
- /* worst case */
- emalloc(sourcefile, char **, argc * sizeof(char *), "main");
-
-
-#ifdef STRICT /* strict Unix awk compatibility */
- strict = 1;
-#else
- /* if invoked as 'awk', also behave strictly */
- if ((cp = rindex(myname, '/')) != NULL)
- cp++;
- else
- cp = myname;
- if (STREQ(cp, "awk"))
- strict = 1;
-#endif
-
- if (strict)
- awk_opts[EXTENSIONS] = '\0';
-
- while ((c = getopt (argc, argv, awk_opts)) != EOF) {
- switch (c) {
-#ifdef DEBUG
- case 'd':
- debugging++;
- dotree++;
- break;
-
- case 'D':
- debugging++;
- yydebug = 2;
- break;
-#endif
-
- case 'F':
- set_fs(optarg);
- break;
-
- case 'f':
- /*
- * a la MKS awk, allow multiple -f options.
- * this makes function libraries real easy.
- * most of the magic is in the scanner.
- */
- sourcefile[++numfiles] = optarg;
- break;
-
- case 'v':
- fprintf(stderr, "%s", version_string);
- break;
-
- case 'V':
- copyleft();
- break;
-
- case '?':
- default:
- /* getopt will print a message for us */
- /* S5R4 awk ignores bad options and keeps going */
- break;
- }
- }
-#ifdef DEBUG
- setbuf(stdout, (char *) NULL); /* make debugging easier */
-#endif
- /* No -f option, use next arg */
- /* write to temp file and save sourcefile name */
- if (numfiles == -1) {
- int i;
-
- if (optind > argc - 1) /* no args left */
- usage();
- numfiles++;
-#ifdef MSDOS
- if ((ptr = getenv ("TMP")) == NULL)
- ptr = ".";
- sprintf (template, TEMPLATE, ptr);
-#else
- strcpy (template, TEMPLATE);
-#endif
- sourcefile[0] = mktemp (template);
- i = strlen (argv[optind]);
- if ((fp = fopen (sourcefile[0], "w")) == NULL)
- fatal("could not save source prog in temp file (%s)",
- sys_errlist[errno]);
- if (fwrite (argv[optind], 1, i, fp) == 0)
- fatal(
- "could not write source program to temp file (%s)",
- sys_errlist[errno]);
- if (argv[optind][i-1] != '\n')
- putc ('\n', fp);
- (void) fclose (fp);
- tempsource++;
- optind++;
- }
- init_args(optind, argc, myname, argv);
-
- /* Read in the program */
- if (yyparse() || errcount)
- exit(1);
-
-#ifdef DEBUG
- if (dotree)
- print_parse_tree(expression_value);
-#endif
- /* Set up the field variables */
- init_fields();
-
- if (begin_block)
- (void) interpret(begin_block);
- if (!exiting && (expression_value || end_block))
- do_input();
- if (end_block)
- (void) interpret(end_block);
- if (close_io() != 0 && exit_val == 0)
- exit_val = 1;
- exit(exit_val);
-}
-
-static void
-usage()
-{
-#ifdef STRICT
- char *opt1 = "[ -Ffs ] -f progfile [ -- ]";
- char *opt2 = "[ -Ffs ] [ -- ] 'program'";
-#else
- char *opt1 = "[ -v ] [ -Ffs ] -f progfile [ -- ]";
- char *opt2 = "[ -v ] [ -Ffs ] [ -- ] 'program'";
-#endif
-
- fprintf(stderr, "usage: %s %s file ...\n %s %s file ...\n",
- myname, opt1, myname, opt2);
- exit(11);
-}
-
-/* Generate compiled regular expressions */
-struct re_pattern_buffer *
-make_regexp(s, ignorecase)
-NODE *s;
-int ignorecase;
-{
- struct re_pattern_buffer *rp;
- char *err;
-
- emalloc(rp, struct re_pattern_buffer *, sizeof(*rp), "make_regexp");
- bzero((char *) rp, sizeof(*rp));
- emalloc(rp->buffer, char *, 8, "make_regexp");
- rp->allocated = 8;
- emalloc(rp->fastmap, char *, 256, "make_regexp");
-
- if (! strict && ignorecase)
- rp->translate = casetable;
- else
- rp->translate = NULL;
- if ((err = re_compile_pattern(s->stptr, s->stlen, rp)) != NULL)
- fatal("%s: /%s/", err, s->stptr);
- free_temp(s);
- return rp;
-}
-
-struct re_pattern_buffer *
-mk_re_parse(s, ignorecase)
-char *s;
-int ignorecase;
-{
- register char *src, *dest;
- register int c;
-
- for (dest = src = s; *src != '\0'; src++) {
- if (*src == '\\') {
- c = *++src;
- switch (c) {
- case 'a':
- if (strict)
- goto def;
- else
- *dest++ = BELL;
- break;
- case 'b':
- *dest++ = '\b';
- break;
- case 'f':
- *dest++ = '\f';
- break;
- case 'n':
- *dest++ = '\n';
- break;
- case 'r':
- *dest++ = '\r';
- break;
- case 't':
- *dest++ = '\t';
- break;
- case 'v':
- if (strict)
- goto def;
- else
- *dest++ = '\v';
- break;
- case 'x':
- if (strict)
- goto def;
- else {
- register int i = 0;
-
- while ((c = *++src)) {
- if (! isxdigit(c))
- break;
- if (isdigit(c))
- i += c - '0';
- else if (isupper(c))
- i += c - 'A' + 10;
- else
- i += c - 'a' + 10;
- }
- *dest++ = i;
- }
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- {
- register int i = c - '0';
- register int count = 0;
-
- while (++count < 3) {
- if ((c = *++src) >= '0' && c <= '7') {
- i *= 8;
- i += c - '0';
- } else
- break;
- }
- *dest++ = i;
- }
- break;
- default:
- def:
- *dest++ = '\\';
- *dest++ = c;
- break;
- }
- } else if (*src == '/')
- break;
- else
- *dest++ = *src;
- }
- return make_regexp(tmp_string(s, dest-s), ignorecase);
-}
-
-copyleft ()
-{
- extern char *version_string;
- char *cp;
- static char blurb[] =
-".\nCopyright (C) 1989, Free Software Foundation.\n\
-GNU Awk comes with ABSOLUTELY NO WARRANTY. This is free software, and\n\
-you are welcome to distribute it under the terms of the GNU General\n\
-Public License, which covers both the warranty information and the\n\
-terms for redistribution.\n\n\
-You should have received a copy of the GNU General Public License along\n\
-with this program; if not, write to the Free Software Foundation, Inc.,\n\
-675 Mass Ave, Cambridge, MA 02139, USA.\n";
-
- for (cp = version_string; *cp && *cp != '\n'; cp++)
- putc (*cp, stderr);
- fputs(blurb, stderr);
- fflush(stderr);
-}
diff --git a/awk4.c b/awk4.c
deleted file mode 100644
index 1e2193e7..00000000
--- a/awk4.c
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- * awk4 -- Code for features in new AWK, System V compatibility.
- *
- * $Log: awk4.c,v $
- * Revision 1.38 89/03/31 13:26:09 david
- * GNU license
- *
- * Revision 1.37 89/03/29 14:19:07 david
- * delinting and code movement
- *
- * Revision 1.36 89/03/22 22:10:23 david
- * a cleaner way to handle assignment to $n where n > 0
- *
- * Revision 1.35 89/03/22 21:05:24 david
- * delete some obsolete code
- *
- * Revision 1.34 89/03/22 21:00:34 david
- * replace some free()'s with freenode()
- *
- * Revision 1.33 89/03/21 19:26:01 david
- * minor cleanup
- *
- * Revision 1.32 89/03/21 18:22:54 david
- * some function tracing debugging code
- *
- * Revision 1.31 89/03/21 10:53:21 david
- * cleanup
- *
- * Revision 1.30 89/03/15 22:22:03 david
- * fix from hack: check for null function before using it in diagnostic
- *
- * Revision 1.29 89/03/15 22:02:24 david
- * new case stuff added
- *
- * Revision 1.28 89/03/15 21:34:37 david
- * free more memory and purge obstack stuff
- *
- * Revision 1.27 88/12/14 10:53:49 david
- * malloc structures in func_call and free them on return
- *
- * Revision 1.26 88/12/13 22:29:15 david
- * minor change
- *
- * Revision 1.25 88/12/08 10:52:01 david
- * small correction to #ifdef'ing
- *
- * Revision 1.24 88/11/30 15:18:21 david
- * fooling around with memory allocation in func_call() but this new code remains
- * #ifdef'd out
- * correction to creasting private copy of string in do_sub()
- *
- * Revision 1.23 88/11/29 09:55:48 david
- * corrections to code that tracks value of NF -- this needs cleanup
- *
- * Revision 1.22 88/11/28 20:30:10 david
- * bug fix for do_sub when third arg. not specified
- *
- * Revision 1.21 88/11/22 13:51:10 david
- * Arnold: delinting
- *
- * Revision 1.20 88/11/15 10:25:14 david
- * Arnold: minor cleanup
- *
- * Revision 1.19 88/11/14 22:00:09 david
- * Arnold: error message on bad regexp; correction to handling of RSTART in
- * match() on failure; return arg handling to previous behaviour: var=val
- * arg is processed whne it is encountered.
- *
- * Revision 1.18 88/11/14 21:28:09 david
- * moved concat_exp(); update NF on assign to field > NF; temporarily aborted
- * mods. in func_call(); flag misnamed as TMP becomes PERM (don't free)
- *
- * Revision 1.17 88/11/01 12:19:37 david
- * cleanup and substantial changes to do_sub()
- *
- * Revision 1.16 88/10/19 21:59:20 david
- * replace malloc and realloc with error checking versions
- *
- * Revision 1.15 88/10/17 20:54:54 david
- * SYSV --> USG
- *
- * Revision 1.14 88/10/13 22:00:44 david
- * purge FAST and cleanup error messages
- *
- * Revision 1.13 88/10/11 09:29:12 david
- * retrieve parameters from the stack in func_call
- *
- * Revision 1.12 88/10/06 21:53:15 david
- * added FSF copyleft; Arnold's changes to command line processing
- *
- *
- */
-
-/*
- * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
- *
- * This file is part of GAWK, the GNU implementation of the
- * AWK Progamming Language.
- *
- * GAWK is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 1, or (at your option)
- * any later version.
- *
- * GAWK is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GAWK; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include "awk.h"
-
-extern NODE **fields_arr;
-
-jmp_buf func_tag;
-NODE **stack_ptr;
-
-NODE *
-func_call(name, arg_list)
-NODE *name; /* name is a Node_val giving function name */
-NODE *arg_list; /* Node_expression_list of calling args. */
-{
- register NODE *arg, *argp, *r;
- NODE *n, *f;
- jmp_buf func_tag_stack;
- NODE *ret_node_stack;
- NODE **local_stack;
- NODE **sp;
- static int func_tag_valid = 0;
- int count;
- extern NODE *ret_node;
-
- /*
- * retrieve function definition node
- */
- f = lookup(variables, name->stptr);
- if (!f || f->type != Node_func)
- fatal("function `%s' not defined", name->stptr);
-#ifdef FUNC_TRACE
- fprintf(stderr, "function %s called\n", name->stptr);
-#endif
- /*
- * mark stack for variables allocated during life of function
- */
- count = f->lnode->param_cnt;
- emalloc(local_stack, NODE **, count * sizeof(NODE *), "func_call");
- sp = local_stack;
-
- /*
- * for each calling arg. add NODE * on stack
- */
- for (argp = arg_list; count && argp != NULL; argp = argp->rnode) {
- arg = argp->lnode;
- r = newnode(Node_var);
- /*
- * call by reference for arrays; see below also
- */
- if (arg->type == Node_param_list)
- arg = stack_ptr[arg->param_cnt];
- if (arg->type == Node_var_array)
- *r = *arg;
- else {
- n = dupnode(tree_eval(arg));
- r->lnode = n;
- r->rnode = (NODE *) NULL;
- }
- *sp++ = r;
- count--;
- }
- if (argp != NULL) /* left over calling args. */
- warning(
- "function `%s' called with more arguments than declared",
- name->stptr);
- /*
- * add remaining params. on stack with null value
- */
- while (count-- > 0) {
- r = newnode(Node_var);
- r->lnode = Nnull_string;
- r->rnode = (NODE *) NULL;
- *sp++ = r;
- }
-
- /*
- * execute function body, saving context, as a return statement
- * will longjmp back here
- */
- sp = local_stack;
- local_stack = stack_ptr;
- stack_ptr = sp;
- PUSH_BINDING(func_tag_stack, func_tag, func_tag_valid);
- ret_node_stack = ret_node;
- if (_setjmp(func_tag) == 0)
- (void) interpret(f->rnode);
- r = ret_node;
- ret_node = ret_node_stack;
- RESTORE_BINDING(func_tag_stack, func_tag, func_tag_valid);
- sp = stack_ptr;
- stack_ptr = local_stack;
- local_stack = sp;
-
- /*
- * here, we pop each parameter and check whether
- * it was an array. If so, and if the arg. passed in was
- * a simple variable, then the value should be copied back.
- * This achieves "call-by-reference" for arrays.
- */
- count = f->lnode->param_cnt;
- for (argp = arg_list; count-- > 0 && argp != NULL; argp = argp->rnode) {
- arg = argp->lnode;
- n = *sp++;
- if (arg->type == Node_var && n->type == Node_var_array) {
- arg->var_array = n->var_array;
- arg->type = Node_var_array;
- }
- deref = n->lnode;
- do_deref();
- freenode(n);
- }
- while (count-- > 0) {
- n = *sp++;
- deref = n->lnode;
- do_deref();
- freenode(n);
- }
- free((char *) local_stack);
- return r;
-}
-
-NODE *
-do_match(tree)
-NODE *tree;
-{
- NODE *t1;
- int rstart;
- struct re_registers reregs;
- struct re_pattern_buffer *rp;
-
- t1 = force_string(tree_eval(tree->lnode));
- if (tree->rnode->type == Node_regex) {
- rp = tree->rnode->rereg;
- if (!strict && ((IGNORECASE_node->var_value->numbr != 0)
- ^ (tree->rnode->re_case != 0))) {
- /* recompile since case sensitivity differs */
- rp = tree->rnode->rereg =
- mk_re_parse(tree->rnode->re_text,
- (IGNORECASE_node->var_value->numbr != 0));
- tree->rnode->re_case = (IGNORECASE_node->var_value->numbr != 0);
- }
- } else {
- rp = make_regexp(force_string(tree_eval(tree->rnode)),
- (IGNORECASE_node->var_value->numbr != 0));
- if (rp == NULL)
- cant_happen();
- }
- rstart = re_search(rp, t1->stptr, t1->stlen, 0, t1->stlen, &reregs);
- free_temp(t1);
- if (rstart >= 0) {
- rstart++; /* 1-based indexing */
- /* RSTART set to rstart below */
- RLENGTH_node->var_value->numbr =
- (AWKNUM) (reregs.end[0] - reregs.start[0]);
- } else {
- /*
- * Match failed. Set RSTART to 0, RLENGTH to -1.
- * Return the value of RSTART.
- */
- rstart = 0; /* used as return value */
- RLENGTH_node->var_value->numbr = -1.0;
- }
- RSTART_node->var_value->numbr = (AWKNUM) rstart;
- return tmp_number((AWKNUM) rstart);
-}
-
-NODE *
-do_sub(tree)
-NODE *tree;
-{
- register int len;
- register char *scan;
- register char *bp, *cp;
- int search_start = 0;
- int match_length;
- int matches = 0;
- char *buf;
- int global;
- struct re_pattern_buffer *rp;
- NODE *s; /* subst. pattern */
- NODE *t; /* string to make sub. in; $0 if none given */
- struct re_registers reregs;
- unsigned int saveflags;
- NODE *tmp;
- NODE **lhs;
- char *lastbuf;
-
- global = (tree->type == Node_gsub);
-
- if (tree->rnode->type == Node_regex) {
- rp = tree->rnode->rereg;
- if (! strict && ((IGNORECASE_node->var_value->numbr != 0)
- ^ (tree->rnode->re_case != 0))) {
- /* recompile since case sensitivity differs */
- rp = tree->rnode->rereg =
- mk_re_parse(tree->rnode->re_text,
- (IGNORECASE_node->var_value->numbr != 0));
- tree->rnode->re_case = (IGNORECASE_node->var_value->numbr != 0);
- }
- } else {
- rp = make_regexp(force_string(tree_eval(tree->rnode)),
- (IGNORECASE_node->var_value->numbr != 0));
- if (rp == NULL)
- cant_happen();
- }
- tree = tree->lnode;
- s = force_string(tree_eval(tree->lnode));
- tree = tree->rnode;
- deref = 0;
- field_num = -1;
- if (tree == NULL) {
- t = node0_valid ? fields_arr[0] : *get_field(0, 0);
- lhs = &fields_arr[0];
- field_num = 0;
- deref = t;
- } else {
- t = tree->lnode;
- lhs = get_lhs(t, 1);
- t = force_string(tree_eval(t));
- }
- /*
- * create a private copy of the string
- */
- if (t->stref > 1 || (t->flags & PERM)) {
- saveflags = t->flags;
- t->flags &= ~MALLOC;
- tmp = dupnode(t);
- t->flags = saveflags;
- do_deref();
- t = tmp;
- if (lhs)
- *lhs = tmp;
- }
- lastbuf = t->stptr;
- do {
- if (re_search(rp, t->stptr, t->stlen, search_start,
- t->stlen-search_start, &reregs) == -1
- || reregs.start[0] == reregs.end[0])
- break;
- matches++;
-
- /*
- * first, make a pass through the sub. pattern, to calculate
- * the length of the string after substitution
- */
- match_length = reregs.end[0] - reregs.start[0];
- len = t->stlen - match_length;
- for (scan = s->stptr; scan < s->stptr + s->stlen; scan++)
- if (*scan == '&')
- len += match_length;
- else if (*scan == '\\' && *(scan+1) == '&') {
- scan++;
- len++;
- } else
- len++;
- emalloc(buf, char *, len + 1, "do_sub");
- bp = buf;
-
- /*
- * now, create the result, copying in parts of the original
- * string
- */
- for (scan = t->stptr; scan < t->stptr + reregs.start[0]; scan++)
- *bp++ = *scan;
- for (scan = s->stptr; scan < s->stptr + s->stlen; scan++)
- if (*scan == '&')
- for (cp = t->stptr + reregs.start[0]; cp < t->stptr + reregs.end[0]; cp++)
- *bp++ = *cp;
- else if (*scan == '\\' && *(scan+1) == '&') {
- scan++;
- *bp++ = *scan;
- } else
- *bp++ = *scan;
- search_start = bp - buf;
- for (scan = t->stptr + reregs.end[0]; scan < t->stptr + t->stlen; scan++)
- *bp++ = *scan;
- *bp = '\0';
- free(lastbuf);
- t->stptr = buf;
- lastbuf = buf;
- t->stlen = len;
- } while (global && search_start < t->stlen);
-
- free_temp(s);
- if (matches > 0) {
- if (field_num == 0)
- set_record(fields_arr[0]->stptr, fields_arr[0]->stlen);
- t->flags &= ~NUM;
- }
- field_num = -1;
- return tmp_number((AWKNUM) matches);
-}
diff --git a/awk7.c b/awk7.c
deleted file mode 100644
index 789e84dd..00000000
--- a/awk7.c
+++ /dev/null
@@ -1,1123 +0,0 @@
-/*
- * awk7.c - routines for dealing with record input and fields
- */
-
-/*
- * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
- *
- * This file is part of GAWK, the GNU implementation of the
- * AWK Progamming Language.
- *
- * GAWK is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 1, or (at your option)
- * any later version.
- *
- * GAWK is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GAWK; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include "awk.h"
-#include <fcntl.h>
-
-extern NODE *concat_exp();
-
-static void do_file();
-static int get_rs();
-static IOBUF *nextfile();
-static int re_split();
-static int get_a_record();
-static int iop_close();
-static IOBUF *iop_alloc();
-static void close_one();
-static int close_fp();
-
-static int getline_redirect = 0;/* "getline <file" being executed */
-static char *line_buf = NULL; /* holds current input line */
-static int line_alloc = 0; /* current allocation for line_buf */
-static char *parse_extent; /* marks where to restart parse of record */
-static int parse_high_water=0; /* field number that we have parsed so far */
-static char f_empty[] = "";
-static char *save_fs = " "; /* save current value of FS when line is read,
- * to be used in deferred parsing
- */
-
-extern NODE *ARGC_node;
-extern NODE *ARGV_node;
-
-int field_num; /* save number of field in get_lhs */
-NODE **fields_arr; /* array of pointers to the field nodes */
-NODE node0; /* node for $0 which never gets free'd */
-int node0_valid = 1; /* $(>0) has not been changed yet */
-
-void
-init_fields()
-{
- emalloc(fields_arr, NODE **, sizeof(NODE *), "init_fields");
- node0.type = Node_val;
- node0.stref = 0;
- node0.flags = (STR|PERM); /* never free buf */
- fields_arr[0] = &node0;
-}
-
-/*
- * Danger! Must only be called for fields we know have just been blanked, or
- * fields we know don't exist yet.
- */
-
-/*ARGSUSED*/
-static void
-set_field(num, str, len, dummy)
-int num;
-char *str;
-int len;
-NODE *dummy; /* not used -- just to make interface same as set_element */
-{
- NODE *n;
- int t;
- static int nf_high_water = 0;
-
- if (num > nf_high_water) {
- erealloc(fields_arr, NODE **, (num + 1) * sizeof(NODE *), "set_field");
- nf_high_water = num;
- }
- /* fill in fields that don't exist */
- for (t = parse_high_water + 1; t < num; t++)
- fields_arr[t] = Nnull_string;
- n = make_string(str, len);
- fields_arr[num] = n;
- parse_high_water = num;
-}
-
-/* Someone assigned a value to $(something). Fix up $0 to be right */
-static void
-rebuild_record()
-{
- register int tlen;
- register NODE *tmp;
- NODE *ofs;
- char *ops;
- register char *cops;
- register NODE **ptr, **maxp;
-
- maxp = 0;
- tlen = 0;
- ofs = force_string(OFS_node->var_value);
- ptr = &fields_arr[parse_high_water];
- while (ptr > &fields_arr[0]) {
- tmp = force_string(*ptr);
- tlen += tmp->stlen;
- if (tmp->stlen && !maxp)
- maxp = ptr;
- ptr--;
- }
- if (maxp) {
- tlen += ((maxp - fields_arr) - 1) * ofs->stlen;
- emalloc(ops, char *, tlen + 1, "fix_fields");
- cops = ops;
- for (ptr = &fields_arr[1]; ptr <= maxp; ptr++) {
- tmp = force_string(*ptr);
- bcopy(tmp->stptr, cops, tmp->stlen);
- cops += tmp->stlen;
- if (ptr != maxp) {
- bcopy(ofs->stptr, cops, ofs->stlen);
- cops += ofs->stlen;
- }
- }
- } else
- ops = "";
- tmp = make_string(ops, tlen);
- deref = fields_arr[0];
- do_deref();
- fields_arr[0] = tmp;
-}
-
-#ifndef SLOWIO
-#define DO_END_OF_BUF len = bp - start;\
- while (len > iop->secsiz) {\
- erealloc(iop->secbuf, char *, iop->secsiz *= 2, "get");\
- }\
- bcopy(start, iop->secbuf, len);\
- start = iop->secbuf;\
- last = start + len;\
- iop->cnt = read(iop->fd, iop->buf, iop->size);\
- if (iop->cnt < 0)\
- return iop->cnt;\
- end_data = iop->buf + iop->cnt;\
- iop->off = bp = iop->buf;
-
-#define DO_END_OF_DATA iop->cnt = read(iop->fd, end_data, end_buf - end_data);\
- if (iop->cnt < 0)\
- return iop->cnt;\
- end_data += iop->cnt;\
- if (iop->cnt == 0)\
- break;\
- iop->cnt = end_data - iop->buf;
-
-static int
-get_a_record(res, iop)
-char **res;
-IOBUF *iop;
-{
- register char *end_data;
- register char *end_buf;
- char *start;
- register char *bp;
- char *last;
- int len;
- register char rs = get_rs();
-
- end_data = iop->buf + iop->cnt;
- if (iop->off >= end_data) {
- iop->cnt = read(iop->fd, iop->buf, iop->size);
- if (iop->cnt <= 0)
- return iop->cnt = EOF;
- end_data = iop->buf + iop->cnt;
- iop->off = iop->buf;
- }
- start = bp = iop->off;
- end_buf = iop->buf + iop->size;
- if (rs == 0) {
- while (!(*bp == '\n' && bp != iop->buf && bp[-1] == '\n')) {
- if (++bp == end_buf) {
- DO_END_OF_BUF
- }
- if (bp == end_data) {
- DO_END_OF_DATA
- }
- }
- if (*bp == '\n' && bp != start && bp[-1] == '\n')
- bp--;
- else if (bp != iop->buf && bp[-1] != '\n')
- warning("record not terminated");
- else
- bp--;
- iop->off = bp + 2;
- } else {
- while (*bp++ != rs) {
- if (bp == end_buf) {
- DO_END_OF_BUF
- }
- if (bp == end_data) {
- DO_END_OF_DATA
- }
- }
- if (*--bp != rs) {
- warning("record not terminated");
- bp++;
- }
- iop->off = bp + 1;
- }
- if (start == iop->secbuf) {
- len = bp - iop->buf;
- while (len > iop->secsiz) {
- erealloc(iop->secbuf, char *, iop->secsiz *= 2, "get2");
- }
- bcopy(iop->buf, last, len);
- bp = last + len;
- }
- *bp = '\0';
- *res = start;
- return bp - start;
-}
-#endif
-
-/*
- * This reads in a record from the input file
- */
-static int
-inrec(iop)
-IOBUF *iop;
-{
- int cnt;
- int retval = 0;
-
-#ifndef SLOWIO
- cnt = get_a_record(&line_buf, iop);
-#else
- cnt = get_a_record(fp, &line_buf, &line_alloc);
-#endif
- if (cnt == EOF) {
- cnt = 0;
- retval = 1;
- } else {
- if (!getline_redirect) {
- assign_number(&NR_node->var_value,
- NR_node->var_value->numbr + 1.0);
- assign_number(&FNR_node->var_value,
- FNR_node->var_value->numbr + 1.0);
- }
- }
- set_record(line_buf, cnt);
-
- return retval;
-}
-
-/*
- * setup $0, but defer parsing rest of line until reference is made to $(>0)
- * or to NF. At that point, parse only as much as necessary.
- */
-void
-set_record(buf, cnt)
-char *buf;
-int cnt;
-{
- register int i;
-
- assign_number(&NF_node->var_value, (AWKNUM)-1);
- for (i = 1; i <= parse_high_water; i++) {
- deref = fields_arr[i];
- do_deref();
- }
- parse_high_water = 0;
- node0_valid = 1;
- if (buf == line_buf) {
- deref = fields_arr[0];
- do_deref();
- save_fs = get_fs();
- node0.type = Node_val;
- node0.stptr = buf;
- node0.stlen = cnt;
- node0.stref = 1;
- node0.flags = (STR|PERM); /* never free buf */
- fields_arr[0] = &node0;
- }
-}
-
-NODE **
-get_field(num, assign)
-int num;
-int assign; /* this field is on the LHS of an assign */
-{
- int n;
-
- /*
- * if requesting whole line but some other field has been altered,
- * then the whole line must be rebuilt
- */
- if (num == 0 && node0_valid == 0) {
- /* first, parse remainder of input record */
- n = parse_fields(HUGE-1, &parse_extent,
- node0.stlen - (parse_extent - node0.stptr),
- save_fs, set_field, (NODE *)NULL);
- assign_number(&NF_node->var_value, (AWKNUM)n);
- rebuild_record();
- return &fields_arr[0];
- }
- if (num > 0 && assign)
- node0_valid = 0;
- if (num <= parse_high_water) /* we have already parsed this field */
- return &fields_arr[num];
- if (parse_high_water == 0 && num > 0) /* starting at the beginning */
- parse_extent = fields_arr[0]->stptr;
- /*
- * parse up to num fields, calling set_field() for each, and saving
- * in parse_extent the point where the parse left off
- */
- n = parse_fields(num, &parse_extent,
- fields_arr[0]->stlen - (parse_extent-fields_arr[0]->stptr),
- save_fs, set_field, (NODE *)NULL);
- if (num == HUGE-1)
- num = n;
- if (n < num) { /* requested field number beyond end of record;
- * set_field will just extend the number of fields,
- * with empty fields
- */
- set_field(num, f_empty, 0, (NODE *) NULL);
- /*
- * if this field is onthe LHS of an assignment, then we want to
- * set NF to this value, below
- */
- if (assign)
- n = num;
- }
- /*
- * if we reached the end of the record, set NF to the number of fields
- * so far. Note that num might actually refer to a field that
- * is beyond the end of the record, but we won't set NF to that value at
- * this point, since this is only a reference to the field and NF
- * only gets set if the field is assigned to -- in this case n has
- * been set to num above
- */
- if (*parse_extent == '\0')
- assign_number(&NF_node->var_value, (AWKNUM)n);
-
- return &fields_arr[num];
-}
-
-/*
- * this is called both from get_field() and from do_split()
- */
-int
-parse_fields(up_to, buf, len, fs, set, n)
-int up_to; /* parse only up to this field number */
-char **buf; /* on input: string to parse; on output: point to start next */
-int len;
-register char *fs;
-void (*set) (); /* routine to set the value of the parsed field */
-NODE *n;
-{
- char *s = *buf;
- register char *field;
- register char *scan;
- register char *end = s + len;
- int NF = parse_high_water;
-
- if (up_to == HUGE)
- NF = 0;
- if (*fs && *(fs + 1) != '\0') { /* fs is a regexp */
- struct re_registers reregs;
-
- scan = s;
- while (re_split(scan, end - scan, fs, &reregs) != -1 &&
- NF < up_to) {
- (*set)(++NF, scan, reregs.start[0], n);
- scan += reregs.end[0];
- }
- if (NF != up_to && scan <= end) {
- (*set)(++NF, scan, end - scan, n);
- scan = end;
- }
- *buf = scan;
- return (NF);
- }
- for (scan = s; scan < end && NF < up_to; scan++) {
- /*
- * special case: fs is single space, strip leading
- * whitespace
- */
- if (*fs == ' ') {
- while ((*scan == ' ' || *scan == '\t') && scan < end)
- scan++;
- if (scan >= end)
- break;
- }
- field = scan;
- if (*fs == ' ')
- while (*scan != ' ' && *scan != '\t' && scan < end)
- scan++;
- else {
- while (*scan != *fs && scan < end)
- scan++;
- if (scan == end-1 && *scan == *fs) {
- (*set)(++NF, field, scan - field, n);
- field = scan;
- }
- }
- (*set)(++NF, field, scan - field, n);
- if (scan == end)
- break;
- }
- *buf = scan;
- return NF;
-}
-
-static int
-re_split(buf, len, fs, reregs)
-char *buf, *fs;
-int len;
-struct re_registers *reregs;
-{
- typedef struct re_pattern_buffer RPAT;
- static RPAT *rp;
- static char *last_fs = NULL;
-
- if ((last_fs != NULL && !STREQ(fs, last_fs))
- || (rp && ! strict && ((IGNORECASE_node->var_value->numbr != 0)
- ^ (rp->translate != NULL))))
- {
- /* fs has changed or IGNORECASE has changed */
- free(rp->buffer);
- free(rp->fastmap);
- free((char *) rp);
- free(last_fs);
- last_fs = NULL;
- }
- if (last_fs == NULL) { /* first time */
- emalloc(rp, RPAT *, sizeof(RPAT), "re_split");
- bzero((char *) rp, sizeof(RPAT));
- emalloc(rp->buffer, char *, 8, "re_split");
- rp->allocated = 8;
- emalloc(rp->fastmap, char *, 256, "re_split");
- emalloc(last_fs, char *, strlen(fs) + 1, "re_split");
- (void) strcpy(last_fs, fs);
- if (! strict && IGNORECASE_node->var_value->numbr != 0.0)
- rp->translate = casetable;
- else
- rp->translate = NULL;
- if (re_compile_pattern(fs, strlen(fs), rp) != NULL)
- fatal("illegal regular expression for FS: `%s'", fs);
- }
- return re_search(rp, buf, len, 0, len, reregs);
-}
-
-#ifdef SLOWIO
-static int /* count of chars read or EOF */
-get_a_record(fp, bp, sizep)
-FILE *fp;
-char **bp; /* *bp points to beginning of line on return */
-int *sizep; /* *sizep is current allocation of *bp */
-{
- register char *buf; /* buffer; realloced if necessary */
- int bsz; /* current buffer size */
- register char *cur; /* current position in buffer */
- register char *buf_end; /* end of buffer */
- register int rs; /* rs is the current record separator */
- register int c;
-
- bsz = *sizep;
- buf = *bp;
- if (!buf) {
- emalloc(buf, char *, 128, "get_a_record");
- bsz = 128;
- }
- rs = get_rs();
- buf_end = buf + bsz;
- cur = buf;
- if (rs == 0) {
- while ((c = getc(fp)) != EOF) {
- if (c == '\n' && cur != buf && cur[-1] == '\n') {
- cur--;
- break;
- }
- *cur++ = c;
- if (cur == buf_end) {
- erealloc(buf, char *, bsz * 2, "get_a_record");
- cur = buf + bsz;
- bsz *= 2;
- buf_end = buf + bsz;
- }
- }
- if (c == EOF && cur != buf && cur[-1] == '\n')
- cur--;
- } else {
- while ((c = getc(fp)) != EOF) {
- if (c == rs)
- break;
- *cur++ = c;
- if (cur == buf_end) {
- erealloc(buf, char *, bsz * 2, "get_a_record");
- cur = buf + bsz;
- bsz *= 2;
- buf_end = buf + bsz;
- }
- }
- }
- *cur = '\0';
- *bp = buf;
- *sizep = bsz;
- if (c == EOF && cur == buf)
- return EOF;
- return cur - buf;
-}
-#endif
-
-NODE *
-do_getline(tree)
-NODE *tree;
-{
- IOBUF *iop;
- int cnt;
- NODE **lhs;
- int redir_error = 0;
-
- if (tree->rnode == NULL) { /* no redirection */
- iop = nextfile();
- if (iop == NULL) /* end of input */
- return tmp_number((AWKNUM) 0.0);
- }
- if (tree->rnode != NULL) { /* with redirection */
- iop = redirect(tree->rnode, &redir_error)->iop;
- if (iop == NULL && redir_error) /* failed redirect */
- return tmp_number((AWKNUM) -1.0);
- getline_redirect++;
- }
- if (tree->lnode == NULL) { /* no optional var. -- read in $0 */
- if (inrec(iop) != 0) {
- getline_redirect = 0;
- return tmp_number((AWKNUM) 0.0);
- }
- } else { /* read in a named variable */
- char *s = NULL;
- int n = 0;
-
- lhs = get_lhs(tree->lnode, 1);
-#ifdef SLOWIO
- cnt = get_a_record(fp, &s, &n);
-#else
- cnt = get_a_record(&s, iop);
-#endif
- if (!getline_redirect) {
- assign_number(&NR_node->var_value,
- NR_node->var_value->numbr + 1.0);
- assign_number(&FNR_node->var_value,
- FNR_node->var_value->numbr + 1.0);
- }
- if (cnt == EOF) {
- getline_redirect = 0;
- free(s);
- return tmp_number((AWKNUM) 0.0);
- }
- *lhs = make_string(s, strlen(s));
- /*free(s);*/
- do_deref();
- /* we may have to regenerate $0 here! */
- if (field_num == 0)
- set_record(fields_arr[0]->stptr, fields_arr[0]->stlen);
- field_num = -1;
- }
- getline_redirect = 0;
- return tmp_number((AWKNUM) 1.0);
-}
-
-/*
- * We can't dereference a variable until after we've given it its new value.
- * This variable points to the value we have to free up
- */
-NODE *deref;
-
-/*
- * This returns a POINTER to a node pointer. get_lhs(ptr) is the current
- * value of the var, or where to store the var's new value
- */
-
-NODE **
-get_lhs(ptr, assign)
-NODE *ptr;
-int assign; /* this is being called for the LHS of an assign. */
-{
- register NODE **aptr;
- NODE *n;
-
-#ifdef DEBUG
- if (ptr == NULL)
- cant_happen();
-#endif
- deref = NULL;
- field_num = -1;
- switch (ptr->type) {
- case Node_var:
- case Node_var_array:
- if (ptr == NF_node && (int) NF_node->var_value->numbr == -1)
- (void) get_field(HUGE-1, assign); /* parse record */
- deref = ptr->var_value;
-#ifdef DEBUG
- if (deref->type != Node_val)
- cant_happen();
- if (deref->flags == 0)
- cant_happen();
-#endif
- return &(ptr->var_value);
-
- case Node_param_list:
- n = stack_ptr[ptr->param_cnt];
-#ifdef DEBUG
- deref = n->var_value;
- if (deref->type != Node_val)
- cant_happen();
- if (deref->flags == 0)
- cant_happen();
- deref = 0;
-#endif
- return &(n->var_value);
-
- case Node_field_spec:
- field_num = (int) force_number(tree_eval(ptr->lnode));
- free_result();
- if (field_num < 0)
- fatal("attempt to access field %d", field_num);
- aptr = get_field(field_num, assign);
- deref = *aptr;
- return aptr;
-
- case Node_subscript:
- n = ptr->lnode;
- if (n->type == Node_param_list)
- n = stack_ptr[n->param_cnt];
- aptr = assoc_lookup(n, concat_exp(ptr->rnode));
- deref = *aptr;
-#ifdef DEBUG
- if (deref->type != Node_val)
- cant_happen();
- if (deref->flags == 0)
- cant_happen();
-#endif
- return aptr;
- case Node_func:
- fatal ("`%s' is a function, assignment is not allowed",
- ptr->lnode->param);
- }
- return 0;
-}
-
-void
-do_deref()
-{
- if (deref == NULL)
- return;
- if (deref == Nnull_string) {
- deref = 0;
- return;
- }
-#ifdef DEBUG
- if (deref->flags == 0)
- cant_happen();
-#endif
- if ((deref->flags & MALLOC) || (deref->flags & TEMP)) {
-#ifdef DEBUG
- if (deref->flags & PERM)
- cant_happen();
-#endif
- if (deref->flags & STR) {
- if (deref->stref > 0 && deref->stref != 255)
- deref->stref--;
- if (deref->stref > 0) {
- deref->flags &= ~TEMP;
- deref = 0;
- return;
- }
- free(deref->stptr);
- }
- freenode(deref);
- }
- deref = 0;
-}
-
-static IOBUF *
-nextfile()
-{
- static int i = 1;
- static int files = 0;
- static IOBUF *curfile = NULL;
- char *arg;
- char *cp;
- int fd = -1;
-
- if (curfile != NULL && curfile->cnt != EOF)
- return curfile;
- for (; i < (int) (ARGC_node->lnode->numbr); i++) {
- arg = (*assoc_lookup(ARGV_node, tmp_number((AWKNUM) i)))->stptr;
- if (*arg == '\0')
- continue;
- cp = index(arg, '=');
- if (cp != NULL) {
- *cp++ = '\0';
- variable(arg)->var_value = make_string(cp, strlen(cp));
- *--cp = '='; /* restore original text of ARGV */
- } else {
- files++;
- if (STREQ(arg, "-"))
- fd = 0;
- else
- fd = open(arg, O_RDONLY);
- if (fd == -1)
- fatal("cannot open file `%s' for reading (%s)",
- arg, sys_errlist[errno]);
- /* NOTREACHED */
- /* This is a kludge. */
- deref = FILENAME_node->var_value;
- do_deref();
- FILENAME_node->var_value =
- make_string(arg, strlen(arg));
- FNR_node->var_value->numbr = 0.0;
- i++;
- break;
- }
- }
- if (files == 0) {
- files++;
- /* no args. -- use stdin */
- /* FILENAME is init'ed to "-" */
- /* FNR is init'ed to 0 */
- fd = 0;
- }
- if (fd == -1)
- return NULL;
- return curfile = iop_alloc(fd);
-}
-
-static IOBUF *
-iop_alloc(fd)
-int fd;
-{
- IOBUF *iop;
- struct stat stb;
-
- /*
- * System V doesn't have the file system block size in the
- * stat structure. So we have to make some sort of reasonable
- * guess. We use stdio's BUFSIZ, since that what it was
- * meant for in the first place.
- */
-#if defined(USG) || defined(MSDOS)
-#define DEFBLKSIZE BUFSIZ
-#else
-#define DEFBLKSIZE stb.st_blksize
-#endif
-
- if (fd == -1)
- return NULL;
- emalloc(iop, IOBUF *, sizeof(IOBUF), "nextfile");
- if (isatty(fd))
- iop->size = 128;
- else if (fstat(fd, &stb) == -1)
- fatal("can't stat fd %d", fd);
- else if (lseek(fd, 0L, 0) == -1)
- iop->size = DEFBLKSIZE;
- else
- iop->size = stb.st_size < DEFBLKSIZE ?
- stb.st_size+1 : DEFBLKSIZE;
- errno = 0;
- iop->fd = fd;
- emalloc(iop->buf, char *, iop->size, "nextfile");
- iop->off = iop->buf;
- iop->cnt = 0;
- iop->secsiz = iop->size < 128 ? iop->size : 128;
- emalloc(iop->secbuf, char *, iop->secsiz, "nextfile");
- return iop;
-}
-
-void
-do_input()
-{
- IOBUF *iop;
- extern int exiting;
-
- while ((iop = nextfile()) != NULL) {
- do_file(iop);
- if (exiting)
- break;
- }
-}
-
-static int
-iop_close(iop)
-IOBUF *iop;
-{
- int ret;
-
- ret = close(iop->fd);
- if (ret == -1)
- warning("close of fd %d failed");
- free(iop->buf);
- free(iop->secbuf);
- free((char *)iop);
- return ret == -1 ? 1 : 0;
-}
-
-static void
-do_file(iop)
-IOBUF *iop;
-{
- /* This is where it spends all its time. The infamous MAIN LOOP */
- if (inrec(iop) == 0)
- while (interpret(expression_value) && inrec(iop) == 0)
- ;
- (void) iop_close(iop);
-}
-
-static int
-get_rs()
-{
- register NODE *tmp;
-
- tmp = force_string(RS_node->var_value);
- if (tmp->stlen == 0)
- return 0;
- return *(tmp->stptr);
-}
-struct redirect *red_head = NULL;
-
-/* Redirection for printf and print commands */
-struct redirect *
-redirect(tree, errflg)
-NODE *tree;
-int *errflg;
-{
- register NODE *tmp;
- register struct redirect *rp;
- register char *str;
- register FILE *fp;
- int tflag;
- char *direction = "to";
-
- tflag = 0;
- switch (tree->type) {
- case Node_redirect_append:
- tflag = RED_APPEND;
- case Node_redirect_output:
- tflag |= (RED_FILE|RED_WRITE);
- break;
-#ifndef MSDOS
- case Node_redirect_pipe:
- tflag = (RED_PIPE|RED_WRITE);
- break;
- case Node_redirect_pipein:
- tflag = (RED_PIPE|RED_READ);
- break;
-#else
- case Node_redirect_pipe:
- case Node_redirect_pipein:
- fprintf (stderr, "%s: cannot use pipe in PC version.\n",
- myname);
- exit(1);
- break;
-#endif
- case Node_redirect_input:
- tflag = (RED_FILE|RED_READ);
- break;
- default:
- fatal ("invalid tree type %d in redirect()\n", tree->type);
- break;
- }
- tmp = force_string(tree_eval(tree->subnode));
- str = tmp->stptr;
- for (rp = red_head; rp != NULL; rp = rp->next)
- if (rp->flag == tflag && STREQ(rp->value, str))
- break;
- if (rp == NULL) {
- emalloc(rp, struct redirect *, sizeof(struct redirect),
- "redirect");
- emalloc(str, char *, strlen(tmp->stptr)+1, "redirect");
- (void) strcpy(str, tmp->stptr);
- rp->value = str;
- rp->flag = tflag;
- rp->offset = 0;
- rp->fp = NULL;
- rp->iop = NULL;
- /* maintain list in most-recently-used first order */
- if (red_head)
- red_head->prev = rp;
- rp->prev = NULL;
- rp->next = red_head;
- red_head = rp;
- }
- while (rp->fp == NULL && rp->iop == NULL) {
- errno = 0;
- switch (tree->type) {
- case Node_redirect_output:
- fp = rp->fp = fdopen(devopen(str, "w"), "w");
- break;
- case Node_redirect_append:
- fp = rp->fp = fdopen(devopen(str, "a"), "a");
- break;
-#ifndef MSDOS
- case Node_redirect_pipe:
- fp = rp->fp = popen(str, "w");
- break;
- case Node_redirect_pipein:
- direction = "from";
- /* this should bypass popen() */
- rp->iop = iop_alloc(fileno(popen(str, "r")));
- break;
-#endif
- case Node_redirect_input:
- direction = "from";
- rp->iop = iop_alloc(devopen(str, "r"));
- break;
- }
- if (fp == NULL && rp->iop == NULL) {
- /* too many files open -- close one and try again */
- if (errno == ENFILE || errno == EMFILE)
- close_one();
- else {
- /*
- * Some other reason for failure.
- *
- * On redirection of input from a file,
- * just return an error, so e.g. getline
- * can return -1. For output to file,
- * complain. The shell will complain on
- * a bad command to a pipe.
- */
- *errflg = 1;
- if (tree->type == Node_redirect_output
- || tree->type == Node_redirect_append)
- fatal("can't redirect %s `%s'\n",
- direction, str);
- else
- return NULL;
- }
- }
- }
- if (rp->offset != 0) /* this file was previously open */
- if (fseek(fp, rp->offset, 0) == -1)
- fatal("can't seek to %ld on `%s'\n", rp->offset, str);
-#ifdef notdef
- (void) flush_io(); /* a la SVR4 awk */
-#endif
- free_temp(tmp);
- return rp;
-}
-
-static void
-close_one()
-{
- register struct redirect *rp;
- register struct redirect *rplast;
-
- /* go to end of list first, to pick up least recently used entry */
- for (rp = red_head; rp != NULL; rp = rp->next)
- rplast = rp;
- /* now work back up through the list */
- for (rp = rplast; rp != NULL; rp = rp->prev)
- if (rp->fp && (rp->flag & RED_FILE)) {
- rp->offset = ftell(rp->fp);
- if (fclose(rp->fp))
- warning("close of \"%s\" failed (%s).",
- rp->value, sys_errlist[errno]);
- rp->fp = NULL;
- break;
- }
- if (rp == NULL)
- /* surely this is the only reason ??? */
- fatal("too many pipes or input files open");
-}
-
-NODE *
-do_close(tree)
-NODE *tree;
-{
- NODE *tmp;
- register struct redirect *rp;
-
- tmp = force_string(tree_eval(tree->subnode));
- for (rp = red_head; rp != NULL; rp = rp->next) {
- if (STREQ(rp->value, tmp->stptr))
- break;
- }
- free_temp(tmp);
- if (rp == NULL) /* no match */
- return tmp_number((AWKNUM) 0.0);
- return tmp_number((AWKNUM)close_fp(rp));
-}
-
-static int
-close_fp(rp)
-register struct redirect *rp;
-{
- int status;
-
-#ifndef MSDOS
- if (rp->flag == (RED_PIPE|RED_WRITE))
- status = pclose(rp->fp);
- else
-#endif
- if (rp->fp)
- status = fclose(rp->fp);
- else if (rp->iop)
- status = iop_close(rp->iop);
-
- /* SVR4 awk checks and warns about status of close */
- if (status)
- warning("%s close of \"%s\" failed (%s).",
-#ifndef MSDOS
- (rp->flag & RED_PIPE) ? "pipe" :
-#endif
- "file", rp->value,
- sys_errlist[errno]);
- if (rp->prev)
- rp->prev->next = rp->next;
- else
- red_head = rp->next;
- free(rp->value);
- free((char *)rp);
- return status;
-}
-
-int
-flush_io ()
-{
- register struct redirect *rp;
- int status = 0;
-
- if (fflush(stdout)) {
- warning("error writing standard output.");
- status++;
- }
- if (fflush(stderr)) {
- warning("error writing standard error.");
- status++;
- }
- for (rp = red_head; rp != NULL; rp = rp->next)
- /* flush both files and pipes, what the heck */
- if ((rp->flag & RED_WRITE) && rp->fp != NULL)
- if (fflush(rp->fp)) {
- warning( "%s flush of \"%s\" failed (%s).",
-#ifndef MSDOS
- (rp->flag & RED_PIPE) ? "pipe" :
-#endif
- "file", rp->value, sys_errlist[errno]);
- status++;
- }
- return status;
-}
-
-int
-close_io ()
-{
- register struct redirect *rp;
- int status = 0;
-
- for (rp = red_head; rp != NULL; rp = rp->next)
- if ((rp->fp && close_fp(rp)) || (rp->iop && iop_close(rp->iop)))
- status++;
- return status;
-}
-
-/* devopen --- handle /dev/std{in,out,err}, /dev/fd/N, regular files */
-int
-devopen (name, mode)
-char *name, *mode;
-{
- int openfd = -1;
- FILE *fdopen ();
- char *cp;
- int flag;
-
- switch(mode[0]) {
- case 'r': flag = O_RDONLY;
- break;
-
- case 'w': flag = O_WRONLY|O_CREAT|O_TRUNC;
- break;
-
- case 'a': flag = O_WRONLY|O_APPEND|O_CREAT;
- break;
- }
-
-#if defined(STRICT) || defined(NO_DEV_FD)
- return (open (name, flag, 0666));
-#else
- if (strict)
- return (open (name, flag, 0666));
-
- if (!STREQN (name, "/dev/", 5))
- return (open (name, flag, 0666));
- else
- cp = name + 5;
-
- /* XXX - first three tests ignore mode */
- if (STREQ(cp, "stdin"))
- return (0);
- else if (STREQ(cp, "stdout"))
- return (1);
- else if (STREQ(cp, "stderr"))
- return (2);
- else if (STREQN(cp, "fd/", 3)) {
- cp += 3;
- if (sscanf (cp, "%d", & openfd) == 1 && openfd >= 0)
- /* got something */
- return openfd;
- else
- return -1;
- } else
- return (open (name, flag, 0666));
-#endif
-}
diff --git a/awka.c b/awka.c
deleted file mode 100644
index 610af2d3..00000000
--- a/awka.c
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * awka.c --- some speciallized memory allocation routines
- *
- * $Log: awka.c,v $
- * Revision 1.2 89/03/31 13:26:15 david
- * GNU license
- *
- * Revision 1.1 89/03/22 21:04:00 david
- * Initial revision
- *
- */
-
-/*
- * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
- *
- * This file is part of GAWK, the GNU implementation of the
- * AWK Progamming Language.
- *
- * GAWK is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 1, or (at your option)
- * any later version.
- *
- * GAWK is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GAWK; see the file COPYING. If not, write to
- * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include "awk.h"
-
-#define NODECHUNK 50
-
-NODE *nextfree = NULL;
-NODE *lastfree = NULL;
-
-NODE *
-newnode(ty)
-NODETYPE ty;
-{
- NODE *it;
- NODE *np;
-
- if (nextfree == lastfree) {
- emalloc(nextfree, NODE *, NODECHUNK * sizeof(NODE), "newnode");
- for (np = nextfree; np < &nextfree[NODECHUNK - 1]; np++)
- np->nextp = np + 1;
- np->nextp = lastfree;
- lastfree = np;
- }
- it = nextfree;
- nextfree = nextfree->nextp;
- it->type = ty;
- it->flags = MALLOC;
- return it;
-}
-
-freenode(it)
-NODE *it;
-{
- lastfree->nextp = it;
- it->nextp = NULL;
- lastfree = it;
-}
diff --git a/awk3.c b/builtin.c
index 50b04339..b949a33b 100644
--- a/awk3.c
+++ b/builtin.c
@@ -1,161 +1,5 @@
/*
- * awk3 -- Builtin functions and various utility procedures
- *
- * $Log: awk3.c,v $
- * Revision 1.40 89/03/31 13:17:20 david
- * GNU license; be careful about types in sprintf calls
- *
- * Revision 1.39 89/03/29 14:20:07 david
- * delinting and code movement
- * change redirect() to return struct redirect *
- *
- * Revision 1.38 89/03/22 22:10:20 david
- * a cleaner way to handle assignment to $n where n > 0
- *
- * Revision 1.37 89/03/21 10:54:21 david
- * cleanup and fix of handling of precision in format string of printf call
- *
- * Revision 1.36 89/03/15 22:01:51 david
- * ENVIRON fix from hack
- * relegated -Ft to strict compatibility
- * getline error return fix
- * printf %c fix (only print 1 char of a string)
- * tolower & toupper added
- * /dev/fd/N etc special files added
- *
- * Revision 1.35 89/03/15 21:34:05 david
- * try to free more memory
- *
- * Revision 1.34 88/12/13 22:28:10 david
- * temporarily #ifdef out flush_io in redirect(); adjust atan2() for
- * force_number as a macro
- *
- * Revision 1.32 88/12/01 15:03:21 david
- * renamed hack_print_node to do_print (at last!)
- * moved force_string() up out of print_simple for simplicity
- *
- * Revision 1.31 88/11/30 15:17:27 david
- * free previous value in set_fs
- *
- * Revision 1.30 88/11/29 16:24:47 david
- * fix bug in previous change
- *
- * Revision 1.29 88/11/29 15:14:52 david
- * dynamically manage open files/pipes to allow an arbitrary number of open files
- * (i.e. when out of file descriptors, close the least recently used file,
- * saving the current offset; if it is reused, reopen and seek to saved offset)
- *
- * Revision 1.28 88/11/28 20:12:53 david
- * correct previous error in cleanup of do_substr
- *
- * Revision 1.27 88/11/23 21:42:13 david
- * Arnold: change ENV to ENVIRON nad a further bug fix for -Ft
- * ..
- *
- * Revision 1.26 88/11/22 13:50:33 david
- * Arnold: added ENV array and bug fix to -Ft
- *
- * Revision 1.25 88/11/15 10:24:08 david
- * Arnold: cleanup of comments, #include's and obsolete code
- *
- * Revision 1.24 88/11/14 21:57:03 david
- * Arnold: init. FILENAME to "-" and cleanup in do_substr()
- *
- * Revision 1.23 88/11/01 12:17:45 david
- * cleanu and code movement; changes to reflect change to parse_fields()
- *
- * Revision 1.22 88/10/19 21:58:43 david
- * replace malloc and realloc with error checking versions
- *
- * Revision 1.21 88/10/17 20:55:31 david
- * SYSV --> USG
- *
- * Revision 1.20 88/10/13 21:59:55 david
- * purge FAST and cleanup error messages
- *
- * Revision 1.19 88/10/06 21:54:28 david
- * cleaned up I/O handling
- *
- * Revision 1.18 88/10/06 15:49:01 david
- * changes from Arnold: be careful about flushing I/O; warn about error on close;
- * return seed from srand
- *
- * Revision 1.17 88/09/19 20:39:11 david
- * minor cleanup
- *
- * Revision 1.16 88/08/09 14:55:16 david
- * getline now gets next file properly
- * stupid bug in do_split() fixed
- * substr() now works if second arg. is negative (truncated to 0)
- *
- * Revision 1.15 88/06/13 18:07:12 david
- * delete -R option
- * cleanup of redirection code [from Arnold]
- *
- * Revision 1.14 88/06/07 23:41:00 david
- * some paranoid typecasting plus one bug fix:
- * in do_getline(), use stdin if input_file is NULL and ther is no redirection
- *
- * Revision 1.13 88/06/06 21:40:49 david
- * oops! got a little overenthusiastic on that last merge
- *
- * Revision 1.12 88/06/06 11:27:57 david
- * get rid of some obsolete code
- * merge parsing of fields for record input and split()
- *
- * Revision 1.11 88/06/05 21:00:35 david
- * flush I/O buffers before calling system (fix from Arnold)
- *
- * Revision 1.10 88/06/05 20:59:26 david
- * local vars. now come off a stack
- *
- * Revision 1.9 88/06/01 22:08:24 david
- * in split(), ensure that if second arg. is a local var. that the value is
- * looked up
- *
- * Revision 1.8 88/05/31 09:30:16 david
- * Arnold's portability fixes to last change in random() stuff
- *
- * Revision 1.7 88/05/30 09:53:49 david
- * clean up some fatal() calls
- * de-lint the random number code
- *
- * Revision 1.6 88/05/27 11:06:21 david
- * input_file wasn't getting properly reset after getline
- *
- * Revision 1.5 88/05/26 22:49:55 david
- * fixed error message for redirection
- *
- * Revision 1.4 88/05/18 18:20:02 david
- * fixed case where RS==""; record was including a trailing newline
- *
- * Revision 1.3 88/04/13 17:39:26 david
- * fixed bug in handling of NR and FNR
- *
- * Revision 1.2 88/04/12 16:04:02 david
- * fixed bug: NF at end of record generated one less field than it should have
- *
- * Revision 1.1 88/04/08 15:15:07 david
- * Initial revision
- * Revision 1.7 88/04/08 15:08:48 david bug fix for file
- * descriptor handlin
- *
- * Revision 1.6 88/04/08 14:48:36 david changes from Arnold Robbins
- *
- * Revision 1.5 88/03/28 14:13:54 david *** empty log message ***
- *
- * Revision 1.4 88/03/23 22:17:41 david mostly delinting -- a couple of bug
- * fixes
- *
- * Revision 1.3 88/03/18 21:00:13 david Baseline -- hoefully all the
- * functionality of the new awk added. Just debugging and tuning to do.
- *
- * Revision 1.2 87/11/19 14:42:31 david expanded functionality for getline
- * broke out get_a_record() from inrec() so that the former can be used from
- * do_getline add system() builtin and skeletons for many other new builtins
- *
- * Revision 1.1 87/10/27 15:23:33 david Initial revision
- *
+ * builtin.c - Builtin functions and various utility procedures
*/
/*
@@ -181,129 +25,16 @@
#include "awk.h"
-extern int parse_fields();
-extern void assoc_clear();
-extern NODE *node();
-
-#ifdef USG
-extern long lrand48();
-extern void srand48();
-#else
extern void srandom();
extern char *initstate();
extern char *setstate();
extern long random();
-#endif
-static void set_element();
+extern NODE **fields_arr;
+
static void get_one();
static void get_two();
static int get_three();
-static int a_get_three();
-static void close_one();
-static int close_fp();
-static NODE *spc_var();
-
-NODE *do_sprintf();
-
-/* These nodes store all the special variables AWK uses */
-NODE *FS_node, *NF_node, *RS_node, *NR_node;
-NODE *FILENAME_node, *OFS_node, *ORS_node, *OFMT_node;
-NODE *FNR_node, *RLENGTH_node, *RSTART_node, *SUBSEP_node;
-NODE *ENVIRON_node, *IGNORECASE_node;
-NODE *ARGC_node, *ARGV_node;
-
-/*
- * Set all the special variables to their initial values.
- */
-void
-init_vars()
-{
- extern char **environ;
- char *var, *val;
- NODE **aptr;
- int i;
-
- FS_node = spc_var("FS", make_string(" ", 1));
- NF_node = spc_var("NF", make_number(-1.0));
- RS_node = spc_var("RS", make_string("\n", 1));
- NR_node = spc_var("NR", make_number(0.0));
- FNR_node = spc_var("FNR", make_number(0.0));
- FILENAME_node = spc_var("FILENAME", make_string("-", 1));
- OFS_node = spc_var("OFS", make_string(" ", 1));
- ORS_node = spc_var("ORS", make_string("\n", 1));
- OFMT_node = spc_var("OFMT", make_string("%.6g", 4));
- RLENGTH_node = spc_var("RLENGTH", make_number(0.0));
- RSTART_node = spc_var("RSTART", make_number(0.0));
- SUBSEP_node = spc_var("SUBSEP", make_string("\034", 1));
- IGNORECASE_node = spc_var("IGNORECASE", make_number(0.0));
-
- ENVIRON_node = spc_var("ENVIRON", Nnull_string);
- for (i = 0; environ[i]; i++) {
- static char nullstr[] = "";
-
- var = environ[i];
- val = index(var, '=');
- if (val)
- *val++ = '\0';
- else
- val = nullstr;
- aptr = assoc_lookup(ENVIRON_node, tmp_string(var, strlen (var)));
- *aptr = make_string(val, strlen (val));
-
- /* restore '=' so that system() gets a valid environment */
- if (val != nullstr)
- *--val = '=';
- }
-}
-
-/*
- * OFMT is special because we don't dare use force_string on it for fear of
- * infinite loops. Thus, if it isn't a string, we return the default "%.6g"
- * This may or may not be the right thing to do, but its the easiest
- */
-/* This routine isn't used! It should be. */
-#ifdef notdef
-char *
-get_ofmt()
-{
- register NODE *tmp;
-
- tmp = OFMT_node->var_value;
- if ((tmp->type != Node_string && tmp->type != Node_str_num) || tmp->stlen == 0)
- return "%.6g";
- return tmp->stptr;
-}
-#endif
-
-char *
-get_fs()
-{
- register NODE *tmp;
-
- tmp = force_string(FS_node->var_value);
- if (tmp->stlen == 0)
- return 0;
- return tmp->stptr;
-}
-
-void
-set_fs(str)
-char *str;
-{
- register NODE **tmp;
-
- tmp = get_lhs(FS_node, 0);
- /*
- * Only if in full compatibility mode check for the stupid special
- * case so -F\t works as documented in awk even though the shell
- * hands us -Ft. Bleah!
- */
- if (strict && str[0] == 't' && str[1] == '\0')
- str[0] = '\t';
- *tmp = make_string(str, 1);
- do_deref();
-}
/* Builtin functions */
NODE *
@@ -311,10 +42,17 @@ do_exp(tree)
NODE *tree;
{
NODE *tmp;
+ double d, res;
double exp();
get_one(tree, &tmp);
- return tmp_number((AWKNUM)exp((double)force_number(tmp)));
+ d = force_number(tmp);
+ free_temp(tmp);
+ errno = 0;
+ res = exp(d);
+ if (errno == ERANGE)
+ warning("exp argument %g is out of range", d);
+ return tmp_number((AWKNUM) res);
}
NODE *
@@ -324,19 +62,40 @@ NODE *tree;
NODE *s1, *s2;
register char *p1, *p2;
register int l1, l2;
+ long ret;
+
get_two(tree, &s1, &s2);
+ force_string(s1);
+ force_string(s2);
p1 = s1->stptr;
p2 = s2->stptr;
l1 = s1->stlen;
l2 = s2->stlen;
- while (l1) {
- if (STREQN(p1, p2, l2))
- return tmp_number((AWKNUM) (1 + s1->stlen - l1));
- l1--;
- p1++;
+ ret = 0;
+ if (! strict && IGNORECASE_node->var_value->numbr != 0.0) {
+ while (l1) {
+ if (casetable[*p1] == casetable[*p2]
+ && strncasecmp(p1, p2, l2) == 0) {
+ ret = 1 + s1->stlen - l1;
+ break;
+ }
+ l1--;
+ p1++;
+ }
+ } else {
+ while (l1) {
+ if (STREQN(p1, p2, l2)) {
+ ret = 1 + s1->stlen - l1;
+ break;
+ }
+ l1--;
+ p1++;
+ }
}
- return tmp_number((AWKNUM) 0.0);
+ free_temp(s1);
+ free_temp(s2);
+ return tmp_number((AWKNUM) ret);
}
NODE *
@@ -345,9 +104,12 @@ NODE *tree;
{
NODE *tmp;
double floor();
+ double d;
get_one(tree, &tmp);
- return tmp_number((AWKNUM)floor((double)force_number(tmp)));
+ d = floor((double)force_number(tmp));
+ free_temp(tmp);
+ return tmp_number((AWKNUM) d);
}
NODE *
@@ -355,9 +117,12 @@ do_length(tree)
NODE *tree;
{
NODE *tmp;
+ int len;
get_one(tree, &tmp);
- return tmp_number((AWKNUM) (force_string(tmp)->stlen));
+ len = force_string(tmp)->stlen;
+ free_temp(tmp);
+ return tmp_number((AWKNUM) len);
}
NODE *
@@ -366,60 +131,15 @@ NODE *tree;
{
NODE *tmp;
double log();
+ double d, arg;
get_one(tree, &tmp);
- return tmp_number((AWKNUM)log((double)force_number(tmp)));
-}
-
-void
-do_printf(tree)
-NODE *tree;
-{
- register FILE *fp = stdout;
- int errflg = 0; /* not used, sigh */
-
- if (tree->rnode)
- fp = redirect(tree->rnode, &errflg)->fp;
- if (fp)
- print_simple(do_sprintf(tree->lnode), fp);
-}
-
-static void
-set_element(num, s, len, n)
-int num;
-char *s;
-int len;
-NODE *n;
-{
- *assoc_lookup(n, tmp_number((AWKNUM) (num))) = make_string(s, len);
-}
-
-NODE *
-do_split(tree)
-NODE *tree;
-{
- NODE *t1, *t2, *t3;
- register char *splitc;
- char *s;
- NODE *n;
-
- if (a_get_three(tree, &t1, &t2, &t3) < 3)
- splitc = get_fs();
- else
- splitc = force_string(t3)->stptr;
-
- n = t2;
- if (t2->type == Node_param_list)
- n = stack_ptr[t2->param_cnt];
- if (n->type != Node_var && n->type != Node_var_array)
- fatal("second argument of split is not a variable");
- assoc_clear(n);
-
- tree = force_string(t1);
-
- s = tree->stptr;
- return tmp_number((AWKNUM)
- parse_fields(HUGE, &s, tree->stlen, splitc, set_element, n));
+ arg = (double) force_number(tmp);
+ if (arg < 0.0)
+ warning("log called with negative argument %g", arg);
+ d = log(arg);
+ free_temp(tmp);
+ return tmp_number((AWKNUM) d);
}
/*
@@ -433,15 +153,15 @@ do_sprintf(tree)
NODE *tree;
{
#define bchunk(s,l) if(l) {\
- if((l)>ofre) {\
+ while((l)>ofre) {\
char *tmp;\
tmp=(char *)alloca(osiz*2);\
- bcopy(obuf,tmp,olen);\
+ memcpy(tmp,obuf,olen);\
obuf=tmp;\
ofre+=osiz;\
osiz*=2;\
}\
- bcopy(s,obuf+olen,(l));\
+ memcpy(obuf+olen,s,(l));\
olen+=(l);\
ofre-=(l);\
}
@@ -450,7 +170,7 @@ NODE *tree;
#define chksize(l) if((l)>ofre) {\
char *tmp;\
tmp=(char *)alloca(osiz*2);\
- bcopy(obuf,tmp,olen);\
+ memcpy(tmp,obuf,olen);\
obuf=tmp;\
ofre+=osiz;\
osiz*=2;\
@@ -479,6 +199,9 @@ NODE *tree;
long fw, prec, lj, alt, big;
long *cur;
long val;
+#ifdef sun386 /* Can't cast unsigned (int/long) from ptr->value */
+ long tmp_uval; /* on 386i 4.0.1 C compiler -- it just hangs */
+#endif
unsigned long uval;
int sgn;
int base;
@@ -488,6 +211,7 @@ NODE *tree;
char *fill;
double tmpval;
char *pr_str;
+ int ucasehex = 0;
extern char *gcvt();
@@ -543,6 +267,10 @@ retry:
*cur = *cur * 10 + *s1++ - '0';
}
goto retry;
+#ifdef not_yet
+ case ' ': /* print ' ' or '-' */
+ case '+': /* print '+' or '-' */
+#endif
case '-':
if (lj || fill != sp)
goto lose;
@@ -565,8 +293,13 @@ retry:
goto retry;
case 'c':
parse_next_arg();
- if (arg->flags & NUM) {
+ if (arg->flags & NUMERIC) {
+#ifdef sun386
+ tmp_uval = arg->numbr;
+ uval= (unsigned long) tmp_uval;
+#else
uval = (unsigned long) arg->numbr;
+#endif
cpbuf[0] = uval;
prec = 1;
pr_str = cpbuf;
@@ -576,7 +309,7 @@ retry:
prec = 1;
else if (prec > arg->stlen)
prec = arg->stlen;
- pr_str = cpbuf;
+ pr_str = arg->stptr;
goto dopr_string;
case 's':
parse_next_arg();
@@ -600,10 +333,13 @@ retry:
}
}
s0 = s1;
+ free_temp(arg);
break;
case 'd':
+ case 'i':
parse_next_arg();
val = (long) force_number(arg);
+ free_temp(arg);
if (val < 0) {
sgn = 1;
val = -val;
@@ -615,6 +351,8 @@ retry:
} while (val);
if (sgn)
*--cp = '-';
+ if (prec > fw)
+ fw = prec;
prec = cend - cp;
if (fw > prec && !lj) {
if (fill != sp && *cp == '-') {
@@ -643,16 +381,30 @@ retry:
case 'o':
base = 8;
goto pr_unsigned;
+ case 'X':
+ ucasehex = 1;
case 'x':
base = 16;
goto pr_unsigned;
pr_unsigned:
parse_next_arg();
uval = (unsigned long) force_number(arg);
+ free_temp(arg);
do {
*--cp = chbuf[uval % base];
+ if (ucasehex && isalpha(*cp))
+ *cp = toupper(*cp);
uval /= base;
} while (uval);
+ if (alt && (base == 8 || base == 16)) {
+ if (base == 16) {
+ if (ucasehex)
+ *--cp = 'X';
+ else
+ *--cp = 'x';
+ }
+ *--cp = '0';
+ }
prec = cend - cp;
if (fw > prec && !lj) {
while (fw > prec) {
@@ -672,6 +424,7 @@ retry:
case 'g':
parse_next_arg();
tmpval = force_number(arg);
+ free_temp(arg);
if (prec == 0)
prec = 13;
(void) gcvt(tmpval, (int) prec, cpbuf);
@@ -708,6 +461,7 @@ retry:
case 'f':
parse_next_arg();
tmpval = force_number(arg);
+ free_temp(arg);
chksize(fw + prec + 5); /* 5==slop */
cp = cpbuf;
@@ -731,6 +485,7 @@ retry:
case 'e':
parse_next_arg();
tmpval = force_number(arg);
+ free_temp(arg);
chksize(fw + prec + 5); /* 5==slop */
cp = cpbuf;
*cp++ = '%';
@@ -757,18 +512,44 @@ retry:
}
}
bchunk(s0, s1 - s0);
+ free_temp(sfmt);
return tmp_string(obuf, olen);
}
+void
+do_printf(tree)
+NODE *tree;
+{
+ struct redirect *rp = NULL;
+ register FILE *fp = stdout;
+ int errflg = 0; /* not used, sigh */
+
+ if (tree->rnode) {
+ rp = redirect(tree->rnode, &errflg);
+ if (rp)
+ fp = rp->fp;
+ }
+ if (fp)
+ print_simple(do_sprintf(tree->lnode), fp);
+ if (rp && (rp->flag & RED_NOBUF))
+ fflush(fp);
+}
+
NODE *
do_sqrt(tree)
NODE *tree;
{
NODE *tmp;
double sqrt();
+ double d, arg;
get_one(tree, &tmp);
- return tmp_number((AWKNUM)sqrt((double)force_number(tmp)));
+ arg = (double) force_number(tmp);
+ if (arg < 0.0)
+ warning("sqrt called with negative argument %g", arg);
+ d = sqrt(arg);
+ free_temp(tmp);
+ return tmp_number((AWKNUM) d);
}
NODE *
@@ -776,47 +557,69 @@ do_substr(tree)
NODE *tree;
{
NODE *t1, *t2, *t3;
+ NODE *r;
register int indx, length;
+ t1 = t2 = t3 = NULL;
length = -1;
if (get_three(tree, &t1, &t2, &t3) == 3)
length = (int) force_number(t3);
indx = (int) force_number(t2) - 1;
- tree = force_string(t1);
+ t1 = force_string(t1);
if (length == -1)
- length = tree->stlen;
+ length = t1->stlen;
if (indx < 0)
indx = 0;
- if (indx >= tree->stlen || length <= 0)
+ if (indx >= t1->stlen || length <= 0) {
+ if (t3)
+ free_temp(t3);
+ free_temp(t2);
+ free_temp(t1);
return Nnull_string;
- if (indx + length > tree->stlen)
- length = tree->stlen - indx;
- return tmp_string(tree->stptr + indx, length);
+ }
+ if (indx + length > t1->stlen)
+ length = t1->stlen - indx;
+ if (t3)
+ free_temp(t3);
+ free_temp(t2);
+ r = tmp_string(t1->stptr + indx, length);
+ free_temp(t1);
+ return r;
}
NODE *
do_system(tree)
NODE *tree;
{
+#if defined(unix) || defined(MSDOS) /* || defined(gnu) */
NODE *tmp;
int ret;
- (void) flush_io (); /* so output is syncrhonous with gawk's */
+ (void) flush_io (); /* so output is synchronous with gawk's */
get_one(tree, &tmp);
ret = system(force_string(tmp)->stptr);
ret = (ret >> 8) & 0xff;
+ free_temp(tmp);
return tmp_number((AWKNUM) ret);
+#else
+ fatal("the \"system\" function is not supported.");
+ /* NOTREACHED */
+#endif
}
void
do_print(tree)
register NODE *tree;
{
+ struct redirect *rp = NULL;
register FILE *fp = stdout;
int errflg = 0; /* not used, sigh */
- if (tree->rnode)
- fp = redirect(tree->rnode, &errflg)->fp;
+ if (tree->rnode) {
+ rp = redirect(tree->rnode, &errflg);
+ if (rp)
+ fp = rp->fp;
+ }
if (!fp)
return;
tree = tree->lnode;
@@ -835,6 +638,8 @@ register NODE *tree;
}
}
print_simple(ORS_node->var_value, fp);
+ if (rp && (rp->flag & RED_NOBUF))
+ fflush(fp);
}
NODE *
@@ -850,6 +655,7 @@ NODE *tree;
for (cp = t2->stptr, cp2 = t2->stptr + t2->stlen; cp < cp2; cp++)
if (isupper(*cp))
*cp = tolower(*cp);
+ free_temp(t1);
return t2;
}
@@ -866,6 +672,7 @@ NODE *tree;
for (cp = t2->stptr; cp < t2->stptr + t2->stlen; cp++)
if (islower(*cp))
*cp = toupper(*cp);
+ free_temp(t1);
return t2;
}
@@ -921,7 +728,7 @@ NODE *tree, **res1, **res2, **res3;
return 3;
}
-static int
+int
a_get_three(tree, res1, res2, res3)
NODE *tree, **res1, **res2, **res3;
{
@@ -947,7 +754,7 @@ NODE *tree;
FILE *fp;
{
if (fwrite(tree->stptr, sizeof(char), tree->stlen, fp) != tree->stlen)
- warning("fwrite: %s", sys_errlist[errno]);
+ warning("fwrite: %s", strerror(errno));
free_temp(tree);
}
@@ -957,11 +764,14 @@ NODE *tree;
{
NODE *t1, *t2;
extern double atan2();
+ double d1, d2;
get_two(tree, &t1, &t2);
- (void) force_number(t1);
- return tmp_number((AWKNUM) atan2((double) t1->numbr,
- (double) force_number(t2)));
+ d1 = force_number(t1);
+ d2 = force_number(t2);
+ free_temp(t1);
+ free_temp(t2);
+ return tmp_number((AWKNUM) atan2(d1, d2));
}
NODE *
@@ -970,9 +780,12 @@ NODE *tree;
{
NODE *tmp;
extern double sin();
+ double d;
get_one(tree, &tmp);
- return tmp_number((AWKNUM) sin((double)force_number(tmp)));
+ d = sin((double)force_number(tmp));
+ free_temp(tmp);
+ return tmp_number((AWKNUM) d);
}
NODE *
@@ -981,16 +794,16 @@ NODE *tree;
{
NODE *tmp;
extern double cos();
+ double d;
get_one(tree, &tmp);
- return tmp_number((AWKNUM) cos((double)force_number(tmp)));
+ d = cos((double)force_number(tmp));
+ free_temp(tmp);
+ return tmp_number((AWKNUM) d);
}
static int firstrand = 1;
-
-#ifndef USG
static char state[256];
-#endif
#define MAXLONG 2147483647 /* maximum value for long int */
@@ -999,16 +812,12 @@ NODE *
do_rand(tree)
NODE *tree;
{
-#ifdef USG
- return tmp_number((AWKNUM) lrand48() / MAXLONG);
-#else
if (firstrand) {
(void) initstate((unsigned) 1, state, sizeof state);
srandom(1);
firstrand = 0;
}
return tmp_number((AWKNUM) random() / MAXLONG);
-#endif
}
NODE *
@@ -1020,14 +829,6 @@ NODE *tree;
long ret = save_seed; /* SVR4 awk srand returns previous seed */
extern long time();
-#ifdef USG
- if (tree == NULL)
- srand48(save_seed = time((long *) 0));
- else {
- get_one(tree, &tmp);
- srand48(save_seed = (long) force_number(tmp));
- }
-#else
if (firstrand)
(void) initstate((unsigned) 1, state, sizeof state);
else
@@ -1038,41 +839,219 @@ NODE *tree;
else {
get_one(tree, &tmp);
srandom((int) (save_seed = (long) force_number(tmp)));
+ free_temp(tmp);
}
-#endif
firstrand = 0;
return tmp_number((AWKNUM) ret);
}
-/* Create a special variable */
-static NODE *
-spc_var(name, value)
-char *name;
-NODE *value;
+NODE *
+do_match(tree)
+NODE *tree;
{
- register NODE *r;
+ NODE *t1;
+ int rstart;
+ struct re_registers reregs;
+ struct re_pattern_buffer *rp;
+ int need_to_free = 0;
- if ((r = lookup(variables, name)) == NULL)
- r = install(variables, name, node(value, Node_var, (NODE *) NULL));
- return r;
+ t1 = force_string(tree_eval(tree->lnode));
+ tree = tree->rnode;
+ if (tree == NULL || tree->lnode == NULL)
+ fatal("match called with only one argument");
+ tree = tree->lnode;
+ if (tree->type == Node_regex) {
+ rp = tree->rereg;
+ if (!strict && ((IGNORECASE_node->var_value->numbr != 0)
+ ^ (tree->re_case != 0))) {
+ /* recompile since case sensitivity differs */
+ rp = tree->rereg =
+ mk_re_parse(tree->re_text,
+ (IGNORECASE_node->var_value->numbr != 0));
+ tree->re_case =
+ (IGNORECASE_node->var_value->numbr != 0);
+ }
+ } else {
+ need_to_free = 1;
+ rp = make_regexp(force_string(tree_eval(tree)),
+ (IGNORECASE_node->var_value->numbr != 0));
+ if (rp == NULL)
+ cant_happen();
+ }
+ rstart = re_search(rp, t1->stptr, t1->stlen, 0, t1->stlen, &reregs);
+ free_temp(t1);
+ if (rstart >= 0) {
+ rstart++; /* 1-based indexing */
+ /* RSTART set to rstart below */
+ RLENGTH_node->var_value->numbr =
+ (AWKNUM) (reregs.end[0] - reregs.start[0]);
+ } else {
+ /*
+ * Match failed. Set RSTART to 0, RLENGTH to -1.
+ * Return the value of RSTART.
+ */
+ rstart = 0; /* used as return value */
+ RLENGTH_node->var_value->numbr = -1.0;
+ }
+ RSTART_node->var_value->numbr = (AWKNUM) rstart;
+ if (need_to_free) {
+ free(rp->buffer);
+ free(rp->fastmap);
+ free((char *) rp);
+ }
+ return tmp_number((AWKNUM) rstart);
}
-void
-init_args(argc0, argc, argv0, argv)
-int argc0, argc;
-char *argv0;
-char **argv;
+static NODE *
+sub_common(tree, global)
+NODE *tree;
+int global;
{
- int i, j;
- NODE **aptr;
-
- ARGV_node = spc_var("ARGV", Nnull_string);
- aptr = assoc_lookup(ARGV_node, tmp_number(0.0));
- *aptr = make_string(argv0, strlen(argv0));
- for (i = argc0, j = 1; i < argc; i++) {
- aptr = assoc_lookup(ARGV_node, tmp_number((AWKNUM) j));
- *aptr = make_string(argv[i], strlen(argv[i]));
- j++;
+ register int len;
+ register char *scan;
+ register char *bp, *cp;
+ int search_start = 0;
+ int match_length;
+ int matches = 0;
+ char *buf;
+ struct re_pattern_buffer *rp;
+ NODE *s; /* subst. pattern */
+ NODE *t; /* string to make sub. in; $0 if none given */
+ struct re_registers reregs;
+ unsigned int saveflags;
+ NODE *tmp;
+ NODE **lhs;
+ char *lastbuf;
+ int need_to_free = 0;
+
+ if (tree == NULL)
+ fatal("sub or gsub called with 0 arguments");
+ tmp = tree->lnode;
+ if (tmp->type == Node_regex) {
+ rp = tmp->rereg;
+ if (! strict && ((IGNORECASE_node->var_value->numbr != 0)
+ ^ (tmp->re_case != 0))) {
+ /* recompile since case sensitivity differs */
+ rp = tmp->rereg =
+ mk_re_parse(tmp->re_text,
+ (IGNORECASE_node->var_value->numbr != 0));
+ tmp->re_case = (IGNORECASE_node->var_value->numbr != 0);
+ }
+ } else {
+ need_to_free = 1;
+ rp = make_regexp(force_string(tree_eval(tmp)),
+ (IGNORECASE_node->var_value->numbr != 0));
+ if (rp == NULL)
+ cant_happen();
+ }
+ tree = tree->rnode;
+ if (tree == NULL)
+ fatal("sub or gsub called with only 1 argument");
+ s = force_string(tree_eval(tree->lnode));
+ tree = tree->rnode;
+ deref = 0;
+ field_num = -1;
+ if (tree == NULL) {
+ t = node0_valid ? fields_arr[0] : *get_field(0, 0);
+ lhs = &fields_arr[0];
+ field_num = 0;
+ deref = t;
+ } else {
+ t = tree->lnode;
+ lhs = get_lhs(t, 1);
+ t = force_string(tree_eval(t));
+ }
+ /*
+ * create a private copy of the string
+ */
+ if (t->stref > 1 || (t->flags & PERM)) {
+ saveflags = t->flags;
+ t->flags &= ~MALLOC;
+ tmp = dupnode(t);
+ t->flags = saveflags;
+ do_deref();
+ t = tmp;
+ if (lhs)
+ *lhs = tmp;
+ }
+ lastbuf = t->stptr;
+ do {
+ if (re_search(rp, t->stptr, t->stlen, search_start,
+ t->stlen-search_start, &reregs) == -1
+ || reregs.start[0] == reregs.end[0])
+ break;
+ matches++;
+
+ /*
+ * first, make a pass through the sub. pattern, to calculate
+ * the length of the string after substitution
+ */
+ match_length = reregs.end[0] - reregs.start[0];
+ len = t->stlen - match_length;
+ for (scan = s->stptr; scan < s->stptr + s->stlen; scan++)
+ if (*scan == '&')
+ len += match_length;
+ else if (*scan == '\\' && *(scan+1) == '&') {
+ scan++;
+ len++;
+ } else
+ len++;
+ emalloc(buf, char *, len + 1, "do_sub");
+ bp = buf;
+
+ /*
+ * now, create the result, copying in parts of the original
+ * string
+ */
+ for (scan = t->stptr; scan < t->stptr + reregs.start[0]; scan++)
+ *bp++ = *scan;
+ for (scan = s->stptr; scan < s->stptr + s->stlen; scan++)
+ if (*scan == '&')
+ for (cp = t->stptr + reregs.start[0];
+ cp < t->stptr + reregs.end[0]; cp++)
+ *bp++ = *cp;
+ else if (*scan == '\\' && *(scan+1) == '&') {
+ scan++;
+ *bp++ = *scan;
+ } else
+ *bp++ = *scan;
+ search_start = bp - buf;
+ for (scan = t->stptr + reregs.end[0];
+ scan < t->stptr + t->stlen; scan++)
+ *bp++ = *scan;
+ *bp = '\0';
+ free(lastbuf);
+ t->stptr = buf;
+ lastbuf = buf;
+ t->stlen = len;
+ } while (global && search_start < t->stlen);
+
+ free_temp(s);
+ if (need_to_free) {
+ free(rp->buffer);
+ free(rp->fastmap);
+ free((char *) rp);
+ }
+ if (matches > 0) {
+ if (field_num == 0)
+ set_record(fields_arr[0]->stptr, fields_arr[0]->stlen);
+ t->flags &= ~(NUM|NUMERIC);
}
- ARGC_node = spc_var("ARGC", make_number((AWKNUM) j));
+ field_num = -1;
+ return tmp_number((AWKNUM) matches);
}
+
+NODE *
+do_gsub(tree)
+NODE *tree;
+{
+ return sub_common(tree, 1);
+}
+
+NODE *
+do_sub(tree)
+NODE *tree;
+{
+ return sub_common(tree, 0);
+}
+
diff --git a/awk6.c b/debug.c
index 5e9a82e6..ffc24280 100644
--- a/awk6.c
+++ b/debug.c
@@ -1,58 +1,5 @@
/*
- * awk6.c -- Various debugging routines
- *
- * $Log: awk6.c,v $
- * Revision 1.13 89/03/31 13:26:12 david
- * GNU license
- *
- * Revision 1.12 89/03/29 14:11:54 david
- * delinting
- *
- * Revision 1.11 89/03/24 15:58:04 david
- * HASHNODE becomes NODE
- *
- * Revision 1.10 89/03/21 10:48:51 david
- * minor cleanup
- *
- * Revision 1.9 89/03/15 22:06:37 david
- * remove old case stuff
- *
- * Revision 1.8 88/11/22 13:51:34 david
- * Arnold: changes for case-insensitive matching
- *
- * Revision 1.7 88/11/15 10:28:08 david
- * Arnold: minor cleanup
- *
- * Revision 1.6 88/11/01 12:20:46 david
- * small improvements to debugging code
- *
- * Revision 1.5 88/10/17 20:53:37 david
- * purge FAST
- *
- * Revision 1.4 88/05/31 09:56:39 david
- * oops! fix to last change
- *
- * Revision 1.3 88/05/31 09:25:48 david
- * expunge Node_local_var
- *
- * Revision 1.2 88/04/15 13:15:47 david
- * brought slightly up-to-date
- *
- * Revision 1.1 88/04/08 15:14:38 david
- * Initial revision
- * Revision 1.5 88/04/08 14:48:39 david changes from
- * Arnold Robbins
- *
- * Revision 1.4 88/03/28 14:13:57 david *** empty log message ***
- *
- * Revision 1.3 88/03/18 21:00:15 david Baseline -- hoefully all the
- * functionality of the new awk added. Just debugging and tuning to do.
- *
- * Revision 1.2 87/11/19 14:41:07 david trying to keep it up to date with
- * changes elsewhere ...
- *
- * Revision 1.1 87/10/27 15:23:36 david Initial revision
- *
+ * debug.c -- Various debugging routines
*/
/*
@@ -127,7 +74,7 @@ NODE *n;
pt()
{
- int x;
+ long x;
(void) scanf("%x", &x);
printf("0x%x\n", x);
@@ -597,3 +544,17 @@ do_bp()
}
#endif
+
+#ifdef MEMDEBUG
+
+#undef free
+extern void free();
+
+void
+do_free(s)
+char *s;
+{
+ free(s);
+}
+
+#endif
diff --git a/awk2.c b/eval.c
index 8b433794..4973b595 100644
--- a/awk2.c
+++ b/eval.c
@@ -1,201 +1,5 @@
/*
- * awk2 --- gawk parse tree interpreter
- *
- * $Log: awk2.c,v $
- * Revision 1.51 89/03/31 13:25:34 david
- * GNU license; MSDOS support
- *
- * Revision 1.50 89/03/30 20:57:19 david
- * allow for Node_rule_node (a single rule)
- * avoid calling eval_condition for no pattern
- * plug a memory leak in assign_number
- *
- * Revision 1.49 89/03/29 14:15:07 david
- * delinting
- *
- * Revision 1.48 89/03/26 17:58:53 david
- * changed return of do_printf to void
- *
- * Revision 1.47 89/03/22 22:09:50 david
- * a cleaner way to handle assignment to $n where n > 0
- *
- * Revision 1.46 89/03/22 21:01:14 david
- * delete some obsolete code
- *
- * Revision 1.45 89/03/21 19:25:37 david
- * minor cleanup
- *
- * Revision 1.44 89/03/21 18:24:02 david
- * bug fix in cmp_nodes: strings in which one was a prefix of the other compared equal
- *
- * Revision 1.43 89/03/21 10:55:55 david
- * cleanup and fix of string comparison (0 length was wrong)
- *
- * Revision 1.42 89/03/15 22:01:17 david
- * old case stuff removed
- * new case stuff added
- * fixed % operator
- * strings with embedded \0 can now be compared
- *
- * Revision 1.41 89/03/15 21:32:50 david
- * try to free up memory in as many places as possible
- *
- * Revision 1.40 88/12/15 12:57:31 david
- * make casetable static
- *
- * Revision 1.39 88/12/14 10:50:51 david
- * dupnode() the return from a function
- *
- * Revision 1.38 88/12/13 22:27:04 david
- * macro-front-end tree_eval and other optimizations
- *
- * Revision 1.36 88/12/08 10:51:37 david
- * small correction to source file code
- *
- * Revision 1.35 88/12/07 20:00:35 david
- * changes for incorporating source filename into error messages
- *
- * Revision 1.34 88/12/01 15:04:48 david
- * cleanup and additions for source line number printing in error messages
- *
- * Revision 1.33 88/11/30 15:16:10 david
- * merge FREE_ONE_REFERENCE into do_deref()
- * free more in do_deref
- * in for (i in array) loops, make sure value of i gets freed on each iteration
- *
- * Revision 1.32 88/11/29 09:55:04 david
- * corrections to code that tracks value of NF -- this needs cleanup
- *
- * Revision 1.31 88/11/23 21:40:47 david
- * Arnold: comment cleanup
- *
- * Revision 1.30 88/11/22 13:49:09 david
- * Arnold: changes for case-insensitive matching
- *
- * Revision 1.29 88/11/15 10:22:42 david
- * Arnold: cleanup of comments and #include's
- *
- * Revision 1.28 88/11/14 21:55:38 david
- * Arnold: misc. cleanup and error message on bad regexp
- *
- * Revision 1.27 88/11/14 21:26:52 david
- * update NF on assignment to a field greater than current NF
- *
- * Revision 1.26 88/11/03 15:26:20 david
- * simplify call to in_array(); extensive revision of cmp_nodes and is_a_number
- *
- * Revision 1.25 88/11/01 12:11:57 david
- * DEBUG macro becomes DBG_P; added some debugging code; moved all the
- * compound assignments (+= etc.) into op_assign()
- *
- * Revision 1.24 88/10/25 10:43:05 david
- * intermediate state: more code movement; Node_string et al. -> Node_val;
- * add more debugging code; improve cmp_nodes
- *
- * Revision 1.22 88/10/19 21:57:41 david
- * replace malloc and realloc with error checking versions
- * start to change handling of $0
- *
- * Revision 1.21 88/10/17 20:56:13 david
- * Arnold: better error messages for use of a function in the wrong context
- *
- * Revision 1.20 88/10/13 21:56:41 david
- * cleanup of previous changes
- * change panic() to fatal()
- * detect and bomb on function call with space between name and opening (
- *
- * Revision 1.19 88/10/11 22:19:20 david
- * cleanup
- *
- * Revision 1.18 88/10/04 21:31:33 david
- * minor cleanup
- *
- * Revision 1.17 88/08/22 14:01:19 david
- * fix to set_field() from Jay Finlayson
- *
- * Revision 1.16 88/08/09 14:51:34 david
- * removed bad call to obstack_free() -- there is a lot of memory that is
- * not being properly freed -- this area needs major work
- * changed semantics in eval_condition -- if(expr) should test true if
- * expr is a non-null string, even if the num,erical value is zero -- counter-
- * intuitive but that's what's in the book
- *
- * Revision 1.15 88/06/13 18:02:58 david
- * separate exit value from fact that exit has been called [from Arnold]
- *
- * Revision 1.14 88/06/07 23:39:48 david
- * insubstantial changes
- *
- * Revision 1.13 88/06/06 11:26:39 david
- * get rid of some obsolete code
- * change interface of set_field()
- *
- * Revision 1.12 88/06/05 22:21:36 david
- * local variables are now kept on a stack
- *
- * Revision 1.11 88/06/01 22:06:50 david
- * make sure incases of Node_param_list that the variable is looked up
- *
- * Revision 1.10 88/05/31 09:29:47 david
- * expunge Node_local_var
- *
- * Revision 1.9 88/05/30 09:52:55 david
- * be prepared for NULL return from make_regexp()
- * fix fatal() call
- *
- * Revision 1.8 88/05/26 22:48:48 david
- * fixed regexp matching code
- *
- * Revision 1.7 88/05/16 21:27:09 david
- * comment out obstack_free in interpret() -- it is done in do_file() anyway
- * and was definitely free'ing stuff it shouldn't have
- * change call of func_call() a bit
- * allow get_lhs to be called with other Node types -- return 0; used in
- * do_sub()
- *
- * Revision 1.6 88/05/13 22:00:03 david
- * generalized *_BINDING macros and moved them to awk.h
- * changes to function calling (mostly elsewhere)
- * put into use the Node_var_array type
- *
- * Revision 1.5 88/05/09 21:22:27 david
- * finally (I hope) got the code right in assign_number
- *
- * Revision 1.4 88/05/04 12:23:30 david
- * fflush(stdout) on prints if FAST not def'ed
- * all the assign_* cases were returning the wrong thing
- * fixed Node_in_array code
- * code in assign_number was freeing memory it shouldn't have
- *
- * Revision 1.3 88/04/15 13:12:38 david
- * additional error message
- *
- * Revision 1.2 88/04/12 16:03:24 david
- * fixed previously intoduced bug: all matches succeeded
- *
- * Revision 1.1 88/04/08 15:15:01 david
- * Initial revision
- * Revision 1.7 88/04/08 14:48:33 david changes from
- * Arnold Robbins
- *
- * Revision 1.6 88/03/28 14:13:50 david *** empty log message ***
- *
- * Revision 1.5 88/03/23 22:17:37 david mostly delinting -- a couple of bug
- * fixes
- *
- * Revision 1.4 88/03/18 21:00:10 david Baseline -- hoefully all the
- * functionality of the new awk added. Just debugging and tuning to do.
- *
- * Revision 1.3 87/11/14 15:16:21 david added user-defined functions with
- * return and do-while loops
- *
- * Revision 1.2 87/10/29 21:45:44 david added support for array membership
- * test, as in: if ("yes" in answers) ... this involved one more case: for
- * Node_in_array and rearrangment of the code in assoc_lookup, so that the
- * element can be located without being created
- *
- * Revision 1.1 87/10/27 15:23:28 david Initial revision
- *
+ * eval.c - gawk parse tree interpreter
*/
/*
@@ -223,24 +27,23 @@
extern void do_print();
extern void do_printf();
-extern NODE *func_call();
extern NODE *do_match();
extern NODE *do_sub();
extern NODE *do_getline();
+extern NODE *concat_exp();
extern int in_array();
extern void do_delete();
-
extern double pow();
static int eval_condition();
-static int is_a_number();
static NODE *op_assign();
+static NODE *func_call();
+static NODE *match_op();
NODE *_t; /* used as a temporary in macros */
#ifdef MSDOS
double _msc51bug; /* to get around a bug in MSC 5.1 */
#endif
-NODE *_result; /* holds result of tree_eval, for possible freeing */
NODE *ret_node;
/* More of that debugging stuff */
@@ -250,7 +53,19 @@ NODE *ret_node;
#define DBG_P(X)
#endif
-extern jmp_buf func_tag;
+/* Macros and variables to save and restore function and loop bindings */
+/*
+ * the val variable allows return/continue/break-out-of-context to be
+ * caught and diagnosed
+ */
+#define PUSH_BINDING(stack, x, val) (memcpy ((char *)(stack), (char *)(x), sizeof (jmp_buf)), val++)
+#define RESTORE_BINDING(stack, x, val) (memcpy ((char *)(x), (char *)(stack), sizeof (jmp_buf)), val--)
+
+static jmp_buf loop_tag; /* always the current binding */
+static int loop_tag_valid = 0; /* nonzero when loop_tag valid */
+static int func_tag_valid = 0;
+static jmp_buf func_tag;
+extern int exiting, exit_val;
/*
* This table is used by the regexp routines to do case independant
@@ -318,30 +133,18 @@ char casetable[] = {
* Tree is a bunch of rules to run. Returns zero if it hit an exit()
* statement
*/
+int
interpret(tree)
NODE *tree;
{
- register NODE *t = NULL; /* temporary */
-
- auto jmp_buf loop_tag_stack; /* shallow binding stack for loop_tag */
- static jmp_buf loop_tag;/* always the current binding */
- static int loop_tag_valid = 0; /* nonzero when loop_tag valid */
-
+ volatile jmp_buf loop_tag_stack; /* shallow binding stack for loop_tag */
static jmp_buf rule_tag;/* tag the rule currently being run, for NEXT
* and EXIT statements. It is static because
* there are no nested rules */
-
- register NODE **lhs; /* lhs == Left Hand Side for assigns, etc */
- register struct search *l; /* For array_for */
-
-
- extern NODE **fields_arr;
- extern int exiting, exit_val;
-
- /*
- * clean up temporary strings created by evaluating expressions in
- * previous recursive calls
- */
+ register NODE *t = NULL;/* temporary */
+ volatile NODE **lhs; /* lhs == Left Hand Side for assigns, etc */
+ volatile struct search *l; /* For array_for */
+ volatile NODE *stable_tree;
if (tree == NULL)
return 1;
@@ -353,7 +156,9 @@ NODE *tree;
tree = t->lnode;
/* FALL THROUGH */
case Node_rule_node:
- switch (_setjmp(rule_tag)) {
+ sourceline = tree->source_line;
+ source = tree->source_file;
+ switch (setjmp(rule_tag)) {
case 0: /* normal non-jump */
/* test pattern, if any */
if (tree->lnode == NULL
@@ -390,6 +195,8 @@ NODE *tree;
return 1;
case TAG_BREAK:
return 0;
+ default:
+ cant_happen();
}
if (t == NULL)
break;
@@ -418,11 +225,12 @@ NODE *tree;
PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid);
DBG_P(("WHILE", tree->lnode));
- while (eval_condition(tree->lnode)) {
- switch (_setjmp(loop_tag)) {
+ stable_tree = tree;
+ while (eval_condition(stable_tree->lnode)) {
+ switch (setjmp(loop_tag)) {
case 0: /* normal non-jump */
- DBG_P(("DO", tree->rnode));
- (void) interpret(tree->rnode);
+ DBG_P(("DO", stable_tree->rnode));
+ (void) interpret(stable_tree->rnode);
break;
case TAG_CONTINUE: /* continue statement */
break;
@@ -438,12 +246,12 @@ NODE *tree;
case Node_K_do:
PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid);
-
+ stable_tree = tree;
do {
- switch (_setjmp(loop_tag)) {
+ switch (setjmp(loop_tag)) {
case 0: /* normal non-jump */
- DBG_P(("DO", tree->rnode));
- (void) interpret(tree->rnode);
+ DBG_P(("DO", stable_tree->rnode));
+ (void) interpret(stable_tree->rnode);
break;
case TAG_CONTINUE: /* continue statement */
break;
@@ -453,27 +261,26 @@ NODE *tree;
default:
cant_happen();
}
- DBG_P(("WHILE", tree->lnode));
- } while (eval_condition(tree->lnode));
+ DBG_P(("WHILE", stable_tree->lnode));
+ } while (eval_condition(stable_tree->lnode));
RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid);
break;
case Node_K_for:
PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid);
-
DBG_P(("FOR", tree->forloop->init));
(void) interpret(tree->forloop->init);
-
DBG_P(("FOR.WHILE", tree->forloop->cond));
- while (eval_condition(tree->forloop->cond)) {
- switch (_setjmp(loop_tag)) {
+ stable_tree = tree;
+ while (eval_condition(stable_tree->forloop->cond)) {
+ switch (setjmp(loop_tag)) {
case 0: /* normal non-jump */
- DBG_P(("FOR.DO", tree->lnode));
- (void) interpret(tree->lnode);
+ DBG_P(("FOR.DO", stable_tree->lnode));
+ (void) interpret(stable_tree->lnode);
/* fall through */
case TAG_CONTINUE: /* continue statement */
- DBG_P(("FOR.INCR", tree->forloop->incr));
- (void) interpret(tree->forloop->incr);
+ DBG_P(("FOR.INCR", stable_tree->forloop->incr));
+ (void) interpret(stable_tree->forloop->incr);
break;
case TAG_BREAK: /* break statement */
RESTORE_BINDING(loop_tag_stack, loop_tag, loop_tag_valid);
@@ -490,22 +297,23 @@ NODE *tree;
#define arrvar forloop->incr
PUSH_BINDING(loop_tag_stack, loop_tag, loop_tag_valid);
DBG_P(("AFOR.VAR", tree->hakvar));
- lhs = get_lhs(tree->hakvar, 1);
+ lhs = (volatile NODE **) get_lhs(tree->hakvar, 1);
t = tree->arrvar;
- if (tree->arrvar->type == Node_param_list)
- t = stack_ptr[tree->arrvar->param_cnt];
- for (l = assoc_scan(t); l; l = assoc_next(l)) {
- deref = *lhs;
+ if (t->type == Node_param_list)
+ t = stack_ptr[t->param_cnt];
+ stable_tree = tree;
+ for (l = assoc_scan(t); l; l = assoc_next((struct search *)l)) {
+ deref = *((NODE **) lhs);
do_deref();
*lhs = dupnode(l->retval);
if (field_num == 0)
set_record(fields_arr[0]->stptr,
fields_arr[0]->stlen);
DBG_P(("AFOR.NEXTIS", *lhs));
- switch (_setjmp(loop_tag)) {
+ switch (setjmp(loop_tag)) {
case 0:
- DBG_P(("AFOR.DO", tree->lnode));
- (void) interpret(tree->lnode);
+ DBG_P(("AFOR.DO", stable_tree->lnode));
+ (void) interpret(stable_tree->lnode);
case TAG_CONTINUE:
break;
@@ -525,14 +333,14 @@ NODE *tree;
DBG_P(("BREAK", NULL));
if (loop_tag_valid == 0)
fatal("unexpected break");
- _longjmp(loop_tag, TAG_BREAK);
+ longjmp(loop_tag, TAG_BREAK);
break;
case Node_K_continue:
DBG_P(("CONTINUE", NULL));
if (loop_tag_valid == 0)
fatal("unexpected continue");
- _longjmp(loop_tag, TAG_CONTINUE);
+ longjmp(loop_tag, TAG_CONTINUE);
break;
case Node_K_print:
@@ -547,7 +355,7 @@ NODE *tree;
case Node_K_next:
DBG_P(("NEXT", NULL));
- _longjmp(rule_tag, TAG_CONTINUE);
+ longjmp(rule_tag, TAG_CONTINUE);
break;
case Node_K_exit:
@@ -560,17 +368,20 @@ NODE *tree;
*/
DBG_P(("EXIT", NULL));
exiting = 1;
- if (tree)
- exit_val = (int) force_number(tree_eval(tree->lnode));
- free_result();
- _longjmp(rule_tag, TAG_BREAK);
+ if (tree) {
+ t = tree_eval(tree->lnode);
+ exit_val = (int) force_number(t);
+ }
+ free_temp(t);
+ longjmp(rule_tag, TAG_BREAK);
break;
case Node_K_return:
DBG_P(("RETURN", NULL));
- ret_node = dupnode(tree_eval(tree->lnode));
- ret_node->flags |= TEMP;
- _longjmp(func_tag, TAG_RETURN);
+ t = tree_eval(tree->lnode);
+ ret_node = dupnode(t);
+ free_temp(t);
+ longjmp(func_tag, TAG_RETURN);
break;
default:
@@ -579,8 +390,8 @@ NODE *tree;
* value.
*/
DBG_P(("E", NULL));
- (void) tree_eval(tree);
- free_result();
+ t = tree_eval(tree);
+ free_temp(t);
break;
}
return 1;
@@ -598,11 +409,9 @@ NODE *tree;
int di;
AWKNUM x, x2;
long lx;
- struct re_pattern_buffer *rp;
extern NODE **fields_arr;
- if (tree->type != Node_var)
- source = tree->source_file;
+ source = tree->source_file;
sourceline = tree->source_line;
switch (tree->type) {
case Node_and:
@@ -632,15 +441,6 @@ NODE *tree;
DBG_P(("IN_ARRAY", tree));
return tmp_number((AWKNUM) in_array(tree->lnode, tree->rnode));
- case Node_K_match:
- DBG_P(("MATCH", tree));
- return do_match(tree);
-
- case Node_sub:
- case Node_gsub:
- DBG_P(("SUB", tree));
- return do_sub(tree);
-
case Node_func_call:
DBG_P(("func_call", tree));
return func_call(tree->rnode, tree->lnode);
@@ -665,8 +465,9 @@ NODE *tree;
case Node_unary_minus:
DBG_P(("UMINUS", tree));
- x = -force_number(tree_eval(tree->subnode));
- free_result();
+ t1 = tree_eval(tree->subnode);
+ x = -force_number(t1);
+ free_temp(t1);
return tmp_number(x);
case Node_cond_exp:
@@ -675,53 +476,34 @@ NODE *tree;
DBG_P(("True", tree->rnode->lnode));
return tree_eval(tree->rnode->lnode);
}
- DBG_P(("False", tree->rnode->rnode));
- return tree_eval(tree->rnode->rnode);
+ DBG_P(("False", tree->rnode->rnode));
+ return tree_eval(tree->rnode->rnode);
case Node_match:
case Node_nomatch:
- DBG_P(("ASSIGN_[no]match", tree));
- t1 = force_string(tree_eval(tree->lnode));
- if (tree->rnode->type == Node_regex) {
- rp = tree->rnode->rereg;
- if (!strict && ((IGNORECASE_node->var_value->numbr != 0)
- ^ (tree->rnode->re_case != 0))) {
- /* recompile since case sensitivity differs */
- rp = tree->rnode->rereg =
- mk_re_parse(tree->rnode->re_text,
- (IGNORECASE_node->var_value->numbr != 0));
- tree->rnode->re_case = (IGNORECASE_node->var_value->numbr != 0);
- }
- } else {
- rp = make_regexp(force_string(tree_eval(tree->rnode)),
- (IGNORECASE_node->var_value->numbr != 0));
- if (rp == NULL)
- cant_happen();
- }
- i = re_search(rp, t1->stptr, t1->stlen, 0, t1->stlen,
- (struct re_registers *) NULL);
- i = (i == -1) ^ (tree->type == Node_match);
- free_temp(t1);
- return tmp_number((AWKNUM) i);
+ case Node_regex:
+ DBG_P(("[no]match_op", tree));
+ return match_op(tree);
case Node_func:
fatal("function `%s' called with space between name and (,\n%s",
tree->lnode->param,
"or used in other expression context");
- /* assignments */
+ /* assignments */
case Node_assign:
DBG_P(("ASSIGN", tree));
r = tree_eval(tree->rnode);
lhs = get_lhs(tree->lnode, 1);
*lhs = dupnode(r);
+ free_temp(r);
do_deref();
if (field_num == 0)
set_record(fields_arr[0]->stptr, fields_arr[0]->stlen);
field_num = -1;
return *lhs;
- /* other assignment types are easier because they are numeric */
+ /* other assignment types are easier because they are numeric */
case Node_preincrement:
case Node_predecrement:
case Node_postincrement:
@@ -733,12 +515,10 @@ NODE *tree;
case Node_assign_plus:
case Node_assign_minus:
return op_assign(tree);
+ default:
+ break; /* handled below */
}
- /*
- * Note that if TREE is invalid, gawk will probably bomb in one of
- * these tree_evals here.
- */
/* evaluate subtrees in order to do binary operation, then keep going */
t1 = tree_eval(tree->lnode);
t2 = tree_eval(tree->rnode);
@@ -750,13 +530,12 @@ NODE *tree;
t2 = force_string(t2);
r = newnode(Node_val);
- r->flags = (STR|TEMP);
+ r->flags |= (STR|TEMP);
r->stlen = t1->stlen + t2->stlen;
r->stref = 1;
emalloc(r->stptr, char *, r->stlen + 1, "tree_eval");
- bcopy(t1->stptr, r->stptr, t1->stlen);
- bcopy(t2->stptr, r->stptr + t1->stlen, t2->stlen);
- r->stptr[r->stlen] = '\0';
+ memcpy(r->stptr, t1->stptr, t1->stlen);
+ memcpy(r->stptr + t1->stlen, t2->stptr, t2->stlen + 1);
free_temp(t1);
free_temp(t2);
return r;
@@ -789,8 +568,12 @@ NODE *tree;
case Node_geq:
DBG_P(("GREATER_THAN_EQUAL", tree));
return tmp_number((AWKNUM) (di >= 0));
+ default:
+ cant_happen();
}
break;
+ default:
+ break; /* handled below */
}
(void) force_number(t1);
@@ -799,7 +582,16 @@ NODE *tree;
switch (tree->type) {
case Node_exp:
DBG_P(("EXPONENT", tree));
- x = pow((double) t1->numbr, (double) t2->numbr);
+ if ((lx = t2->numbr) == t2->numbr) { /* integer exponent */
+ if (lx == 0)
+ x = 1;
+ else {
+ /* doing it this way should be more precise */
+ for (x = x2 = t1->numbr; --lx; )
+ x *= x2;
+ }
+ } else
+ x = pow((double) t1->numbr, (double) t2->numbr);
free_temp(t1);
free_temp(t2);
return tmp_number(x);
@@ -815,10 +607,10 @@ NODE *tree;
DBG_P(("DIVIDE", tree));
x = t2->numbr;
free_temp(t2);
- if (x == (AWKNUM) 0) {
- free_temp(t1);
- return tmp_number((AWKNUM) 0);
- } else {
+ if (x == (AWKNUM) 0)
+ fatal("division by zero attempted");
+ /* NOTREACHED */
+ else {
x = t1->numbr / x;
free_temp(t1);
return tmp_number(x);
@@ -828,10 +620,9 @@ NODE *tree;
DBG_P(("MODULUS", tree));
x = t2->numbr;
free_temp(t2);
- if (x == (AWKNUM) 0) {
- free_temp(t1);
- return tmp_number((AWKNUM) 0);
- }
+ if (x == (AWKNUM) 0)
+ fatal("division by zero attempted in mod");
+ /* NOTREACHED */
lx = t1->numbr / x; /* assignment to long truncates */
x2 = lx * x;
x = t1->numbr - x2;
@@ -886,7 +677,7 @@ AWKNUM value;
if ((n->flags & STR) && (n->flags & (MALLOC|TEMP)))
free(n->stptr);
n->numbr = value;
- n->flags |= NUM;
+ n->flags |= (NUM|NUMERIC);
n->flags &= ~STR;
n->stref = 0;
deref = 0;
@@ -934,120 +725,38 @@ NODE *tree;
*/
t1 = tree_eval(tree);
- if (t1->flags & STR)
- ret = t1->stlen != 0;
- else
+ if (t1->flags & NUMERIC)
ret = t1->numbr != 0.0;
+ else
+ ret = t1->stlen != 0;
free_temp(t1);
return ret;
}
-/*
- * strtod() would have been better, except (1) real awk is needlessly
- * restrictive in what strings it will consider to be numbers, and (2) I
- * couldn't find the public domain version anywhere handy.
- */
-static int
-is_a_number(str) /* does the string str have pure-numeric syntax? */
-char *str; /* don't convert it, assume that atof is better */
-{
- if (*str == 0)
- return 0; /* null string is not equal to 0 */
-
- if (*str == '-')
- str++;
- if (*str == 0)
- return 0;
- /* must be either . or digits (.4 is legal) */
- if (*str != '.' && !isdigit(*str))
- return 0;
- while (isdigit(*str))
- str++;
- if (*str == '.') {
- str++;
- while (isdigit(*str))
- str++;
- }
-
- /*
- * curiously, real awk DOESN'T consider "1E1" to be equal to 10! Or
- * even equal to 1E1 for that matter! For a laugh, try:
- * awk 'BEGIN {if ("1E1" == 1E1) print "eq"; else print "neq"; exit}'
- * Since this behavior is QUITE curious, I include the code for the
- * adventurous. One might also feel like skipping leading whitespace
- * (awk doesn't) and allowing a leading + (awk doesn't).
- */
-#ifdef Allow_Exponents
- if (*str == 'e' || *str == 'E') {
- str++;
- if (*str == '+' || *str == '-')
- str++;
- if (!isdigit(*str))
- return 0;
- while (isdigit(*str))
- str++;
- }
-#endif
- /*
- * if we have digested the whole string, we are
- * successful
- */
- return (*str == 0);
-}
-
int
cmp_nodes(t1, t2)
NODE *t1, *t2;
{
AWKNUM d;
+ AWKNUM d1;
+ AWKNUM d2;
int ret;
int len1, len2;
if (t1 == t2)
return 0;
- if ((t1->flags & NUM)) {
- if ((t2->flags & NUM))
- d = t1->numbr - t2->numbr;
- else if (is_a_number(t2->stptr))
- d = t1->numbr - force_number(t2);
- else {
- t1 = force_string(t1);
- goto strings;
- }
+ d1 = force_number(t1);
+ d2 = force_number(t2);
+ if ((t1->flags & NUMERIC) && (t2->flags & NUMERIC)) {
+ d = d1 - d2;
if (d == 0.0) /* from profiling, this is most common */
return 0;
if (d > 0.0)
return 1;
return -1;
}
- if ((t2->flags & NUM)) {
- if (is_a_number(t1->stptr))
- d = force_number(t1) - t2->numbr;
- else {
- t2 = force_string(t2);
- goto strings;
- }
- if (d == 0.0) /* from profiling, this is most common */
- return 0;
- if (d > 0.0)
- return 1;
- return -1;
- }
- if (is_a_number(t1->stptr) && is_a_number(t2->stptr)) {
- /*
- * following two statements are this way because force_number
- * is a macro
- */
- d = force_number(t1);
- d = d - force_number(t2);
- if (d == 0.0) /* from profiling, this is most common */
- return 0;
- if (d > 0.0)
- return 1;
- return -1;
- }
-
-strings:
+ t1 = force_string(t1);
+ t2 = force_string(t2);
len1 = t1->stlen;
len2 = t2->stlen;
if (len1 == 0) {
@@ -1063,27 +772,6 @@ strings:
return ret;
}
-#ifdef NOMEMCMP
-/*
- * memcmp --- compare strings.
- *
- * We use our own routine since it has to act like strcmp() for return
- * value, and the BSD manual says bcmp() only returns zero/non-zero.
- */
-
-static int
-memcmp (s1, s2, l)
-register char *s1, *s2;
-register int l;
-{
- for (; l--; s1++, s2++) {
- if (*s1 != *s2)
- return (*s1 - *s2);
- }
- return (*--s1 - *--s2);
-}
-#endif
-
static NODE *
op_assign(tree)
NODE *tree;
@@ -1092,6 +780,7 @@ NODE *tree;
NODE **lhs;
AWKNUM t1, t2;
long ltemp;
+ NODE *tmp;
lhs = get_lhs(tree->lnode, 1);
lval = force_number(*lhs);
@@ -1118,14 +807,27 @@ NODE *tree;
set_record(fields_arr[0]->stptr, fields_arr[0]->stlen);
field_num = -1;
return tmp_number(lval);
+ default:
+ break; /* handled below */
}
- rval = force_number(tree_eval(tree->rnode));
- free_result();
+ tmp = tree_eval(tree->rnode);
+ rval = force_number(tmp);
+ free_temp(tmp);
switch(tree->type) {
case Node_assign_exp:
DBG_P(("ASSIGN_exp", tree));
- assign_number(lhs, (AWKNUM) pow((double) lval, (double) rval));
+ if ((ltemp = rval) == rval) { /* integer exponent */
+ if (ltemp == 0)
+ assign_number(lhs, (AWKNUM) 1);
+ else {
+ /* doing it this way should be more precise */
+ for (t1 = t2 = lval; --ltemp; )
+ t1 *= t2;
+ assign_number(lhs, t1);
+ }
+ } else
+ assign_number(lhs, (AWKNUM) pow((double) lval, (double) rval));
break;
case Node_assign_times:
@@ -1135,11 +837,15 @@ NODE *tree;
case Node_assign_quotient:
DBG_P(("ASSIGN_quotient", tree));
+ if (rval == (AWKNUM) 0)
+ fatal("division by zero attempted in /=");
assign_number(lhs, lval / rval);
break;
case Node_assign_mod:
DBG_P(("ASSIGN_mod", tree));
+ if (rval == (AWKNUM) 0)
+ fatal("division by zero attempted in %=");
ltemp = lval / rval; /* assignment to long truncates */
t1 = ltemp * rval;
t2 = lval - t1;
@@ -1155,6 +861,8 @@ NODE *tree;
DBG_P(("ASSIGN_minus", tree));
assign_number(lhs, lval - rval);
break;
+ default:
+ cant_happen();
}
do_deref();
if (field_num == 0)
@@ -1163,3 +871,265 @@ NODE *tree;
return *lhs;
}
+NODE **stack_ptr;
+
+static NODE *
+func_call(name, arg_list)
+NODE *name; /* name is a Node_val giving function name */
+NODE *arg_list; /* Node_expression_list of calling args. */
+{
+ register NODE *arg, *argp, *r;
+ NODE *n, *f;
+ volatile jmp_buf func_tag_stack;
+ volatile jmp_buf loop_tag_stack;
+ volatile int save_loop_tag_valid = 0;
+ volatile NODE **save_stack, *save_ret_node;
+ NODE **local_stack, **sp;
+ int count;
+ extern NODE *ret_node;
+
+ /*
+ * retrieve function definition node
+ */
+ f = lookup(variables, name->stptr);
+ if (!f || f->type != Node_func)
+ fatal("function `%s' not defined", name->stptr);
+#ifdef FUNC_TRACE
+ fprintf(stderr, "function %s called\n", name->stptr);
+#endif
+ count = f->lnode->param_cnt;
+ emalloc(local_stack, NODE **, count * sizeof(NODE *), "func_call");
+ sp = local_stack;
+
+ /*
+ * for each calling arg. add NODE * on stack
+ */
+ for (argp = arg_list; count && argp != NULL; argp = argp->rnode) {
+ arg = argp->lnode;
+ r = newnode(Node_var);
+ /*
+ * call by reference for arrays; see below also
+ */
+ if (arg->type == Node_param_list)
+ arg = stack_ptr[arg->param_cnt];
+ if (arg->type == Node_var_array)
+ *r = *arg;
+ else {
+ n = tree_eval(arg);
+ r->lnode = dupnode(n);
+ r->rnode = (NODE *) NULL;
+ free_temp(n);
+ }
+ *sp++ = r;
+ count--;
+ }
+ if (argp != NULL) /* left over calling args. */
+ warning(
+ "function `%s' called with more arguments than declared",
+ name->stptr);
+ /*
+ * add remaining params. on stack with null value
+ */
+ while (count-- > 0) {
+ r = newnode(Node_var);
+ r->lnode = Nnull_string;
+ r->rnode = (NODE *) NULL;
+ *sp++ = r;
+ }
+
+ /*
+ * Execute function body, saving context, as a return statement
+ * will longjmp back here.
+ *
+ * Have to save and restore the loop_tag stuff so that a return
+ * inside a loop in a function body doesn't scrog any loops going
+ * on in the main program. We save the necessary info in variables
+ * local to this function so that function nesting works OK.
+ * We also only bother to save the loop stuff if we're in a loop
+ * when the function is called.
+ */
+ if (loop_tag_valid) {
+ int junk = 0;
+
+ save_loop_tag_valid = (volatile int) loop_tag_valid;
+ PUSH_BINDING(loop_tag_stack, loop_tag, junk);
+ loop_tag_valid = 0;
+ }
+ save_stack = (volatile NODE **) stack_ptr;
+ stack_ptr = local_stack;
+ PUSH_BINDING(func_tag_stack, func_tag, func_tag_valid);
+ save_ret_node = (volatile NODE *) ret_node;
+ ret_node = Nnull_string; /* default return value */
+ if (setjmp(func_tag) == 0)
+ (void) interpret(f->rnode);
+
+ r = ret_node;
+ ret_node = (NODE *) save_ret_node;
+ RESTORE_BINDING(func_tag_stack, func_tag, func_tag_valid);
+ stack_ptr = (NODE **) save_stack;
+
+ /*
+ * here, we pop each parameter and check whether
+ * it was an array. If so, and if the arg. passed in was
+ * a simple variable, then the value should be copied back.
+ * This achieves "call-by-reference" for arrays.
+ */
+ sp = local_stack;
+ count = f->lnode->param_cnt;
+ for (argp = arg_list; count > 0 && argp != NULL; argp = argp->rnode) {
+ arg = argp->lnode;
+ n = *sp++;
+ if (arg->type == Node_var && n->type == Node_var_array) {
+ arg->var_array = n->var_array;
+ arg->type = Node_var_array;
+ }
+ deref = n->lnode;
+ do_deref();
+ freenode(n);
+ count--;
+ }
+ while (count-- > 0) {
+ n = *sp++;
+ deref = n->lnode;
+ do_deref();
+ freenode(n);
+ }
+ free((char *) local_stack);
+
+ /* Restore the loop_tag stuff if necessary. */
+ if (save_loop_tag_valid) {
+ int junk = 0;
+
+ loop_tag_valid = (int) save_loop_tag_valid;
+ RESTORE_BINDING(loop_tag_stack, loop_tag, junk);
+ }
+
+ if (!(r->flags & PERM))
+ r->flags |= TEMP;
+ return r;
+}
+
+/*
+ * This returns a POINTER to a node pointer. get_lhs(ptr) is the current
+ * value of the var, or where to store the var's new value
+ */
+
+NODE **
+get_lhs(ptr, assign)
+NODE *ptr;
+int assign; /* this is being called for the LHS of an assign. */
+{
+ register NODE **aptr;
+ NODE *n;
+
+#ifdef DEBUG
+ if (ptr == NULL)
+ cant_happen();
+#endif
+ deref = NULL;
+ field_num = -1;
+ switch (ptr->type) {
+ case Node_var:
+ case Node_var_array:
+ if (ptr == NF_node && (int) NF_node->var_value->numbr == -1)
+ (void) get_field(HUGE-1, assign); /* parse record */
+ deref = ptr->var_value;
+#ifdef DEBUG
+ if (deref->type != Node_val)
+ cant_happen();
+ if (deref->flags == 0)
+ cant_happen();
+#endif
+ return &(ptr->var_value);
+
+ case Node_param_list:
+ n = stack_ptr[ptr->param_cnt];
+ deref = n->var_value;
+#ifdef DEBUG
+ if (deref->type != Node_val)
+ cant_happen();
+ if (deref->flags == 0)
+ cant_happen();
+#endif
+ return &(n->var_value);
+
+ case Node_field_spec:
+ n = tree_eval(ptr->lnode);
+ field_num = (int) force_number(n);
+ free_temp(n);
+ if (field_num < 0)
+ fatal("attempt to access field %d", field_num);
+ aptr = get_field(field_num, assign);
+ deref = *aptr;
+ return aptr;
+
+ case Node_subscript:
+ n = ptr->lnode;
+ if (n->type == Node_param_list)
+ n = stack_ptr[n->param_cnt];
+ aptr = assoc_lookup(n, concat_exp(ptr->rnode));
+ deref = *aptr;
+#ifdef DEBUG
+ if (deref->type != Node_val)
+ cant_happen();
+ if (deref->flags == 0)
+ cant_happen();
+#endif
+ return aptr;
+ case Node_func:
+ fatal ("`%s' is a function, assignment is not allowed",
+ ptr->lnode->param);
+ default:
+ cant_happen();
+ }
+ return 0;
+}
+
+static NODE *
+match_op(tree)
+NODE *tree;
+{
+ NODE *t1;
+ struct re_pattern_buffer *rp;
+ int i;
+ int match = 1;
+
+ if (tree->type == Node_nomatch)
+ match = 0;
+ if (tree->type == Node_regex)
+ t1 = WHOLELINE;
+ else {
+ if (tree->lnode)
+ t1 = force_string(tree_eval(tree->lnode));
+ else
+ t1 = WHOLELINE;
+ tree = tree->rnode;
+ }
+ if (tree->type == Node_regex) {
+ rp = tree->rereg;
+ if (!strict && ((IGNORECASE_node->var_value->numbr != 0)
+ ^ (tree->re_case != 0))) {
+ /* recompile since case sensitivity differs */
+ rp = tree->rereg =
+ mk_re_parse(tree->re_text,
+ (IGNORECASE_node->var_value->numbr != 0));
+ tree->re_case =
+ (IGNORECASE_node->var_value->numbr != 0);
+ }
+ } else {
+ rp = make_regexp(force_string(tree_eval(tree)),
+ (IGNORECASE_node->var_value->numbr != 0));
+ if (rp == NULL)
+ cant_happen();
+ }
+ i = re_search(rp, t1->stptr, t1->stlen, 0, t1->stlen,
+ (struct re_registers *) NULL);
+ i = (i == -1) ^ (match == 1);
+ free_temp(t1);
+ if (tree->type != Node_regex) {
+ free(rp->buffer);
+ free(rp->fastmap);
+ free((char *) rp);
+ }
+ return tmp_number((AWKNUM) i);
+}
diff --git a/field.c b/field.c
new file mode 100644
index 00000000..205b534b
--- /dev/null
+++ b/field.c
@@ -0,0 +1,412 @@
+/*
+ * field.c - routines for dealing with fields and record parsing
+ */
+
+/*
+ * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
+ *
+ * This file is part of GAWK, the GNU implementation of the
+ * AWK Progamming Language.
+ *
+ * GAWK is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 1, or (at your option)
+ * any later version.
+ *
+ * GAWK is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with GAWK; see the file COPYING. If not, write to
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#include "awk.h"
+
+extern void assoc_clear();
+extern int a_get_three();
+extern int get_rs();
+
+static char *get_fs();
+static int re_split();
+static int parse_fields();
+static void set_element();
+
+char *line_buf = NULL; /* holds current input line */
+
+static char *parse_extent; /* marks where to restart parse of record */
+static int parse_high_water=0; /* field number that we have parsed so far */
+static char f_empty[] = "";
+static char *save_fs = " "; /* save current value of FS when line is read,
+ * to be used in deferred parsing
+ */
+
+
+NODE **fields_arr; /* array of pointers to the field nodes */
+NODE node0; /* node for $0 which never gets free'd */
+int node0_valid = 1; /* $(>0) has not been changed yet */
+
+void
+init_fields()
+{
+ emalloc(fields_arr, NODE **, sizeof(NODE *), "init_fields");
+ node0.type = Node_val;
+ node0.stref = 0;
+ node0.stptr = "";
+ node0.flags = (STR|PERM); /* never free buf */
+ fields_arr[0] = &node0;
+}
+
+/*
+ * Danger! Must only be called for fields we know have just been blanked, or
+ * fields we know don't exist yet.
+ */
+
+/*ARGSUSED*/
+static void
+set_field(num, str, len, dummy)
+int num;
+char *str;
+int len;
+NODE *dummy; /* not used -- just to make interface same as set_element */
+{
+ NODE *n;
+ int t;
+ static int nf_high_water = 0;
+
+ if (num > nf_high_water) {
+ erealloc(fields_arr, NODE **, (num + 1) * sizeof(NODE *), "set_field");
+ nf_high_water = num;
+ }
+ /* fill in fields that don't exist */
+ for (t = parse_high_water + 1; t < num; t++)
+ fields_arr[t] = Nnull_string;
+ n = make_string(str, len);
+ (void) force_number(n);
+ fields_arr[num] = n;
+ parse_high_water = num;
+}
+
+/* Someone assigned a value to $(something). Fix up $0 to be right */
+static void
+rebuild_record()
+{
+ register int tlen;
+ register NODE *tmp;
+ NODE *ofs;
+ char *ops;
+ register char *cops;
+ register NODE **ptr;
+ register int ofslen;
+
+ tlen = 0;
+ ofs = force_string(OFS_node->var_value);
+ ofslen = ofs->stlen;
+ ptr = &fields_arr[parse_high_water];
+ while (ptr > &fields_arr[0]) {
+ tmp = force_string(*ptr);
+ tlen += tmp->stlen;
+ ptr--;
+ }
+ tlen += (parse_high_water - 1) * ofslen;
+ emalloc(ops, char *, tlen + 1, "fix_fields");
+ cops = ops;
+ ops[0] = '\0';
+ for (ptr = &fields_arr[1]; ptr <= &fields_arr[parse_high_water]; ptr++) {
+ tmp = *ptr;
+ if (tmp->stlen == 1)
+ *cops++ = tmp->stptr[0];
+ else if (tmp->stlen != 0) {
+ memcpy(cops, tmp->stptr, tmp->stlen);
+ cops += tmp->stlen;
+ }
+ if (ptr != &fields_arr[parse_high_water]) {
+ if (ofslen == 1)
+ *cops++ = ofs->stptr[0];
+ else if (ofslen != 0) {
+ memcpy(cops, ofs->stptr, ofslen);
+ cops += ofslen;
+ }
+ }
+ }
+ tmp = make_string(ops, tlen);
+ free(ops);
+ deref = fields_arr[0];
+ do_deref();
+ fields_arr[0] = tmp;
+}
+
+/*
+ * setup $0, but defer parsing rest of line until reference is made to $(>0)
+ * or to NF. At that point, parse only as much as necessary.
+ */
+void
+set_record(buf, cnt)
+char *buf;
+int cnt;
+{
+ register int i;
+
+ assign_number(&NF_node->var_value, (AWKNUM)-1);
+ for (i = 1; i <= parse_high_water; i++) {
+ deref = fields_arr[i];
+ do_deref();
+ }
+ parse_high_water = 0;
+ node0_valid = 1;
+ if (buf == line_buf) {
+ deref = fields_arr[0];
+ do_deref();
+ save_fs = get_fs();
+ node0.type = Node_val;
+ node0.stptr = buf;
+ node0.stlen = cnt;
+ node0.stref = 1;
+ node0.flags = (STR|PERM); /* never free buf */
+ fields_arr[0] = &node0;
+ }
+}
+
+NODE **
+get_field(num, assign)
+int num;
+int assign; /* this field is on the LHS of an assign */
+{
+ int n;
+
+ /*
+ * if requesting whole line but some other field has been altered,
+ * then the whole line must be rebuilt
+ */
+ if (num == 0 && (node0_valid == 0 || assign)) {
+ /* first, parse remainder of input record */
+ if (NF_node->var_value->numbr == -1) {
+ if (parse_high_water == 0)
+ parse_extent = node0.stptr;
+ n = parse_fields(HUGE-1, &parse_extent,
+ node0.stlen - (parse_extent - node0.stptr),
+ save_fs, set_field, (NODE *)NULL);
+ assign_number(&NF_node->var_value, (AWKNUM)n);
+ }
+ if (node0_valid == 0)
+ rebuild_record();
+ return &fields_arr[0];
+ }
+ if (num > 0 && assign)
+ node0_valid = 0;
+ if (num <= parse_high_water) /* we have already parsed this field */
+ return &fields_arr[num];
+ if (parse_high_water == 0 && num > 0) /* starting at the beginning */
+ parse_extent = fields_arr[0]->stptr;
+ /*
+ * parse up to num fields, calling set_field() for each, and saving
+ * in parse_extent the point where the parse left off
+ */
+ n = parse_fields(num, &parse_extent,
+ fields_arr[0]->stlen - (parse_extent-fields_arr[0]->stptr),
+ save_fs, set_field, (NODE *)NULL);
+ if (num == HUGE-1)
+ num = n;
+ if (n < num) { /* requested field number beyond end of record;
+ * set_field will just extend the number of fields,
+ * with empty fields
+ */
+ set_field(num, f_empty, 0, (NODE *) NULL);
+ /*
+ * if this field is onthe LHS of an assignment, then we want to
+ * set NF to this value, below
+ */
+ if (assign)
+ n = num;
+ }
+ /*
+ * if we reached the end of the record, set NF to the number of fields
+ * so far. Note that num might actually refer to a field that
+ * is beyond the end of the record, but we won't set NF to that value at
+ * this point, since this is only a reference to the field and NF
+ * only gets set if the field is assigned to -- in this case n has
+ * been set to num above
+ */
+ if (*parse_extent == '\0')
+ assign_number(&NF_node->var_value, (AWKNUM)n);
+
+ return &fields_arr[num];
+}
+
+/*
+ * this is called both from get_field() and from do_split()
+ */
+static int
+parse_fields(up_to, buf, len, fs, set, n)
+int up_to; /* parse only up to this field number */
+char **buf; /* on input: string to parse; on output: point to start next */
+int len;
+register char *fs;
+void (*set) (); /* routine to set the value of the parsed field */
+NODE *n;
+{
+ char *s = *buf;
+ register char *field;
+ register char *scan;
+ register char *end = s + len;
+ int NF = parse_high_water;
+ char rs = get_rs();
+
+
+ if (up_to == HUGE)
+ NF = 0;
+ if (*fs && *(fs + 1) != '\0') { /* fs is a regexp */
+ struct re_registers reregs;
+
+ scan = s;
+ if (rs == 0 && STREQ(FS_node->var_value->stptr, " ")) {
+ while ((*scan == '\n' || *scan == ' ' || *scan == '\t')
+ && scan < end)
+ scan++;
+ }
+ while (re_split(scan, (int)(end - scan), fs, &reregs) != -1 &&
+ NF < up_to) {
+ (*set)(++NF, scan, reregs.start[0], n);
+ scan += reregs.end[0];
+ }
+ if (NF != up_to && scan <= end) {
+ if (!(rs == 0 && scan == end)) {
+ (*set)(++NF, scan, (int)(end - scan), n);
+ scan = end;
+ }
+ }
+ *buf = scan;
+ return (NF);
+ }
+ for (scan = s; scan < end && NF < up_to; scan++) {
+ /*
+ * special case: fs is single space, strip leading
+ * whitespace
+ */
+ if (*fs == ' ') {
+ while ((*scan == ' ' || *scan == '\t') && scan < end)
+ scan++;
+ if (scan >= end)
+ break;
+ }
+ field = scan;
+ if (*fs == ' ')
+ while (*scan != ' ' && *scan != '\t' && scan < end)
+ scan++;
+ else {
+ while (*scan != *fs && scan < end)
+ scan++;
+ if (rs && scan == end-1 && *scan == *fs) {
+ (*set)(++NF, field, (int)(scan - field), n);
+ field = scan;
+ }
+ }
+ (*set)(++NF, field, (int)(scan - field), n);
+ if (scan == end)
+ break;
+ }
+ *buf = scan;
+ return NF;
+}
+
+static int
+re_split(buf, len, fs, reregsp)
+char *buf, *fs;
+int len;
+struct re_registers *reregsp;
+{
+ typedef struct re_pattern_buffer RPAT;
+ static RPAT *rp;
+ static char *last_fs = NULL;
+
+ if ((last_fs != NULL && !STREQ(fs, last_fs))
+ || (rp && ! strict && ((IGNORECASE_node->var_value->numbr != 0)
+ ^ (rp->translate != NULL))))
+ {
+ /* fs has changed or IGNORECASE has changed */
+ free(rp->buffer);
+ free(rp->fastmap);
+ free((char *) rp);
+ free(last_fs);
+ last_fs = NULL;
+ }
+ if (last_fs == NULL) { /* first time */
+ emalloc(rp, RPAT *, sizeof(RPAT), "re_split");
+ memset((char *) rp, 0, sizeof(RPAT));
+ emalloc(rp->buffer, char *, 8, "re_split");
+ rp->allocated = 8;
+ emalloc(rp->fastmap, char *, 256, "re_split");
+ emalloc(last_fs, char *, strlen(fs) + 1, "re_split");
+ (void) strcpy(last_fs, fs);
+ if (! strict && IGNORECASE_node->var_value->numbr != 0.0)
+ rp->translate = casetable;
+ else
+ rp->translate = NULL;
+ if (re_compile_pattern(fs, strlen(fs), rp) != NULL)
+ fatal("illegal regular expression for FS: `%s'", fs);
+ }
+ return re_search(rp, buf, len, 0, len, reregsp);
+}
+
+NODE *
+do_split(tree)
+NODE *tree;
+{
+ NODE *t1, *t2, *t3;
+ register char *splitc;
+ char *s;
+ NODE *n;
+
+ if (a_get_three(tree, &t1, &t2, &t3) < 3)
+ splitc = get_fs();
+ else
+ splitc = force_string(t3)->stptr;
+
+ n = t2;
+ if (t2->type == Node_param_list)
+ n = stack_ptr[t2->param_cnt];
+ if (n->type != Node_var && n->type != Node_var_array)
+ fatal("second argument of split is not a variable");
+ assoc_clear(n);
+
+ tree = force_string(t1);
+
+ s = tree->stptr;
+ return tmp_number((AWKNUM)
+ parse_fields(HUGE, &s, tree->stlen, splitc, set_element, n));
+}
+
+static char *
+get_fs()
+{
+ register NODE *tmp;
+ static char buf[10];
+
+ tmp = force_string(FS_node->var_value);
+ if (get_rs() == 0) {
+ if (tmp->stlen == 1) {
+ if (tmp->stptr[0] == ' ')
+ (void) strcpy(buf, "[ \n]+");
+ else
+ sprintf(buf, "[%c\n]", tmp->stptr[0]);
+ } else if (tmp->stlen == 0) {
+ buf[0] = '\n';
+ buf[1] = '\0';
+ } else
+ return tmp->stptr;
+ return buf;
+ }
+ return tmp->stptr;
+}
+
+static void
+set_element(num, s, len, n)
+int num;
+char *s;
+int len;
+NODE *n;
+{
+ *assoc_lookup(n, tmp_number((AWKNUM) (num))) = make_string(s, len);
+}
diff --git a/gawk-info b/gawk-info
deleted file mode 100644
index 361bd0c5..00000000
--- a/gawk-info
+++ /dev/null
@@ -1,6151 +0,0 @@
-Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
-file gawk.texinfo.
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them.
-
-Copyright (C) 1989 Free Software Foundation, Inc.
-
-Permission is granted to make and distribute verbatim copies of this
-manual provided the copyright notice and this permission notice are
-preserved on all copies.
-
-Permission is granted to copy and distribute modified versions of
-this manual under the conditions for verbatim copying, provided that
-the entire resulting derived work is distributed under the terms of a
-permission notice identical to this one.
-
-Permission is granted to copy and distribute translations of this
-manual into another language, under the above conditions for modified
-versions, except that this permission notice may be stated in a
-translation approved by the Foundation.
-
-
-
-File: gawk-info, Node: Top, Next: Preface, Prev: (dir), Up: (dir)
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them; it
-contains the following chapters:
-
-* Menu:
-
-* Preface:: What you can do with `awk'; brief history
- and acknowledgements.
-
-* License:: Your right to copy and distribute `gawk'.
-
-* This Manual:: Using this manual.
-
- Includes sample input files that you can use.
-
-* Getting Started:: A basic introduction to using `awk'.
- How to run an `awk' program. Command line syntax.
-
-* Reading Files:: How to read files and manipulate fields.
-
-* Printing:: How to print using `awk'. Describes the
- `print' and `printf' statements.
- Also describes redirection of output.
-
-* One-liners:: Short, sample `awk' programs.
-
-* Patterns:: The various types of patterns explained in detail.
-
-* Actions:: The various types of actions are introduced here.
- Describes expressions and the various operators in
- detail. Also describes comparison expressions.
-
-* Statements:: The various control statements are described in
- detail.
-
-* Arrays:: The description and use of arrays. Also includes
- array--oriented control statements.
-
-* User-defined:: User--defined functions are described in detail.
-
-* Built-in:: The built--in functions are summarized here.
-
-* Special:: The special variables are summarized here.
-
-* Sample Program:: A sample `awk' program with a complete explanation.
-
-* Notes:: Something about the implementation of `gawk'.
-
-* Glossary:: An explanation of some unfamiliar terms.
-
-* Index::
-
-
-
-File: gawk-info, Node: Preface, Next: License, Prev: Top, Up: Top
-
-Preface
-*******
-
-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 may be easier with `awk'.
-
-The `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 `awk' is called `gawk'; it is fully upward
-compatible with the System V Release 3.1 and later version of `awk'.
-All properly written `awk' programs should work with `gawk'. So we
-usually don't distinguish between `gawk' and other `awk'
-implementations in this manual.
-
-This manual teaches you what `awk' does and how you can use `awk'
-effectively. You should already be familiar with basic,
-general--purpose, operating system commands such as `ls'. Using
-`awk' you can:
-
- * manage small, personal databases,
-
- * generate reports,
-
- * validate data,
-
- * produce indexes, and perform other document preparation tasks,
-
- * even experiment with algorithms that can be adapted later to
- other computer languages!
-
-* Menu:
-
-* History:: The history of gawk and awk. Acknowledgements.
-
-
-
-File: gawk-info, Node: History, Up: Preface
-
-History of `awk' and `gawk'
-===========================
-
-The name `awk' comes from the initials of its designers: Alfred V.
-Aho, Peter J. Weinberger, and Brian W. Kernighan. The original
-version of `awk' was written in 1977. In 1985 a new version made the
-programming language more powerful, introducing user--defined
-functions, multiple input streams, and computed regular expressions.
-
-The GNU implementation, `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 `gawk' for compatibility with the
-newer `awk'.
-
-Many people need to be thanked for their assistance in producing this
-manual. Jay Fenlason contributed many ideas and sample programs.
-Richard Mlynarik and Robert Chassell gave helpful comments on drafts
-of this manual. The paper ``A Supplemental Document for `awk''' by
-John W. Pierce of the Chemistry Department at UC San Diego,
-pinpointed several issues relevant both to `awk' implementation and
-to this manual, that would otherwise have escaped us.
-
-Finally, we would like to thank Brian Kernighan of Bell Labs for
-invaluable assistance during the testing and debugging of `gawk', and
-for help in clarifying several points about the language.
-
-
-
-File: gawk-info, Node: License, Next: This Manual, Prev: Preface, Up: Top
-
-GNU GENERAL PUBLIC LICENSE
-**************************
-
- Version 1, February 1989
-
- Copyright (C) 1989 Free Software Foundation, Inc.
- 675 Mass Ave, Cambridge, MA 02139, USA
-
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-=========
-
- The license agreements of most software companies try to keep users
-at the mercy of those companies. By contrast, our General Public
-License is intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-The General Public License applies to the Free Software Foundation's
-software and to any other program whose authors commit to using it.
-You can use it for your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Specifically, the General Public License is designed to make
-sure that you have the freedom to give away or sell copies of free
-software, that you receive source code or can get it if you want it,
-that you can change the software or use pieces of it in new free
-programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if
-you distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of a such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must tell them their rights.
-
- We protect your rights with two steps: (1) copyright the software,
-and (2) offer you this license which gives you legal permission to
-copy, distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on,
-we want its recipients to know that what they have is not the
-original, so that any problems introduced by others will not reflect
-on the original authors' reputations.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 1. This License Agreement applies to any program or other work
- which contains a notice placed by the copyright holder saying it
- may be distributed under the terms of this General Public
- License. The ``Program'', below, refers to any such program or
- work, and a ``work based on the Program'' means either the
- Program or any work containing the Program or a portion of it,
- either verbatim or with modifications. Each licensee is
- addressed as ``you''.
-
- 2. You may copy and distribute verbatim copies of the Program's
- source code as you receive it, in any medium, provided that you
- conspicuously and appropriately publish on each copy an
- appropriate copyright notice and disclaimer of warranty; keep
- intact all the notices that refer to this General Public License
- and to the absence of any warranty; and give any other
- recipients of the Program a copy of this General Public License
- along with the Program. You may charge a fee for the physical
- act of transferring a copy.
-
- 3. You may modify your copy or copies of the Program or any portion
- of it, and copy and distribute such modifications under the
- terms of Paragraph 1 above, provided that you also do the
- following:
-
- * cause the modified files to carry prominent notices stating
- that you changed the files and the date of any change; and
-
- * cause the whole of any work that you distribute or publish,
- that in whole or in part contains the Program or any part
- thereof, either with or without modifications, to be
- licensed at no charge to all third parties under the terms
- of this General Public License (except that you may choose
- to grant warranty protection to some or all third parties,
- at your option).
-
- * If the modified program normally reads commands
- interactively when run, you must cause it, when started
- running for such interactive use in the simplest and most
- usual way, to print or display an announcement including an
- appropriate copyright notice and a notice that there is no
- warranty (or else, saying that you provide a warranty) and
- that users may redistribute the program under these
- conditions, and telling the user how to view a copy of this
- General Public License.
-
- * You may charge a fee for the physical act of transferring a
- copy, and you may at your option offer warranty protection
- in exchange for a fee.
-
- Mere aggregation of another independent work with the Program
- (or its derivative) on a volume of a storage or distribution
- medium does not bring the other work under the scope of these
- terms.
-
- 4. You may copy and distribute the Program (or a portion or
- derivative of it, under Paragraph 2) in object code or
- executable form under the terms of Paragraphs 1 and 2 above
- provided that you also do one of the following:
-
- * accompany it with the complete corresponding
- machine-readable source code, which must be distributed
- under the terms of Paragraphs 1 and 2 above; or,
-
- * accompany it with a written offer, valid for at least three
- years, to give any third party free (except for a nominal
- charge for the cost of distribution) a complete
- machine-readable copy of the corresponding source code, to
- be distributed under the terms of Paragraphs 1 and 2 above;
- or,
-
- * accompany it with the information you received as to where
- the corresponding source code may be obtained. (This
- alternative is allowed only for noncommercial distribution
- and only if you received the program in object code or
- executable form alone.)
-
- Source code for a work means the preferred form of the work for
- making modifications to it. For an executable file, complete
- source code means all the source code for all modules it
- contains; but, as a special exception, it need not include
- source code for modules which are standard libraries that
- accompany the operating system on which the executable file
- runs, or for standard header files or definitions files that
- accompany that operating system.
-
- 5. You may not copy, modify, sublicense, distribute or transfer the
- Program except as expressly provided under this General Public
- License. Any attempt otherwise to copy, modify, sublicense,
- distribute or transfer the Program is void, and will
- automatically terminate your rights to use the Program under
- this License. However, parties who have received copies, or
- rights to use copies, from you under this General Public License
- will not have their licenses terminated so long as such parties
- remain in full compliance.
-
- 6. By copying, distributing or modifying the Program (or any work
- based on the Program) you indicate your acceptance of this
- license to do so, and all its terms and conditions.
-
- 7. Each time you redistribute the Program (or any work based on the
- Program), the recipient automatically receives a license from
- the original licensor to copy, distribute or modify the Program
- subject to these terms and conditions. You may not impose any
- further restrictions on the recipients' exercise of the rights
- granted herein.
-
- 8. The Free Software Foundation may publish revised and/or new
- versions of the General Public License from time to time. Such
- new versions will be similar in spirit to the present version,
- but may differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
- Program specifies a version number of the license which applies
- to it and ``any later version'', you have the option of
- following the terms and conditions either of that version or of
- any later version published by the Free Software Foundation. If
- the Program does not specify a version number of the license,
- you may choose any version ever published by the Free Software
- Foundation.
-
- 9. If you wish to incorporate parts of the Program into other free
- programs whose distribution conditions are different, write to
- the author to ask for permission. For software which is
- copyrighted by the Free Software Foundation, write to the Free
- Software Foundation; we sometimes make exceptions for this. Our
- decision will be guided by the two goals of preserving the free
- status of all derivatives of our free software and of promoting
- the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 10. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
- WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
- LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
- HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS''
- WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
- ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS
- WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE
- COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 11. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
- WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
- MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
- LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
- INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
- INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS
- OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
- YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH
- ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
- ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
-Appendix: How to Apply These Terms to Your 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
-free software which everyone can redistribute and change under these
-terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the ``copyright'' line and a pointer to where the full notice is found.
-
- ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
- Copyright (C) 19YY NAME OF AUTHOR
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 1, or (at your option)
- any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
- Also add information on how to contact you by electronic and paper
-mail.
-
-If the program is interactive, make it output a short notice like
-this when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
- The hypothetical commands `show w' and `show c' should show the
-appropriate parts of the General Public License. Of course, the
-commands you use may be called something other than `show w' and
-`show c'; they could even be mouse-clicks or menu items--whatever
-suits your program.
-
-You should also get your employer (if you work as a programmer) or
-your school, if any, to sign a ``copyright disclaimer'' for the
-program, if necessary. Here a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- program `Gnomovision' (a program to direct compilers to make passes
- at assemblers) written by James Hacker.
-
- SIGNATURE OF TY COON, 1 April 1989
- Ty Coon, President of Vice
-
-That's all there is to it!
-
-
-
-File: gawk-info, Node: This Manual, Next: Getting Started, Prev: License, Up: Top
-
-Using This Manual
-*****************
-
-The term `gawk' refers to a program (a version of `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
-`awk' utility'' and the language ``the `awk' language''. The purpose
-of this manual is to explain the `awk' language and how to run the
-`awk' utility.
-
-The term "`awk' program" refers to a program written by you in the
-`awk' programming language.
-
-*Note Getting Started::, for the bare essentials you need to know to
-start using `awk'.
-
-Useful ``one--liners'' are included to give you a feel for the `awk'
-language (*note One-liners::.).
-
-A sizable sample `awk' program has been provided for you (*note
-Sample Program::.).
-
-If you find terms that you aren't familiar with, try looking them up
-in the glossary (*note Glossary::.).
-
-Most of the time complete `awk' programs are used as examples, but in
-some of the more advanced sections, only the part of the `awk'
-program that illustrates the concept being described is shown.
-
-* Menu:
-
-This chapter contains the following sections:
-
-* The Files:: Sample data files for use in the `awk' programs
- illustrated in this manual.
-
-
-
-File: gawk-info, Node: The Files, Up: This Manual
-
-Input Files for the Examples
-============================
-
-This manual contains many sample programs. The data for many of
-those programs comes from two files. The first file, called
-`BBS-list', represents a list of computer bulletin board systems and
-information about those systems.
-
-Each line of this file is one "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 `A'
-in the last column means the board operates 24 hours all week. A `B'
-in the last column means the board operates evening and weekend
-hours, only. A `C' means the board operates only on weekends.
-
- aardvark 555-5553 1200/300 B
- alpo-net 555-3412 2400/1200/300 A
- barfly 555-7685 1200/300 A
- bites 555-1675 2400/1200/300 A
- camelot 555-0542 300 C
- core 555-2912 1200/300 C
- fooey 555-1234 2400/1200/300 B
- foot 555-6699 1200/300 B
- macfoo 555-6480 1200/300 A
- sdace 555-3430 2400/1200/300 A
- sabafoo 555-2127 1200/300 C
-
-The second data file, called `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.
-
- Jan 13 25 15 115
- Feb 15 32 24 226
- Mar 15 24 34 228
- Apr 31 52 63 420
- May 16 34 29 208
- Jun 31 42 75 492
- Jul 24 34 67 436
- Aug 15 34 47 316
- Sep 13 55 37 277
- Oct 29 54 68 525
- Nov 20 87 82 577
- Dec 17 35 61 401
-
- Jan 21 36 64 620
- Feb 26 58 80 652
- Mar 24 75 70 495
- Apr 21 70 74 514
-
-If you are reading this in GNU Emacs using Info, you can copy the
-regions of text showing these sample files into your own test files.
-This way you can try out the examples shown in the remainder of this
-document. You do this by using the command `M-x write-region' to
-copy text from the Info file into a file for use with `awk' (see your
-``GNU Emacs Manual'' for more information). Using this information,
-create your own `BBS-list' and `inventory-shipped' files, and
-practice what you learn in this manual.
-
-
-
-File: gawk-info, Node: Getting Started, Next: Reading Files, Prev: This Manual, Up: Top
-
-Getting Started With `awk'
-**************************
-
-The basic function of `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, `awk' performs specified actions on
-that line. Then `awk' keeps processing input lines until the end of
-the file is reached.
-
-An `awk' "program" or "script" consists of a series of "rules".
-(They may also contain "function definitions", but that is an
-advanced feature, so let's ignore it for now. *Note User-defined::.)
-
-A rule contains a "pattern", an "action", or both. Actions are
-enclosed in curly braces to distinguish them from patterns.
-Therefore, an `awk' program is a sequence of rules in the form:
-
- PATTERN { ACTION }
- PATTERN { ACTION }
- ...
-
- * Menu:
-
-* Very Simple:: A very simple example.
-* 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.
-* Statements/Lines:: Subdividing or combining statements into lines.
-
-* When:: When to use gawk and when to use other things.
-
-
-
-File: gawk-info, Node: Very Simple, Next: Two Rules, Up: Getting Started
-
-A Very Simple Example
-=====================
-
-The following command runs a simple `awk' program that searches the
-input file `BBS-list' for the string of characters: `foo'. (A string
-of characters is usually called, quite simply, a "string".)
-
- awk '/foo/ { print $0 }' BBS-list
-
-When lines containing `foo' are found, they are printed, because
-`print $0' means print the current line. (Just `print' by itself
-also means the same thing, so we could have written that instead.)
-
-You will notice that slashes, `/', surround the string `foo' in the
-actual `awk' program. The slashes indicate that `foo' is a pattern
-to search for. This type of pattern is called a "regular
-expression", and is covered in more detail later (*note Regexp::.).
-There are single quotes around the `awk' program so that the shell
-won't interpret any of it as special shell characters.
-
-Here is what this program prints:
-
- fooey 555-1234 2400/1200/300 B
- foot 555-6699 1200/300 B
- macfoo 555-6480 1200/300 A
- sabafoo 555-2127 1200/300 C
-
-In an `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 *every*
-input line.
-
-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 `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.)
-
-
-
-File: gawk-info, Node: Two Rules, Next: More Complex, Prev: Very Simple, Up: Getting Started
-
-An Example with Two Rules
-=========================
-
-The `awk' utility reads the input files one line at a time. For each
-line, `awk' tries the patterns of all the rules. If several patterns
-match then several actions are run, in the order in which they appear
-in the `awk' program. If no patterns match, then no actions are run.
-
-After processing all the rules (perhaps none) that match the line,
-`awk' reads the next line (however, *note Next::.). This continues
-until the end of the file is reached.
-
-For example, the `awk' program:
-
- /12/ { print $0 }
- /21/ { print $0 }
-
-contains two rules. The first rule has the string `12' as the
-pattern and `print $0' as the action. The second rule has the string
-`21' as the pattern and also has `print $0' as the action. Each
-rule's action is enclosed in its own pair of braces.
-
-This `awk' program prints every line that contains the string `12'
-*or* the string `21'. If a line contains both strings, it is printed
-twice, once by each rule.
-
-If we run this program on our two sample data files, `BBS-list' and
-`inventory-shipped', as shown here:
-
- awk '/12/ { print $0 }
- /21/ { print $0 }' BBS-list inventory-shipped
-
-we get the following output:
-
- aardvark 555-5553 1200/300 B
- alpo-net 555-3412 2400/1200/300 A
- barfly 555-7685 1200/300 A
- bites 555-1675 2400/1200/300 A
- core 555-2912 1200/300 C
- fooey 555-1234 2400/1200/300 B
- foot 555-6699 1200/300 B
- macfoo 555-6480 1200/300 A
- sdace 555-3430 2400/1200/300 A
- sabafoo 555-2127 1200/300 C
- sabafoo 555-2127 1200/300 C
- Jan 21 36 64 620
- Apr 21 70 74 514
-
-Note how the line in `BBS-list' beginning with `sabafoo' was printed
-twice, once for each rule.
-
-
-
-File: gawk-info, Node: More Complex, Next: Running gawk, Prev: Two Rules, Up: Getting Started
-
-A More Complex Example
-======================
-
-Here is an example to give you an idea of what typical `awk' programs
-do. This example shows how `awk' can be used to summarize, select,
-and rearrange the output of another utility. It uses features that
-haven't been covered yet, so don't worry if you don't understand all
-the details.
-
- ls -l | awk '$5 == "Nov" { sum += $4 }
- END { print sum }'
-
-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.)
-
-The `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:
-
- -rw-r--r-- 1 close 1933 Nov 7 13:05 Makefile
- -rw-r--r-- 1 close 10809 Nov 7 13:03 gawk.h
- -rw-r--r-- 1 close 983 Apr 13 12:14 gawk.tab.h
- -rw-r--r-- 1 close 31869 Jun 15 12:20 gawk.y
- -rw-r--r-- 1 close 22414 Nov 7 13:03 gawk1.c
- -rw-r--r-- 1 close 37455 Nov 7 13:03 gawk2.c
- -rw-r--r-- 1 close 27511 Dec 9 13:07 gawk3.c
- -rw-r--r-- 1 close 7989 Nov 7 13:03 gawk4.c
-
-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 `$5 == "Nov"' in our `awk' program is an expression that tests
-whether the fifth field of the output from `ls -l' matches the string
-`Nov'. Each time a line has the string `Nov' in its fifth field, the
-action `{ sum += $4 }' is performed. This adds the fourth field (the
-file size) to the variable `sum'. As a result, when `awk' has
-finished reading all the input lines, `sum' will be the sum of the
-sizes of files whose lines matched the pattern.
-
-After the last line of output from `ls' has been processed, the `END'
-pattern is executed, and the value of `sum' is printed. In this
-example, the value of `sum' would be 80600.
-
-These more advanced `awk' techniques are covered in later sections
-(*note Actions::.). Before you can move on to more advanced `awk'
-programming, you have to know how `awk' interprets your input and
-displays your output. By manipulating "fields" and using special
-"print" statements, you can produce some very useful and spectacular
-looking reports.
-
-
-
-File: gawk-info, Node: Running gawk, Next: Comments, Prev: More Complex, Up: Getting Started
-
-How to Run `awk' Programs
-=========================
-
-There are several ways to run an `awk' program. If the program is
-short, it is easiest to include it in the command that runs `awk',
-like this:
-
- awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
-
- where 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:
-
- awk -f PROGRAM-FILE INPUT-FILE1 INPUT-FILE2 ...
-
- * Menu:
-
-* One-shot:: Running a short throw--away `awk' program.
-* Read Terminal:: Using no input files (input from terminal instead).
-* Long:: Putting permanent `awk' programs in files.
-* Executable Scripts:: Making self--contained `awk' programs.
-* Command Line:: How the `awk' command line is laid out.
-
-
-
-File: gawk-info, Node: One-shot, Next: Read Terminal, Up: Running gawk
-
-One--shot Throw--away `awk' Programs
-------------------------------------
-
-Once you are familiar with `awk', you will often type simple programs
-at the moment you want to use them. Then you can write the program
-as the first argument of the `awk' command, like this:
-
- awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
-
- where PROGRAM consists of a series of PATTERNS and ACTIONS, as
-described earlier.
-
-This command format tells the shell to start `awk' and use the
-PROGRAM to process records in the input file(s). There are single
-quotes around the PROGRAM so that the shell doesn't interpret any
-`awk' characters as special shell characters. They cause the shell
-to treat all of PROGRAM as a single argument for `awk'. They also
-allow PROGRAM to be more than one line long.
-
-This format is also useful for running short or medium--sized `awk'
-programs from shell scripts, because it avoids the need for a
-separate file for the `awk' program. A self--contained shell script
-is more reliable since there are no other files to misplace.
-
-
-
-File: gawk-info, Node: Read Terminal, Next: Long, Prev: One-shot, Up: Running gawk
-
-Running `awk' without Input Files
----------------------------------
-
-You can also use `awk' without any input files. If you type the
-command line:
-
- awk 'PROGRAM'
-
-then `awk' applies the PROGRAM to the "standard input", which usually
-means whatever you type on the terminal. This continues until you
-indicate end--of--file by typing `Control-d'.
-
-For example, if you type:
-
- awk '/th/'
-
-whatever you type next will be taken as data for that `awk' program.
-If you go on to type the following data,
-
- Kathy
- Ben
- Tom
- Beth
- Seth
- Karen
- Thomas
- `Control-d'
-
-then `awk' will print
-
- Kathy
- Beth
- Seth
-
-as matching the pattern `th'. Notice that it did not recognize
-`Thomas' as matching the pattern. The `awk' language is "case
-sensitive", and matches patterns *exactly*.
-
-
-
-File: gawk-info, Node: Long, Next: Executable Scripts, Prev: Read Terminal, Up: Running gawk
-
-Running Long Programs
----------------------
-
-Sometimes your `awk' programs can be very long. In this case it is
-more convenient to put the program into a separate file. To tell
-`awk' to use that file for its program, you type:
-
- awk -f SOURCE-FILE INPUT-FILE1 INPUT-FILE2 ...
-
- The `-f' tells the `awk' utility to get the `awk' program from the
-file SOURCE-FILE. Any file name can be used for SOURCE-FILE. For
-example, you could put the program:
-
- /th/
-
-into the file `th-prog'. Then the command:
-
- awk -f th-prog
-
-does the same thing as this one:
-
- awk '/th/'
-
-which was explained earlier (*note Read Terminal::.). Note that you
-don't usually need single quotes around the file name that you
-specify with `-f', because most file names don't contain any of the
-shell's special characters.
-
-If you want to identify your `awk' program files clearly as such, you
-can add the extension `.awk' to the filename. This doesn't affect
-the execution of the `awk' program, but it does make ``housekeeping''
-easier.
-
-
-
-File: gawk-info, Node: Executable Scripts, Next: Command Line, Prev: Long, Up: Running gawk
-
-Executable `awk' Programs
--------------------------
-
-(The following section assumes that you are already somewhat familiar
-with `awk'.)
-
-Once you have learned `awk', you may want to write self--contained
-`awk' scripts, using the `#!' script mechanism. You can do this on
-BSD Unix systems and GNU.
-
-For example, you could create a text file named `hello', containing
-the following (where `BEGIN' is a feature we have not yet discussed):
-
- #! /bin/awk -f
-
- # a sample awk program
-
- BEGIN { print "hello, world" }
-
-After making this file executable (with the `chmod' command), you can
-simply type:
-
- hello
-
-at the shell, and the system will arrange to run `awk' as if you had
-typed:
-
- awk -f hello
-
-Self--contained `awk' scripts are particularly useful for putting
-`awk' programs into production on your system, without your users
-having to know that they are actually using an `awk' program.
-
-If your system does not support the `#!' mechanism, you can get a
-similar effect using a regular shell script. It would look something
-like this:
-
- : a sample awk program
-
- awk 'PROGRAM' "$@"
-
-Using this technique, it is *vital* to enclose the PROGRAM in single
-quotes to protect it from interpretation by the shell. If you omit
-the quotes, only a shell wizard can predict the result.
-
-The `"$@"' causes the shell to forward all the command line arguments
-to the `awk' program, without interpretation.
-
-
-
-File: gawk-info, Node: Command Line, Prev: Executable Scripts, Up: Running gawk
-
-Details of the `awk' Command Line
----------------------------------
-
-(The following section assumes that you are already familiar with
-`awk'.)
-
-There are two ways to run `awk'. Here are templates for both of
-them; items enclosed in `[' and `]' in these templates are optional.
-
- awk [ -FFS ] [ -- ] 'PROGRAM' FILE ...
- awk [ -FFS ] -f SOURCE-FILE [ -f SOURCE-FILE ... ] [ -- ] FILE ...
-
- Options begin with a minus sign, and consist of a single character.
-The options and their meanings are as follows:
-
-`-FFS'
- This sets the `FS' variable to FS (*note Special::.). As a
- special case, if FS is `t', then `FS' will be set to the tab
- character (`"\t"').
-
-`-f SOURCE-FILE'
- Indicates that the `awk' program is to be found in SOURCE-FILE
- instead of in the first non--option argument.
-
-`--'
- This signals the end of the command line options. If you wish
- to specify an input file named `-f', you can precede it with the
- `--' argument to prevent the `-f' from being interpreted as an
- option. This handling of `--' follows the POSIX argument
- parsing conventions.
-
-Any other options will be flagged as invalid with a warning message,
-but are otherwise ignored.
-
-If the `-f' option is *not* used, then the first non--option command
-line argument is expected to be the program text.
-
-The `-f' option may be used more than once on the command line.
-`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 `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 `/dev/tty' as one of the arguments to a
-`-f'. Type your program, and end it with the keyboard end--of--file
-character `Control-d'.
-
-Any additional arguments on the command line are made available to
-your `awk' program in the `ARGV' array (*note Special::.). These
-arguments are normally treated as input files to be processed in the
-order specified. However, an argument that has the form VAR`='VALUE,
-means to assign the value VALUE to the variable VAR--it does not
-specify a file at all.
-
-Command line options and the program text (if present) are omitted
-from the `ARGV' array. All other arguments, including variable
-assignments, are included (*note Special::.).
-
-The distinction between file name arguments and variable--assignment
-arguments is made when `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, *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 *not* available
-inside a `BEGIN' rule (*note BEGIN/END::.), since such rules are run
-before `awk' begins scanning the argument list.
-
-The variable assignment feature is most useful for assigning to
-variables such as `RS', `OFS', and `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:
-
- awk 'pass == 1 { PASS 1 STUFF }
- pass == 2 { PASS 2 STUFF }' pass=1 datafile pass=2 datafile
-
-
-
-File: gawk-info, Node: Comments, Next: Statements/Lines, Prev: Running gawk, Up: Getting Started
-
-Comments in `awk' Programs
-==========================
-
-When you write a complicated `awk' program, you can put "comments" in
-the program file to help you remember what the program does, and how
-it works.
-
-A comment starts with the the sharp sign character, `#', and
-continues to the end of the line. The `awk' language ignores the
-rest of a line following a sharp sign. For example, we could have
-put the following into `th-prog':
-
- # This program finds records containing the pattern `th'. This is how
- # you continue comments on additional lines.
- /th/
-
-You can put comment lines into keyboard--composed throw--away `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 another time.
-
-
-
-File: gawk-info, Node: Statements/Lines, Next: When, Prev: Comments, Up: Getting Started
-
-`awk' Statements versus Lines
-=============================
-
-Most often, each line in an `awk' program is a separate statement or
-separate rule, like this:
-
- awk '/12/ { print $0 }
- /21/ { print $0 }' BBS-list inventory-shipped
-
-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:
-
- , { ? : || &&
-
-Lines ending in `do' or `else' automatically have their statements
-continued on the following line(s). A newline at any other point
-ends the statement.
-
-If you would like to split a single statement into two lines at a
-point where a newline would terminate it, you can "continue" it by
-ending the first line with a backslash character, `\'. This is
-allowed absolutely anywhere in the statement, even in the middle of a
-string or regular expression. For example:
-
- awk '/This program is too long, so continue it\
- on the next line/ { print $1 }'
-
-We have generally not used backslash continuation in the sample
-programs in this manual. Since there is no limit on the length of a
-line, it is never strictly necessary; it just makes programs
-prettier. We have preferred to make them even more pretty by keeping
-the statements short. Backslash continuation is most useful when
-your `awk' program is in a separate source file, instead of typed in
-on the command line.
-
-*Warning: this does not work if you are using the C shell.*
-Continuation with backslash works for `awk' programs in files, and
-also for one--shot programs *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.
-
-When `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, `;'. This also applies to the rules
-themselves. Thus, the above example program could have been written:
-
- /12/ { print $0 } ; /21/ { print $0 }
-
-*Note:* It is a new requirement that rules on the same line require
-semicolons as a separator in the `awk' language; it was done for
-consistency with the statements in the action part of rules.
-
-
-
-File: gawk-info, Node: When, Prev: Statements/Lines, Up: Getting Started
-
-When to Use `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 `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 `ls'. (*Note A More Complex Example: More Complex.)
-
-Programs written with `awk' are usually much smaller than they would
-be in other languages. This makes `awk' programs easy to compose and
-use. Often `awk' programs can be quickly composed at your terminal,
-used once, and thrown away. Since `awk' programs are interpreted,
-you can avoid the usually lengthy edit--compile--test--debug cycle of
-software development.
-
-Complex programs have been written in `awk', including a complete
-retargetable assembler for 8--bit microprocessors (*note Glossary::.
-for more information) and a microcode assembler for a special purpose
-Prolog computer. However, `awk''s capabilities are strained by tasks
-of such complexity.
-
-If you find yourself writing `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 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 `awk' programs,
-but they will be easier to maintain and usually run more efficiently.
-
-
-
-File: gawk-info, Node: Reading Files, Next: Printing, Prev: Getting Started, Up: Top
-
-Reading Files (Input)
-*********************
-
-In the typical `awk' program, all input is read either from the
-standard input (usually the keyboard) or from files whose names you
-specify on the `awk' command line. If you specify input files, `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 `FILENAME'
-(*note Special::.).
-
-The input is split automatically into "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 "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 `getline' command, which
-can do explicit input from any number of files.
-
-* 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 `getline' function.
-* Close Input:: Closing an input file (so you can read from
- the beginning once more).
-
-
-
-File: gawk-info, Node: Records, Next: Fields, Up: Reading Files
-
-How Input is Split into Records
-===============================
-
-The `awk' language divides its input into records and fields.
-Records are separated from each other by the "record separator". By
-default, the record separator is the "newline" character. Therefore,
-normally, a record is a line of text.
-
-Sometimes you may want to use a different character to separate your
-records. You can use different characters by changing the special
-variable `RS'.
-
-The value of `RS' is a string that says how to separate records; the
-default value is `"\n"', the string of just a newline character.
-This is why lines of text are the default record. Although `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. `RS' is exceptional in this regard; `awk' uses the full
-value of all its other special variables.
-
-The value of `RS' is changed by "assigning" it a new value (*note
-Assignment Ops::.). One way to do this is at the beginning of your
-`awk' program, before any input has been processed, using the special
-`BEGIN' pattern (*note BEGIN/END::.). This way, `RS' is changed to
-its new value before any input is read. The new value of `RS' is
-enclosed in quotation marks. For example:
-
- awk 'BEGIN { RS = "/" } ; { print $0 }' BBS-list
-
-changes the value of `RS' to `/', the slash character, before reading
-any input. Records are now separated by a slash. The second rule in
-the `awk' program (the action with no pattern) will proceed to print
-each record. Since each `print' statement adds a newline at the end
-of its output, the effect of this `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 (*note Command Line::.).
-
- awk '...' RS="/" SOURCE-FILE
-
-`RS' will be set to `/' before processing SOURCE-FILE.
-
-The empty string (a string of no characters) has a special meaning as
-the value of `RS': it means that records are separated only by blank
-lines. *Note Multiple::, for more details.
-
-The `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 `FNR'. It is reset to zero when a new file
-is started. Another variable, `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 `RS' in the middle of an `awk' run, the
-new value is used to delimit subsequent records, but the record
-currently being processed (and records already finished) are not
-affected.
-
-
-
-File: gawk-info, Node: Fields, Next: Non-Constant Fields, Prev: Records, Up: Reading Files
-
-Examining Fields
-================
-
-When `awk' reads an input record, the record is automatically
-separated or "parsed" by the interpreter into pieces called "fields".
-By default, fields are separated by whitespace, like words in a line.
-Whitespace in `awk' means any string of one or more spaces and/or
-tabs; other characters such as newline, formfeed, and so on, that are
-considered whitespace by other languages are *not* considered
-whitespace by `awk'.
-
-The purpose of fields is to make it more convenient for you to refer
-to these pieces of the record. You don't have to use them--you can
-operate on the whole record if you wish--but fields are what make
-simple `awk' programs so powerful.
-
-To refer to a field in an `awk' program, you use a dollar--sign, `$',
-followed by the number of the field you want. Thus, `$1' refers to
-the first field, `$2' to the second, and so on. For example, suppose
-the following is a line of input:
-
- This seems like a pretty nice example.
-
- Here the first field, or `$1', is `This'; the second field, or `$2',
-is `seems'; and so on. Note that the last field, `$7', is
-`example.'. Because there is no space between the `e' and the `.',
-the period is considered part of the seventh field.
-
-No matter how many fields there are, the last field in a record can
-be represented by `$NF'. So, in the example above, `$NF' would be
-the same as `$7', which is `example.'. Why this works is explained
-below (*note Non-Constant Fields::.). If you try to refer to a field
-beyond the last one, such as `$8' when the record has only 7 fields,
-you get the empty string.
-
-Plain `NF', with no `$', is a special variable whose value is the
-number of fields in the current record.
-
-`$0', which looks like an attempt to refer to the zeroth field, is a
-special case: it represents the whole input record. This is what you
-would use when you aren't interested in fields.
-
-Here are some more examples:
-
- awk '$1 ~ /foo/ { print $0 }' BBS-list
-
-This example contains the "matching" operator `~' (*note Comparison
-Ops::.). Using this operator, all records in the file `BBS-list'
-whose first field contains the string `foo' are printed.
-
-By contrast, the following example:
-
- awk '/foo/ { print $1, $NF }' BBS-list
-
-looks for the string `foo' in *the entire record* and prints the
-first field and the last field for each input record containing the
-pattern.
-
-The following program will search the system password file, and print
-the entries for users who have no password.
-
- awk -F: '$2 == ""' /etc/passwd
-
-This program uses the `-F' option on the command line to set the file
-separator. (Fields in `/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.)
-
-
-
-File: gawk-info, Node: Non-Constant Fields, Next: Changing Fields, Prev: Fields, Up: Reading Files
-
-Non-constant Field Numbers
-==========================
-
-The number of a field does not need to be a constant. Any expression
-in the `awk' language can be used after a `$' to refer to a field.
-The `awk' utility evaluates the expression and uses the "numeric
-value" as a field number. Consider this example:
-
- awk '{ print $NR }'
-
-Recall that `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.
-
-Here is another example of using expressions as field numbers:
-
- awk '{ print $(2*2) }' BBS-list
-
-The `awk' language must evaluate the expression `(2*2)' and use its
-value as the field number to print. The `*' sign represents
-multiplication, so the expression `2*2' evaluates to 4. This
-example, then, prints the hours of operation (the fourth field) for
-every line of the file `BBS-list'.
-
-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, `$(1-4)' would try to examine field number -3; it would
-result in an empty string.
-
-If the field number you compute is zero, you get the entire record.
-
-The number of fields in the current record is stored in the special
-variable `NF' (*note Special::.). The expression `$NF' is not a
-special feature: it is the direct consequence of evaluating `NF' and
-using its value as a field number.
-
-
-
-File: gawk-info, Node: Changing Fields, Next: Field Separators, Prev: Non-Constant Fields, Up: Reading Files
-
-Changing the Contents of a Field
-================================
-
-You can change the contents of a field as seen by `awk' within an
-`awk' program; this changes what `awk' perceives as the current input
-record. (The actual input is untouched: `awk' never modifies the
-input file.)
-
-Look at this example:
-
- awk '{ $3 = $2 - 10; print $2, $3 }' inventory-shipped
-
-The `-' sign represents subtraction, so this program reassigns field
-three, `$3', to be the value of field two minus ten, ``$2' - 10'.
-(*Note Arithmetic Ops::.) Then field two, and the new value for
-field three, are printed.
-
-In order for this to work, the text in field `$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. *Note Conversion::.
-
-When you change the value of a field (as perceived by `awk'), the
-text of the input record is recalculated to contain the new field
-where the old one was. `$0' will from that time on reflect the
-altered field. Thus,
-
- awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
-
-will print 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:
-
- awk '{ $6 = ($5 + $4 + $3 + $2)/4) ; print $6 }' inventory-shipped
-
-We've just created `$6', whose value is the average of fields `$2',
-`$3', `$4', and `$5'. The `+' sign represents addition, and the `/'
-sign represents division. For the file `inventory-shipped' `$6'
-represents the average number of parcels shipped for a particular
-month.
-
-Creating a new field changes what `awk' interprets as the current
-input record. The value of `$0' will be recomputed. This
-recomputation affects and is affected by features not yet discussed,
-in particular, the "Output Field Separator", `OFS', which is used to
-separate the fields (*note Output Separators::.), and `NF' (the
-number of fields; *note Fields::.). For example, the value of `NF'
-will be set to the number of the highest out--of--range field you
-create.
-
-Note, however, that merely *referencing* an out--of--range field will
-*not* change the value of either `$0' or `NF'. Referencing an
-out--of--range field merely produces a null string. For example:
-
- if ($(NF+1) != "")
- print "can't happen"
- else
- print "everything is normal"
-
-should print `everything is normal'. (*Note If::, for more
-information about `awk''s `if-else' statements.)
-
-
-
-File: gawk-info, Node: Field Separators, Next: Multiple, Prev: Changing Fields, Up: Reading Files
-
-Specifying How Fields Are Separated
-===================================
-
-You can change the way `awk' splits a record into fields by changing
-the value of the "field separator". The field separator is
-represented by the special variable `FS' in an `awk' program, and can
-be set by `-F' on the command line. The `awk' language scans each
-input line for the field separator character to determine the
-positions of fields within that line. Shell programmers take note!
-`awk' uses the variable `FS', not `IFS'.
-
-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 `FS' by "assigning" it a new value. You can
-do this using the special `BEGIN' pattern (*note BEGIN/END::.). This
-pattern allows you to change the value of `FS' before any input is
-read. The new value of `FS' is enclosed in quotations. For example,
-set the value of `FS' to the string `","':
-
- awk 'BEGIN { FS = "," } ; { print $2 }'
-
-and use the input line:
-
- John Q. Smith, 29 Oak St., Walamazoo, MI 42139
-
-This `awk' program will extract the string `29 Oak St.'.
-
-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 `John Q. Smith, LXIX'. If you assigned
-`FS' to be `,' then:
-
- awk 'BEGIN { FS = "," } ; { print $2 }
-
-would extract `LXIX', instead of `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.
-
-You can assign `FS' to be a series of characters. For example, the
-assignment:
-
- FS = ", \t"
-
-makes every area of an input line that consists of a comma followed
-by a space and a tab, into a field separator. (`\t' stands for a tab.)
-
-If `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 `FS' to a string longer than one character, that string
-is evaluated as a "regular expression" (*note Regexp::.). The value
-of the regular expression is used as a field separator.
-
-`FS' can be set on the command line. You use the `-F' argument to do
-so. For example:
-
- awk -F, 'PROGRAM' INPUT-FILES
-
-sets `FS' to be the `,' character. Notice that the argument uses a
-capital `F'. Contrast this with `-f', which specifies a file
-containing an `awk' program. Case is significant in command options:
-the `-F' and `-f' options have nothing to do with each other. You
-can use both options at the same time to set the `FS' argument *and*
-get an `awk' program from a file.
-
-As a special case, if the argument to `-F' is `t', then `FS' is set
-to the tab character. (This is because if you type `-F\t', without
-the quotes, at the shell, the `\' gets deleted, so `awk' figures that
-you really want your fields to be separated with tabs, and not `t's.
-Use `FS="t"' if you really do want to separate your fields with `t's.)
-
-For example, let's use an `awk' program file called `baud.awk' that
-contains the pattern `/300/', and the action `print $1'. We'll use
-the operating system utility `cat' to ``look'' at our program:
-
- % cat baud.awk
- /300/ { print $1 }
-
-Let's also set `FS' to be the `-' character. We will apply all this
-information to the file `BBS-list'. This `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.
-
- awk -F- -f baud.awk BBS-list
-
-produces this output:
-
- aardvark 555
- alpo
- barfly 555
- bites 555
- camelot 555
- core 555
- fooey 555
- foot 555
- macfoo 555
- sdace 555
- sabafoo 555
-
-Note the second line of output. If you check the original file, you
-will see that the second line looked like this:
-
- alpo-net 555-3412 2400/1200/300 A
-
-The `-' as part of the system's name was used as the field separator,
-instead of the `-' in the phone number that was originally intended.
-This demonstrates why you have to be careful in choosing your field
-and record separators.
-
-
-
-File: gawk-info, Node: Multiple, Next: Assignment Options, Prev: Field Separators, Up: Reading Files
-
-Multiple--Line Records
-======================
-
-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.
-
-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? 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
-`\f' in `awk', as in C) to separate them, making each record a page
-of the file. To do this, just set the variable `RS' to `"\f"' (a
-string containing the formfeed character), or whatever string you
-prefer to use.
-
-Another technique is to have blank lines separate records. By a
-special dispensation, a null string as the value of `RS' indicates
-that records are separated by one or more blank lines. If you set
-`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.
-
-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 `FS' to the string `"\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
-`"[ \t\n]+"' will do this nicely by treating the newlines inside the
-record just like spaces.
-
-When `RS' is set to the null string, the newline character *always*
-acts as a field separator. This is in addition to whatever value
-`FS' has. The probable reason for this rule is so that you get
-rational behavior in the default case (i.e. `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 `split' function to manually break up
-your data (*note String Functions::.).
-
-Here is how to use records separated by blank lines and break each
-line into fields normally:
-
- awk 'BEGIN { RS = ""; FS = "[ \t\n]+" } ; { print $0 }' BBS-list
-
-
-
-File: gawk-info, Node: Assignment Options, Next: Getline, Prev: Multiple, Up: Reading Files
-
-Assigning Variables on the Command Line
-=======================================
-
-You can include variable "assignments" among the file names on the
-command line used to invoke `awk' (*note Command Line::.). Such
-assignments have the form:
-
- VARIABLE=TEXT
-
-and allow you to change variables either at the beginning of the
-`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:
-
- awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
-
-prints the value of field number `n' for all input records. Before
-the first file is read, the command line sets the variable `n' equal
-to 4. This causes the fourth field of the file `inventory-shipped'
-to be printed. After the first file has finished, but before the
-second file is started, `n' is set to 2, so that the second field of
-the file `BBS-list' will be printed.
-
-Command line arguments are made available for explicit examination by
-the `awk' program in an array named `ARGV' (*note Special::.).
-
-
-
-File: gawk-info, Node: Getline, Prev: Assignment Options, Up: Reading Files
-
-Explicit Input with `getline'
-=============================
-
-So far we have been getting our input files from `awk''s main input
-stream--either the standard input (usually your terminal) or the
-files specified on the command line. The `awk' language has a
-special built--in function called `getline' that can be used to read
-input under your explicit control.
-
-This command is quite complex and should *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
-`getline' command include material that has not been covered yet.
-Therefore, come back and attempt the `getline' command *after* you
-have reviewed the rest of this manual and have a good knowledge of
-how `awk' works.
-
-When retrieving input, `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 `getline' returns a -1.
-
-In the following examples, COMMAND stands for a string value that
-represents a shell command.
-
-`getline'
- The `getline' function can be used by itself, in an `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
- *right now* on the next record. Here's an example:
-
- awk '{
- if (t = index($0, "/*")) {
- if(t > 1)
- tmp = substr($0, 1, t - 1)
- else
- tmp = ""
- u = index(substr($0, t + 2), "*/")
- while (! u) {
- getline
- t = -1
- u = index($0, "*/")
- }
- if(u <= length($0) - 2)
- $0 = tmp substr($0, t + u + 3)
- else
- $0 = tmp
- }
- print $0
- }'
-
- This `awk' program deletes all comments, `/* ... */', from the
- input. By replacing the `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 expression.
-
- This form of the `getline' command sets `NF' (the number of
- fields; *note Fields::.), `NR' (the number of records read so
- far), the `FNR' variable (*note Records::.), and the value of
- `$0'.
-
- *Note:* The new value of `$0' will be used in testing the
- patterns of any subsequent rules. The original value of `$0'
- that triggered the rule which executed `getline' is lost. By
- contrast, the `next' statement reads a new record but
- immediately begins processing it normally, starting with the
- first rule in the program. *Note Next::.
-
-`getline VAR'
- This form of `getline' reads a record into the variable 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.
-
- 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
- `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 `awk' never sees it.
-
- The following example swaps every two lines of input. For
- example, given:
-
- wan
- tew
- free
- phore
-
- it outputs:
-
- tew
- wan
- phore
- free
-
- Here's the program:
-
- awk '{
- if ((getline tmp) > 0) {
- print tmp
- print $0
- } else
- print $0
- }'
-
- The `getline' function used in this way sets only `NR' and `FNR'
- (and of course, VAR). The record is not split into fields, so
- the values of the fields (including `$0') and the value of `NF'
- do not change.
-
-`getline < FILE'
- This form of the `getline' function takes its input from the
- file FILE. Here FILE is a string--valued expression that
- specifies the file name.
-
- 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 program reads its input record from the
- file `foo.input' when it encounters a first field with a value
- equal to 10 in the current input file.
-
- awk '{
- if ($1 == 10) {
- getline < "foo.input"
- print
- } else
- print
- }'
-
- Since the main input stream is not used, the values of `NR' and
- `FNR' are not changed. But the record read is split into fields
- in the normal manner, so the values of `$0' and other fields are
- changed. So is the value of `NF'.
-
- This does not cause the record to be tested against all the
- patterns in the `awk' program, in the way that would happen if
- the record were read normally by the main processing loop of
- `awk'. However the new record is tested against any subsequent
- rules, just as when `getline' is used without a redirection.
-
-`getline VAR < FILE'
- This form of the `getline' function takes its input from the
- file FILE and puts it in the variable VAR. As above, FILE is a
- string--valued expression that specifies the file to read from.
-
- In this version of `getline', none of the built--in variables
- are changed, and the record is not split into fields. The only
- variable changed is VAR.
-
- For example, the following program copies all the input files to
- the output, except for records that say `@include FILENAME'.
- Such a record is replaced by the contents of the file FILENAME.
-
- awk '{
- if (NF == 2 && $1 == "@include") {
- while ((getline line < $2) > 0)
- print line
- close($2)
- } else
- print
- }'
-
- 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 `@include' line.
-
- The `close' command is used to ensure that if two identical
- `@include' lines appear in the input, the entire specified file
- is included twice. *Note Close Input::.
-
- One deficiency of this program is that it does not process
- nested `@include' statements the way a true macro preprocessor
- would.
-
-`COMMAND | getline'
- You can "pipe" the output of a command into `getline'. A pipe
- is simply a way to link the output of one program to the input
- of another. In this case, the string COMMAND is run as a shell
- command and its output is piped into `awk' to be used as input.
- This form of `getline' reads one record from the pipe.
-
- For example, the following program copies input to output,
- except for lines that begin with `@execute', which are replaced
- by the output produced by running the rest of the line as a
- shell command:
-
- awk '{
- if ($1 == "@execute") {
- tmp = substr($0, 10)
- while ((tmp | getline) > 0)
- print
- close(tmp)
- } else
- print
- }'
-
- The `close' command is used to ensure that if two identical
- `@execute' lines appear in the input, the command is run again
- for each one. *Note Close Input::.
-
- Given the input:
-
- foo
- bar
- baz
- @execute who
- bletch
-
- the program might produce:
-
- foo
- bar
- baz
- hack ttyv0 Jul 13 14:22
- hack ttyp0 Jul 13 14:23 (gnu:0)
- hack ttyp1 Jul 13 14:23 (gnu:0)
- hack ttyp2 Jul 13 14:23 (gnu:0)
- hack ttyp3 Jul 13 14:23 (gnu:0)
- bletch
-
- Notice that this program ran the command `who' and printed the
- result. (If you try this program yourself, you will get
- different results, showing you logged in.)
-
- This variation of `getline' splits the record into fields, sets
- the value of `NF' and recomputes the value of `$0'. The values
- of `NR' and `FNR' are not changed.
-
-`COMMAND | getline VAR'
- The output of the command COMMAND is sent through a pipe to
- `getline' and into the variable VAR. For example, the following
- program reads the current date and time into the variable
- `current_time', using the utility called `date', and then prints
- it.
-
- awk 'BEGIN {
- "date" | getline current_time
- close("date")
- print "Report printed on " current_time
- }'
-
- In this version of `getline', none of the built--in variables
- are changed, and the record is not split into fields.
-
-
-
-File: gawk-info, Node: Close Input, Up: Getline
-
-Closing Input Files
--------------------
-
-If the same file name or the same shell command is used with
-`getline' more than once during the execution of the `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
-`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 `close' statement:
-
- close (FILENAME)
-
-This statement closes a file or pipe, represented here by FILENAME.
-The string value of FILENAME must be the same value as the string
-used to open the file or pipe to begin with.
-
-Once this statement is executed, the next `getline' from that file or
-command will reopen the file or rerun the command.
-
-
-
-File: gawk-info, Node: Printing, Next: One-liners, Prev: Reading Files, Up: Top
-
-Printing Output
-***************
-
-One of the most common things that actions do is to output or "print"
-some or all of the input. For simple output, use the `print'
-statement. For fancier formatting use the `printf' statement. Both
-are described in this chapter.
-
-* Menu:
-
-* Print:: The `print' statement.
-* Print Examples:: Simple examples of `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 `printf' statement.
-
-
-
-File: gawk-info, Node: Print, Next: Print Examples, Up: Printing
-
-The `print' Statement
-=====================
-
-The `print' statement does output with simple, standardized
-formatting. You specify only the strings or numbers to be printed,
-in a list separated by commas. They are output, separated by single
-spaces, followed by a newline. The statement looks like this:
-
- print ITEM1, ITEM2, ...
-
- The entire list of items may optionally be enclosed in parentheses.
-The parentheses are necessary if any of the item expressions uses a
-relational operator; otherwise it could be confused with a
-redirection (*note Redirection::.). The relational operators are
-`==', `!=', `<', `>', `>=', `<=', `~' and `!~' (*note Comparison
-Ops::.).
-
-The items printed can be constant strings or numbers, fields of the
-current record (such as `$1'), variables, or any `awk' expressions.
-The `print' statement is completely general for computing *what*
-values to print. With one exception (*note Output Separators::.),
-what you can't do is specify *how* to print them--how many columns to
-use, whether to use exponential notation or not, and so on. For
-that, you need the `printf' statement (*note Printf::.).
-
-To print a fixed piece of text, write a string constant as one item,
-such as `"Hello there"'. If you forget to use the double--quote
-characters, your text will be taken as an `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 `print' with no items is equivalent to `print
-$0': it prints the entire current record. To print a blank line, use
-`print ""', where `""' is the null, or empty, string.
-
-Most often, each `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 single `print' can make any number of lines this way.
-
-
-
-File: gawk-info, Node: Print Examples, Next: Output Separators, Prev: Print, Up: Printing
-
-Examples of `print' Statements
-==============================
-
-Here is an example that prints the first two fields of each input
-record, with a space between them:
-
- awk '{ print $1, $2 }' inventory-shipped
-
-Its output looks like this:
-
- Jan 13
- Feb 15
- Mar 15
- ...
-
- A common mistake in using the `print' statement is to omit the comma
-between two items. This often has the effect of making the items run
-together in the output, with no space. The reason for this is that
-juxtaposing two string expressions in `awk' means to concatenate
-them. For example, without the comma:
-
- awk '{ print $1 $2 }' inventory-shipped
-
-prints:
-
- Jan13
- Feb15
- Mar15
- ...
-
- Neither example's output makes much sense to someone unfamiliar with
-the file `inventory-shipped'. A heading line at the beginning would
-make it clearer. Let's add some headings to our table of months
-(`$1') and green crates shipped (`$2'). We do this using the BEGIN
-pattern (*note BEGIN/END::.) to cause the headings to be printed only
-once:
-
- awk 'BEGIN { print "Month Crates"
- print "---- -----" }
- { print $1, $2 }' inventory-shipped
-
-Did you already guess what will happen? This program prints the
-following:
-
- Month Crates
- ---- -----
- Jan 13
- Feb 15
- Mar 15
- ...
-
- The headings and the table data don't line up! We can fix this by
-printing some spaces between the two fields:
-
- awk 'BEGIN { print "Month Crates"
- print "---- -----" }
- { print $1, " ", $2 }' inventory-shipped
-
-You can imagine that this way of lining up columns can get pretty
-complicated when you have many columns to fix. Counting spaces for
-two or three columns can be simple, but more than this and you can
-get ``lost'' quite easily. This is why the `printf' statement was
-created (*note Printf::.); one of its specialties is lining up
-columns of data.
-
-
-
-File: gawk-info, Node: Output Separators, Next: Redirection, Prev: Print Examples, Up: Printing
-
-Output Separators
-=================
-
-As mentioned previously, a `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 "output field separator", by setting the
-special variable `OFS'. The initial value of this variable is the
-string `" "'.
-
-The output from an entire `print' statement is called an "output
-record". Each `print' statement outputs one output record and then
-outputs a string called the "output record separator". The special
-variable `ORS' specifies this string. The initial value of the
-variable is the string `"\n"' containing a newline character; thus,
-normally each `print' statement makes a separate line.
-
-You can change how output fields and records are separated by
-assigning new values to the variables `OFS' and/or `ORS'. The usual
-place to do this is in the `BEGIN' rule (*note BEGIN/END::.), so that
-it happens before any input is processed. You may also do this with
-assignments on the command line, before the names of your input files.
-
-The following example prints the first and second fields of each
-input record separated by a semicolon, with a blank line added after
-each line:
-
- awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
- { print $1, $2 }' BBS-list
-
-If the value of `ORS' does not contain a newline, all your output
-will be run together on a single line, unless you output newlines
-some other way.
-
-
-
-File: gawk-info, Node: Redirection, Next: Printf, Prev: Output Separators, Up: Printing
-
-Redirecting Output of `print' and `printf'
-==========================================
-
-So far we have been dealing only with output that prints to the
-standard output, usually your terminal. Both `print' and `printf'
-can be told to send their output to other places. This is called
-"redirection".
-
-A redirection appears after the `print' or `printf' statement.
-Redirections in `awk' are written just like redirections in shell
-commands, except that they are written inside the `awk' program.
-
-Here are the three forms of output redirection. They are all shown
-for the `print' statement, but they work for `printf' also.
-
-`print ITEMS > OUTPUT-FILE'
- This type of redirection prints the items onto the output file
- OUTPUT-FILE. The file name OUTPUT-FILE can be any expression.
- Its value is changed to a string and then used as a filename
- (*note Expressions::.).
-
- When this type of redirection is used, the OUTPUT-FILE is erased
- before the first output is written to it. Subsequent writes do
- not erase OUTPUT-FILE, but append to it. If OUTPUT-FILE does
- not exist, then it is created.
-
- For example, here is how one `awk' program can write a list of
- BBS names to a file `name-list' and a list of phone numbers to a
- file `phone-list'. Each output file contains one name or number
- per line.
-
- awk '{ print $2 > "phone-list"
- print $1 > "name-list" }' BBS-list
-
-`print ITEMS >> OUTPUT-FILE'
- This type of redirection prints the items onto the output file
- OUTPUT-FILE. The difference between this and the single--`>'
- redirection is that the old contents (if any) of OUTPUT-FILE are
- not erased. Instead, the `awk' output is appended to the file.
-
-`print ITEMS | COMMAND'
- It is also possible to send output through a "pipe" instead of
- into a file. This type of redirection opens a pipe to COMMAND
- and writes the values of ITEMS through this pipe, to another
- process created to execute COMMAND.
-
- The redirection argument COMMAND is actually an `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:
-
- awk '{ print $1 > "names.unsorted"
- print $1 | "sort -r > names.sorted" }' BBS-list
-
- Here the unsorted list is written with an ordinary redirection
- while the sorted list is written by piping through the `sort'
- utility.
-
- Here is an example that uses redirection to mail a message to a
- mailing list `bug-system'. This might be useful when trouble is
- encountered in an `awk' script run periodically for system
- maintenance.
-
- print "Awk script failed:", $0 | "mail bug-system"
- print "processing record number", FNR, "of", FILENAME | "mail bug-system"
- close ("mail bug-system")
-
- We use a `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. *Note Close Output::, for more information on this.
-
-Redirecting output using `>', `>>', or `|' asks the system to open a
-file or pipe only if the particular FILE or COMMAND you've specified
-has not already been written to by your program.
-
-
-
-File: gawk-info, Node: Close Output, Up: Redirection
-
-Closing Output Files and Pipes
-------------------------------
-
-When a file or pipe is opened, the filename or command associated
-with it is remembered by `awk' and subsequent writes to the same file
-or command are appended to the previous writes. The file or pipe
-stays open until `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 `close' command, as follows:
-
- close (FILENAME)
-
-or
-
- close (COMMAND)
-
-The argument FILENAME or 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:
-
- print $1 | "sort -r > names.sorted"
-
-then you must close it with this:
-
- close ("sort -r > names.sorted")
-
-Here are some reasons why you might need to close an output file:
-
- * To write a file and read it back later on in the same `awk'
- program. Close the file when you are finished writing it; then
- you can start reading it with `getline' (*note Getline::.).
-
- * To write numerous files, successively, in the same `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.
-
- * 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 `mail' program, the
- message will not actually be sent until the pipe is closed.
-
- * 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 `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.
-
-
-
-File: gawk-info, Node: Printf, Prev: Redirection, Up: Printing
-
-Using `printf' Statements For Fancier Printing
-==============================================
-
-If you want more precise control over the output format than `print'
-gives you, use `printf'. With `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 "format string".
-
-* Menu:
-
-* Basic Printf:: Syntax of the `printf' statement.
-* Format-Control:: Format-control letters.
-* Modifiers:: Format--specification modifiers.
-* Printf Examples:: Several examples.
-
-
-
-File: gawk-info, Node: Basic Printf, Next: Format-Control, Up: Printf
-
-Introduction to the `printf' Statement
---------------------------------------
-
-The `printf' statement looks like this:
-
- printf FORMAT, ITEM1, ITEM2, ...
-
- The entire list of items may optionally be enclosed in parentheses.
-The parentheses are necessary if any of the item expressions uses a
-relational operator; otherwise it could be confused with a
-redirection (*note Redirection::.). The relational operators are
-`==', `!=', `<', `>', `>=', `<=', `~' and `!~' (*note Comparison
-Ops::.).
-
-The difference between `printf' and `print' is the argument 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 the
-"format string".
-
-The format string is essentially the same as in the C library
-function `printf'. Most of FORMAT is text to be output verbatim.
-Scattered among this text are "format specifiers", one per item.
-Each format specifier says to output the next item at that place in
-the format.
-
-The `printf' statement does not automatically append a newline to its
-output. It outputs nothing but what the format specifies. So if you
-want a newline, you must include one in the format. The output
-separator variables `OFS' and `ORS' have no effect on `printf'
-statements.
-
-
-
-File: gawk-info, Node: Format-Control, Next: Modifiers, Prev: Basic Printf, Up: Printf
-
-Format--Control Characters
---------------------------
-
-A format specifier starts with the character `%' and ends with a
-"format--control letter"; it tells the `printf' statement how to
-output one item. (If you actually want to output a `%', write `%%'.)
-The format--control letter specifies what kind of value to print.
-The rest of the format specifier is made up of optional "modifiers"
-which are parameters such as the field width to use.
-
-Here is a list of them:
-
-`c'
- This prints a number as an ASCII character. Thus, `printf "%c",
- 65' outputs the letter `A'. The output for a string value is
- the first character of the string.
-
-`d'
- This prints a decimal integer.
-
-`e'
- This prints a number in scientific (exponential) notation. For
- example,
-
- printf "%4.3e", 1950
-
- prints `1.950e+03', with a total of 4 significant figures of
- which 3 follow the decimal point. The `4.3' are "modifiers",
- discussed below.
-
-`f'
- This prints a number in floating point notation.
-
-`g'
- This prints either scientific notation or floating point
- notation, whichever is shorter.
-
-`o'
- This prints an unsigned octal integer.
-
-`s'
- This prints a string.
-
-`x'
- This prints an unsigned hexadecimal integer.
-
-`%'
- This isn't really a format--control letter, but it does have a
- meaning when used after a `%': the sequence `%%' outputs one
- `%'. It does not consume an argument.
-
-
-
-File: gawk-info, Node: Modifiers, Next: Printf Examples, Prev: Format-Control, Up: Printf
-
-Modifiers for `printf' Formats
-------------------------------
-
-A format specification can also include "modifiers" that can control
-how much of the item's value is printed and how much space it gets.
-The modifiers come between the `%' and the format--control letter.
-Here are the possible modifiers, in the order in which they may appear:
-
-`-'
- 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.
-
-`WIDTH'
- This is a number representing the desired width of a field.
- Inserting any number between the `%' 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.
-
-`.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.
-
-The C library `printf''s dynamic WIDTH and PREC capability (for
-example, `"%*.*s"') is not supported. However, it can be easily
-simulated using concatenation to dynamically build the format string.
-
-
-
-File: gawk-info, Node: Printf Examples, Prev: Modifiers, Up: Printf
-
-Examples of Using `printf'
---------------------------
-
-Here is how to use `printf' to make an aligned table:
-
- awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
-
-prints the names of bulletin boards (`$1') of the file `BBS-list' as
-a string of 10 characters, left justified. It also prints the phone
-numbers (`$2') afterward on the line. This will produce an aligned
-two--column table of names and phone numbers, like so:
-
- aardvark 555-5553
- alpo-net 555-3412
- barfly 555-7685
- bites 555-1675
- camelot 555-0542
- core 555-2912
- fooey 555-1234
- foot 555-6699
- macfoo 555-6480
- sdace 555-3430
- sabafoo 555-2127
-
-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 (*note
-BEGIN/END::.) to cause the header to be printed only once, at the
-beginning of the `awk' program:
-
- awk 'BEGIN { print "Name Number"
- print "--- -----" }
- { printf "%-10s %s\n", $1, $2 }' BBS-list
-
-Did you notice that we mixed `print' and `printf' statements in the
-above example? We could have used just `printf' statements to get
-the same results:
-
- awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
- printf "%-10s %s\n", "---", "-----" }
- { printf "%-10s %s\n", $1, $2 }' BBS-list
-
-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.
-
-The fact that the same format specification is used can be emphasized
-by storing it in a variable, like so:
-
- awk 'BEGIN { format = "%-10s %s\n"
- printf format, "Name", "Number"
- printf format, "---", "-----" }
- { printf format, $1, $2 }' BBS-list
-
-See if you can use the `printf' statement to line up the headings and
-table data for our `inventory-shipped' example covered earlier in the
-section on the `print' statement (*note Print::.).
-
-
-
-File: gawk-info, Node: One-liners, Next: Patterns, Prev: Printing, Up: Top
-
-Useful ``One-liners''
-*********************
-
-Useful `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 of the program will give you a good idea of what is going
-on, but please read the rest of the manual to become an `awk' expert!
-
-`awk '{ num_fields = num_fields + NF }'
-`` END { print num_fields }'''
- This program prints the total number of fields in all input lines.
-
-`awk 'length($0) > 80''
- This program prints every line longer than 80 characters. The
- sole rule has a relational expression as its pattern, and has no
- action (so the default action, printing the record, is used).
-
-`awk 'NF > 0''
- This program prints every line that has at least one field.
- This is an 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).
-
-`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.
-
-`awk 'BEGIN { for (i = 1; i <= 7; i++)'
-`` print int(101 * rand()) }'''
- This program prints 7 random numbers from 0 to 100, inclusive.
-
-`ls -l FILES | awk '{ x += $4 } ; END { print "total bytes: " x }''
- This program prints the total number of bytes used by FILES.
-
-`expand FILE | awk '{ if (x < length()) x = length() }'
-`` END { print "maximum line length is " x }'''
- This program prints the maximum line length of FILE. The input
- is piped through the `expand' program to change tabs into
- spaces, so the widths compared are actually the right--margin
- columns.
-
-
-
-File: gawk-info, Node: Patterns, Next: Actions, Prev: One-liners, Up: Top
-
-Patterns
-********
-
-Patterns control the execution of rules: a rule is executed when its
-pattern matches the input record. The `awk' language provides
-several special patterns that are described in the sections that
-follow. Patterns include:
-
-NULL
- The empty pattern, which matches every input record. (*Note The
- Empty Pattern: Empty.)
-
-/REGULAR EXPRESSION/
- A regular expression as a pattern. It matches when the text of
- the input record fits the regular expression. (*Note Regular
- Expressions as Patterns: Regexp.)
-
-CONDEXP
- A single comparison expression. It matches when it is true.
- (*Note Comparison Expressions as Patterns: Comparison Patterns.)
-
-`BEGIN'
-`END'
- Special patterns to supply start--up or clean--up information to
- `awk'. (*Note Specifying Record Ranges With Patterns: BEGIN/END.)
-
-PAT1, PAT2
- A pair of patterns separated by a comma, specifying a range of
- records. (*Note Specifying Record Ranges With Patterns: Ranges.)
-
-CONDEXP1 BOOLEAN CONDEXP2
- A "compound" pattern, which combines expressions with the
- operators `and', `&&', and `or', `||'. (*Note Boolean
- Operators and Patterns: Boolean.)
-
-! CONDEXP
- The pattern CONDEXP is evaluated. Then the `!' performs a
- boolean ``not'' or logical negation operation; if the input line
- matches the pattern in CONDEXP then the associated action is
- *not* executed. If the input line did not match that pattern,
- then the action *is* executed. (*Note Boolean Operators and
- Patterns: Boolean.)
-
-(EXPR)
- Parentheses may be used to control how operators nest.
-
-PAT1 ? PAT2 : 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. (*Note Conditional Patterns: Conditional
- Patterns.)
-
-* Menu:
-
-The following subsections describe these forms in detail:
-
-* Empty:: The empty pattern, which matches every record.
-
-* Regexp:: Regular expressions such as `/foo/'.
-
-* Comparison Patterns:: Comparison expressions such as `$1 > 10'.
-
-* Boolean:: Combining comparison expressions.
-
-* Ranges:: Using pairs of patterns to specify record ranges.
-
-* BEGIN/END:: Specifying initialization and cleanup rules.
-
-* Conditional Patterns:: Patterns such as `pat1 ? pat2 : pat3'.
-
-
-
-File: gawk-info, Node: Empty, Next: Regexp, Up: Patterns
-
-The Empty Pattern
-=================
-
-An empty pattern is considered to match *every* input record. For
-example, the program:
-
- awk '{ print $1 }' BBS-list
-
-prints just the first field of every record.
-
-
-
-File: gawk-info, Node: Regexp, Next: Comparison Patterns, Prev: Empty, Up: Patterns
-
-Regular Expressions as Patterns
-===============================
-
-A "regular expression", or "regexp", is a way of describing classes
-of strings. When enclosed in slashes (`/'), it makes an `awk'
-pattern that matches every input record that contains a match for the
-regexp.
-
-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 `foo' matches any string containing `foo'. (More
-complicated regexps let you specify classes of similar strings.)
-
-* Menu:
-
-* Usage: Regexp Usage. How regexps are used in patterns.
-* Operators: Regexp Operators. How to write a regexp.
-
-
-
-File: gawk-info, Node: Regexp Usage, Next: Regexp Operators, Up: Regexp
-
-How to use Regular Expressions
-------------------------------
-
-When you enclose `foo' in slashes, you get a pattern that matches a
-record that contains `foo'. For example, this prints the second
-field of each record that contains `foo' anywhere:
-
- awk '/foo/ { print $2 }' BBS-list
-
-Regular expressions can also be used in comparison expressions. Then
-you can specify the string to match against; it need not be the
-entire current input record. These comparison expressions can be
-used as patterns or in `if' and `while' statements.
-
-`EXP ~ /REGEXP/'
- This is true if the expression EXP (taken as a character string)
- is matched by REGEXP. The following example matches, or
- selects, all input records with the letter `J' in the first field:
-
- awk '$1 ~ /J/' inventory-shipped
-
- So does this:
-
- awk '{ if ($1 ~ /J/) print }' inventory-shipped
-
-`EXP !~ /REGEXP/'
- This is true if the expression EXP (taken as a character string)
- is *not* matched by REGEXP. The following example matches, or
- selects, all input records whose first field *does not* contain
- the letter `J':
-
- awk '$1 !~ /J/' inventory-shipped
-
-The right hand side of a `~' or `!~' operator need not be a constant
-regexp (i.e. a string of characters between `/'s). It can also be
-"computed", or "dynamic". For example:
-
- identifier = "[A-Za-z_][A-Za-z_0-9]+"
- $0 ~ identifier
-
-sets `identifier' to a regexp that describes `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.
-
-
-
-File: gawk-info, Node: Regexp Operators, Prev: Regexp Usage, Up: Regexp
-
-Regular Expression Operators
-----------------------------
-
-You can combine regular expressions with the following characters,
-called "regular expression operators", or "metacharacters", to
-increase the power and versatility of regular expressions. This is a
-table of metacharacters:
-
-`\'
- This is used to suppress the special meaning of a character when
- matching. For example:
-
- \$
-
- matches the character `$'.
-
-`^'
- This matches the beginning of the string or the beginning of a
- line within the string. For example:
-
- ^@chapter
-
- matches the `@chapter' at the beginning of a string, and can be
- used to identify chapter beginnings in Texinfo source files.
-
-`$'
- This is similar to `^', but it matches only at the end of a
- string or the end of a line within the string. For example:
-
- /p$/
-
- as a pattern matches a record that ends with a `p'.
-
-`.'
- This matches any single character except a newline. For example:
-
- .P
-
- matches any single character followed by a `P' in a string.
- Using concatenation we can make regular expressions like `U.A',
- which matches any three--character string that begins with `U'
- and ends with `A'.
-
-`[...]'
- This is called a "character set". It matches any one of a group
- of characters that are enclosed in the square brackets. For
- example:
-
- [MVX]
-
- matches any of the characters `M', `V', or `X' in a string.
-
- Ranges of characters are indicated by using a hyphen between the
- beginning and ending characters, and enclosing the whole thing
- in brackets. For example:
-
- [0-9]
-
- matches any string that contains a digit.
-
- Note that special patterns have to be followed to match the
- characters, `]', `-', and `^' when they are enclosed in the
- square brackets. To match a `]', make it the first character in
- the set. For example:
-
- []d]
-
- matches either `]', or `d'.
-
- To match `-', write it as `--', which is a range containing only
- `-'. You may also make the `-' be the first or last character
- in the set. To match `^', make it any character except the
- first one of a set.
-
-`[^ ...]'
- This is the "complemented character set". The first character
- after the `[' *must* be a `^'. This matches any characters
- *except* those in the square brackets. For example:
-
- [^0-9]
-
- matches any characters that are not digits.
-
-`|'
- This is the "alternation operator" and it is used to specify
- alternatives. For example:
-
- ^P|[0-9]
-
- matches any string that matches either `^P' or `[0-9]'. This
- means it matches any string that contains a digit or starts with
- `P'.
-
-`(...)'
- Parentheses are used for grouping in regular expressions as in
- arithmetic. They can be used to concatenate regular expressions
- containing the alternation operator, `|'.
-
-`*'
- This symbol means that the preceding regular expression is to be
- repeated as many times as possible to find a match. For example:
-
- ph*
-
- applies the `*' symbol to the preceding `h' and looks for
- matches to one `p' followed by any number of `h''s. This will
- also match just `p' if no `h''s are present.
-
- The `*' means repeat the *smallest* possible preceding
- expression in order to find a match. The `awk' language
- processes a `*' by matching as many repetitions as can be found.
- For example:
-
- awk '/\(c[ad][ad]*r x\)/ { print }' sample
-
- matches every record in the input containing a string of the
- form `(car x)', `(cdr x)', `(cadr x)', and so on.
-
-`+'
- This symbol is similar to `*', but the preceding expression must
- be matched at least once. This means that:
-
- wh+y
-
- would match `why' and `whhy' but not `wy', whereas `wh*y' would
- match all three of these strings. And this is a simpler way of
- writing the last `*' example:
-
- awk '/\(c[ad]+r x\)/ { print }' sample
-
-`?'
- This symbol is similar to `*', but the preceding expression can
- be matched once or not at all. For example:
-
- fe?d
-
- will match `fed' or `fd', but nothing else.
-
-In regular expressions, the `*', `+', and `?' operators have the
-highest precedence, followed by concatenation, and finally by `|'.
-As in arithmetic, parentheses can change how operators are grouped.
-
-Any other character stands for itself. However, it is important to
-note that case in regular expressions *is* significant, both when
-matching ordinary (i.e. non--metacharacter) characters, and inside
-character sets. Thus a `w' in a regular expression matches only a
-lower case `w' and not either an uppercase or lowercase `w'. When
-you want to do a case--independent match, you have to use a character
-set: `[Ww]'.
-
-
-
-File: gawk-info, Node: Comparison Patterns, Next: Ranges, Prev: Regexp, Up: Patterns
-
-Comparison Expressions as Patterns
-==================================
-
-"Comparison patterns" use "relational operators" to compare strings
-or numbers. The relational operators are the same as in C. Here is
-a table of them:
-
-`X < Y'
- True if X is less than Y.
-
-`X <= Y'
- True if X is less than or equal to Y.
-
-`X > Y'
- True if X is greater than Y.
-
-`X >= Y'
- True if X is greater than or equal to Y.
-
-`X == Y'
- True if X is equal to Y.
-
-`X != Y'
- True if X is not equal to Y.
-
-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 "true".
-
-The operands of a relational operator are compared as numbers if they
-are both numbers. Otherwise they are converted to, and compared as,
-strings (*note Conversion::.). Strings are compared by comparing the
-first character of each, then the second character of each, and so on.
-Thus, `"10"' is less than `"9"'.
-
-The following example prints the second field of each input record
-whose first field is precisely `foo'.
-
- awk '$1 == "foo" { print $2 }' BBS-list
-
-Contrast this with the following regular expression match, which
-would accept any record with a first field that contains `foo':
-
- awk '$1 ~ "foo" { print $2 }' BBS-list
-
-
-
-File: gawk-info, Node: Ranges, Next: BEGIN/END, Prev: Comparison Patterns, Up: Patterns
-
-Specifying Record Ranges With Patterns
-======================================
-
-A "range pattern" is made of two patterns separated by a comma:
-`BEGPAT, ENDPAT'. It matches ranges of consecutive input records.
-The first pattern BEGPAT controls where the range begins, and the
-second one ENDPAT controls where it ends.
-
-They work as follows: BEGPAT is matched against every input record;
-when a record matches BEGPAT, the range pattern becomes "turned on".
-The range pattern matches this record. As long as it stays turned
-on, it automatically matches every input record read. But meanwhile,
-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 BEGPAT against each record. For example:
-
- awk '$1 == "on", $1 == "off"'
-
-prints every record between on/off pairs, inclusive.
-
-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
-these records, you can write `if' statements in the rule's action to
-distinguish them.
-
-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.
-
-
-
-File: gawk-info, Node: BEGIN/END, Next: Boolean, Prev: Ranges, Up: Patterns
-
-`BEGIN' and `END' Special Patterns
-==================================
-
-`BEGIN' and `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 `awk' script. A `BEGIN' rule is
-executed, once, before the first input record has been read. An
-`END' rule is executed, once, after all the input has been read. For
-example:
-
- awk 'BEGIN { print "Analysis of ``foo'' program" }
- /foo/ { ++foobar }
- END { print "``foo'' appears " foobar " times." }' BBS-list
-
-This program finds out how many times the string `foo' appears in the
-input file `BBS-list'. The `BEGIN' pattern prints out a title for
-the report. There is no need to use the `BEGIN' pattern to
-initialize the counter `foobar' to zero, as `awk' does this for us
-automatically (*note Variables::.). The second rule increments the
-variable `foobar' every time a record containing the pattern `foo' is
-read. The last rule prints out the value of `foobar' at the end of
-the run.
-
-The special patterns `BEGIN' and `END' do not combine with other
-kinds of patterns.
-
-An `awk' program may have multiple `BEGIN' and/or `END' rules. The
-contents of multiple `BEGIN' or `END' rules are treated as if they
-had been enclosed in a single rule, in the order that the rules are
-encountered in the `awk' program. (This feature was introduced with
-the new version of `awk'.)
-
-Multiple `BEGIN' and `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 `BEGIN' and
-`END' rules will be executed. Therefore you have to be careful how
-you write your library functions. (*Note Command Line::, for more
-information on using library functions.)
-
-If an `awk' program only has a `BEGIN' rule, and no other rules, then
-the program will exit after the `BEGIN' rule has been run. Older
-versions of `awk' used to read their input until end of file was
-seen. However, if an `END' rule exists as well, then the input will
-be read, even if there are no other rules in the program.
-
-`BEGIN' and `END' rules must have actions; there is no default action
-for these rules since there is no current record when they run.
-
-
-
-File: gawk-info, Node: Boolean, Next: Conditional Patterns, Prev: BEGIN/END, Up: Patterns
-
-Boolean Operators and Patterns
-==============================
-
-A boolean pattern is a combination of other patterns using the
-boolean operators ``or'' (`||'), ``and'' (`&&'), and ``not'' (`!'),
-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 `BEGIN' and `END', which never match any
-input record.
-
-Here are descriptions of the three boolean operators.
-
-`PAT1 && PAT2'
- Matches if both PAT1 and PAT2 match by themselves. For example,
- the following command prints all records in the input file
- `BBS-list' that contain both `2400' and `foo'.
-
- awk '/2400/ && /foo/' BBS-list
-
- Whether PAT2 matches is tested only if PAT1 succeeds. This can
- make a difference when PAT2 contains expressions that have side
- effects: in the case of `/foo/ && ($2 == bar++)', the variable
- `bar' is not incremented if there is no `foo' in the record.
-
-`PAT1 || PAT2'
- Matches if at least one of PAT1 and PAT2 matches the current
- input record. For example, the following command prints all
- records in the input file `BBS-list' that contain *either*
- `2400' or `foo', or both.
-
- awk '/2400/ || /foo/' BBS-list
-
- Whether PAT2 matches is tested only if PAT1 fails to match.
- This can make a difference when PAT2 contains expressions that
- have side effects.
-
-`!PAT'
- Matches if PAT does not match. For example, the following
- command prints all records in the input file `BBS-list' that do
- *not* contain the string `foo'.
-
- awk '! /foo/' BBS-list
-
-Note that boolean patterns are built from other patterns just as
-boolean expressions are built from other expressions (*note Boolean
-Ops::.). Any boolean expression is also a valid boolean pattern.
-But the converse is not true: simple regular expression patterns such
-as `/foo/' are not allowed in boolean expressions. Regular
-expressions can appear in boolean expressions only in conjunction
-with the matching operators, `~' and `!~'.
-
-
-
-File: gawk-info, Node: Conditional Patterns, Prev: Boolean, Up: Patterns
-
-Conditional Patterns
-====================
-
-Patterns may use a "conditional expression" much like the conditional
-expression of the C language. This takes the form:
-
- PAT1 ? PAT2 : PAT3
-
-The first pattern is evaluated. If it evaluates to TRUE, then the
-input record is tested against PAT2. Otherwise it is tested against
-PAT3. The conditional pattern matches if PAT2 or PAT3 (whichever one
-is selected) matches.
-
-
-
-File: gawk-info, Node: Actions, Next: Expressions, Prev: Patterns, Up: Top
-
-Actions: The Basics
-*******************
-
-The "action" part of an `awk' rule tells `awk' what to do once a
-match for the pattern is found. An action consists of one or more
-`awk' "statements", enclosed in curly braces (`{' and `}'). 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.
-
-Besides the print statements already covered (*note Printing::.),
-there are four kinds of action statements: expressions, control
-statements, compound statements, and function definitions.
-
- * "Expressions" include assignments, arithmetic, function calls,
- and more (*note Expressions::.).
-
- * "Control statements" specify the control flow of `awk' programs.
- The `awk' language gives you C--like constructs (`if', `for',
- `while', and so on) as well as a few special ones (*note
- Statements::.).
-
- * A "compound statement" is just one or more `awk' statements
- enclosed in curly braces. This way you can group several
- statements to form the body of an `if' or similar statement.
-
- * You can define "user--defined functions" for use elsewhere in
- the `awk' program (*note User-defined::.).
-
-
-
-File: gawk-info, Node: Expressions, Next: Statements, Prev: Actions, Up: Top
-
-Actions: Expressions
-********************
-
-Expressions are the basic building block of `awk' actions. An
-expression evaluates to a value, which you can print, test, store in
-a 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 `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 `$1' are also expressions.
-* Arrays:: Array element references are expressions.
-
-* Arithmetic Ops:: Arithmetic operations (`+', `-', etc.)
-* Concatenation:: Concatenating strings.
-* Comparison Ops:: Comparison of numbers and strings with `<', etc.
-* Boolean Ops:: Combining comparison expressions using boolean operators
- `||' (``or''), `&&' (``and'') and `!' (``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.
-* Function Calls:: A function call is an expression.
-
-
-
-File: gawk-info, Node: Constants, Next: Variables, Up: Expressions
-
-Constant Expressions
-====================
-
-There are two types of constants: numeric constants and string
-constants.
-
-The "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 `awk' in
-double--precision floating point. Here are some examples of numeric
-constants, which all have the same value:
-
- 105
- 1.05e+2
- 1050e-1
-
-A string constant consists of a sequence of characters enclosed in
-double--quote marks. For example:
-
- "parrot"
-
-represents the string constant `parrot'. Strings in `gawk' can be of
-any length and they can contain all the possible 8--bit ASCII
-characters including ASCII NUL. Other `awk' implementations may have
-difficulty with some character codes.
-
-Some characters cannot be included literally in a string. You
-represent them instead with "escape sequences", which are character
-sequences beginning with a backslash (`\').
-
-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 `\"'. Backslash itself is another character that can't be
-included normally; you write `\\' to put one backslash in the string.
-
-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 `awk' program, they may look ugly.
-
-`\b'
- Represents a backspaced, H'.
-
-`\f'
- Represents a formfeed, L'.
-
-`\n'
- Represents a newline, J'.
-
-`\r'
- Represents a carriage return, M'.
-
-`\t'
- Represents a horizontal tab, I'.
-
-`\v'
- Represents a vertical tab, K'.
-
-`\NNN'
- Represents the octal value NNN, where NNN is one to three digits
- between 0 and 7. For example, the code for the ASCII ESC
- (escape) character is `\033'.
-
-
-
-File: gawk-info, Node: Variables, Next: Arithmetic Ops, Prev: Constants, Up: Expressions
-
-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 must be a sequence of letters, digits and underscores, but
-it may not begin with a digit. Case is significant in variable
-names; `a' and `A' are distinct variables.
-
-A variable name is a valid expression by itself; it represents the
-variable's current value. Variables are given new values with
-"assignment operators" and "increment operators". *Note Assignment
-Ops::.
-
-A few variables have special built--in meanings, such as `FS', the
-field separator, and `NF', the number of fields in the current input
-record. *Note 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 `awk'. Each special
-variable's name is made entirely of upper case letters.
-
-Variables in `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 `awk', the way you would
-need to do in C or most other traditional programming languages.
-
-
-
-File: gawk-info, Node: Arithmetic Ops, Next: Concatenation, Prev: Variables, Up: Expressions
-
-Arithmetic Operators
-====================
-
-The `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:
-
- awk '{ $1 = $2 + $3 / $4; print }' inventory-shipped
-
-The arithmetic operators in `awk' are:
-
-`X + Y'
- Addition.
-
-`X - Y'
- Subtraction.
-
-`- X'
- Negation.
-
-`X / Y'
- Division. Since all numbers in `awk' are double--precision
- floating point, the result is not rounded to an integer: `3 / 4'
- has the value 0.75.
-
-`X * Y'
- Multiplication.
-
-`X % Y'
- Remainder. The quotient is rounded toward zero to an integer,
- multiplied by Y and this result is subtracted from X. This
- operation is sometimes known as ``trunc--mod''. The following
- relation always holds:
-
- `b * int(a / b) + (a % b) == a'
-
- One undesirable effect of this definition of remainder is that X
- % Y is negative if X is negative. Thus,
-
- -17 % 8 = -1
-
-`X ^ Y'
-`X ** Y'
- Exponentiation: X raised to the Y power. `2 ^ 3' has the value
- 8. The character sequence `**' is equivalent to `^'.
-
-
-
-File: gawk-info, Node: Concatenation, Next: Comparison Ops, Prev: Arithmetic Ops, Up: Expressions
-
-String 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:
-
- awk '{ print "Field number one: " $1 }' BBS-list
-
-produces, for the first record in `BBS-list':
-
- Field number one: aardvark
-
-If you hadn't put the space after the `:', the line would have run
-together. For example:
-
- awk '{ print "Field number one:" $1 }' BBS-list
-
-produces, for the first record in `BBS-list':
-
- Field number one:aardvark
-
-
-
-File: gawk-info, Node: Comparison Ops, Next: Boolean Ops, Prev: Concatenation, Up: Expressions
-
-Comparison Expressions
-======================
-
-"Comparison expressions" use "relational operators" to compare
-strings or numbers. The relational operators are the same as in C.
-Here is a table of them:
-
-`X < Y'
- True if X is less than Y.
-
-`X <= Y'
- True if X is less than or equal to Y.
-
-`X > Y'
- True if X is greater than Y.
-
-`X >= Y'
- True if X is greater than or equal to Y.
-
-`X == Y'
- True if X is equal to Y.
-
-`X != Y'
- True if X is not equal to Y.
-
-`X ~ REGEXP'
- True if regexp REGEXP matches the string X.
-
-`X !~ REGEXP'
- True if regexp REGEXP does not match the string X.
-
-`SUBSCRIPT in ARRAY'
- True if array ARRAY has an element with the subscript SUBSCRIPT.
-
-Comparison expressions have the value 1 if true and 0 if false.
-
-The operands of a relational operator are compared as numbers if they
-are both numbers. Otherwise they are converted to, and compared as,
-strings (*note Conversion::.). Strings are compared by comparing the
-first character of each, then the second character of each, and so on.
-Thus, `"10"' is less than `"9"'.
-
-For example,
-
- $1 == "foo"
-
-has the value of 1, or is true, if the first field of the current
-input record is precisely `foo'. By contrast,
-
- $1 ~ /foo/
-
-has the value 1 if the first field contains `foo'.
-
-
-
-File: gawk-info, Node: Boolean Ops, Next: Assignment Ops, Prev: Comparison Ops, Up: Expressions
-
-Boolean Operators
-=================
-
-A boolean expression is combination of comparison expressions or
-matching expressions, using the boolean operators ``or'' (`||'),
-``and'' (`&&'), and ``not'' (`!'), 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 `if' and `while'
-statements. They have numeric values (1 if true, 0 if false).
-
-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 (*note Boolean::.), which use
-the same boolean operators in patterns instead of expressions.
-
-`BOOLEAN1 && BOOLEAN2'
- True if both BOOLEAN1 and BOOLEAN2 are true. For example, the
- following statement prints the current input record if it
- contains both `2400' and `foo'.
-
- if ($0 ~ /2400/ && $0 ~ /foo/) print
-
- The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is
- true. This can make a difference when BOOLEAN2 contains
- expressions that have side effects: in the case of `$0 ~ /foo/
- && ($2 == bar++)', the variable `bar' is not incremented if
- there is no `foo' in the record.
-
-`BOOLEAN1 || BOOLEAN2'
- True if at least one of BOOLEAN1 and BOOLEAN2 is true. For
- example, the following command prints all records in the input
- file `BBS-list' that contain *either* `2400' or `foo', or both.
-
- awk '{ if ($0 ~ /2400/ || $0 ~ /foo/) print }' BBS-list
-
- The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is
- true. This can make a difference when BOOLEAN2 contains
- expressions that have side effects.
-
-`!BOOLEAN'
- True if BOOLEAN is false. For example, the following program
- prints all records in the input file `BBS-list' that do *not*
- contain the string `foo'.
-
- awk '{ if (! ($0 ~ /foo/)) print }' BBS-list
-
-
-
-File: gawk-info, Node: Assignment Ops, Next: Increment Ops, Prev: Boolean Ops, Up: Expressions
-
-Assignment Operators
-====================
-
-An "assignment" is an expression that stores a new value into a
-variable. For example, let's assign the value 1 to the variable `z':
-
- z = 1
-
-After this expression is executed, the variable `z' has the value 1.
-Whatever old value `z' had before the assignment is forgotten.
-
-The `=' sign is called an "assignment operator". It is the simplest
-assignment operator because the value of the right--hand operand is
-stored unchanged.
-
-The left--hand operand of an assignment can be a variable (*note
-Variables::.), a field (*note Changing Fields::.) or an array element
-(*note Arrays::.). These are all called "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 `"this food is good"' in the variable `message':
-
- thing = "food"
- predicate = "good"
- message = "this " thing " is " predicate
-
-(This also illustrates concatenation of strings.)
-
-It is important to note that variables do *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 `foo' has a numeric value at first, and a string value
-later on:
-
- foo = 1
- print foo
- foo = "bar"
- print foo
-
-When the second assignment gives `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, `z = 1' as an expression has the value 1.
-One consequence of this is that you can write multiple assignments
-together:
-
- x = y = z = 0
-
-stores the value 0 in all three variables. It does this because the
-value of `z = 0', which is 0, is stored into `y', and then the value
-of `y = z = 0', which is 0, is stored into `x'.
-
-You can use an assignment anywhere an expression is called for. For
-example, it is valid to write `x != (y = 1)' to set `y' to 1 and then
-test whether `x' equals 1. But this style tends to make 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 `=', there are several other assignment operators that do
-arithmetic with the old value of the variable. For example, the
-operator `+=' 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 `foo':
-
- foo += 5
-
-This is precisely equivalent to the following:
-
- 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 to a number.
-
-`LVALUE += INCREMENT'
- Adds INCREMENT to the value of LVALUE to make the new value of
- LVALUE.
-
-`LVALUE -= DECREMENT'
- Subtracts DECREMENT from the value of LVALUE.
-
-`LVALUE *= COEFFICIENT'
- Multiplies the value of LVALUE by COEFFICIENT.
-
-`LVALUE /= QUOTIENT'
- Divides the value of LVALUE by QUOTIENT.
-
-`LVALUE %= MODULUS'
- Sets LVALUE to its remainder by MODULUS.
-
-`LVALUE ^= POWER'
-`LVALUE **= POWER'
- Raises LVALUE to the power POWER.
-
-
-
-File: gawk-info, Node: Increment Ops, Next: Conversion, Prev: Assignment Ops, Up: Expressions
-
-Increment Operators
-===================
-
-"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 `awk' language; but they are
-convenient abbreviations for something very common.
-
-The operator to add 1 is written `++'. There are two ways to use
-this operator: pre--incrementation and post--incrementation.
-
-To pre--increment a variable V, write `++V'. This adds 1 to the
-value of V and that new value is also the value of this expression.
-The assignment expression `V += 1' is completely equivalent.
-
-Writing the `++' 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 *old*
-value. Thus, if `foo' has value 4, then the expression `foo++' has
-the value 4, but it changes the value of `foo' to 5.
-
-The post--increment `foo++' is nearly equivalent to writing `(foo +=
-1) - 1'. It is not perfectly equivalent because all numbers in `awk'
-are floating point: in floating point, `foo + 1 - 1' does not
-necessarily equal `foo'. But the difference will be 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 `--' works just like `++' except that it
-subtracts 1 instead of adding. Like `++', 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.
-
-`++LVALUE'
- This expression increments LVALUE and the new value becomes the
- value of this expression.
-
-`LVALUE++'
- This expression causes the contents of LVALUE to be incremented.
- The value of the expression is the *old* value of LVALUE.
-
-`--LVALUE'
- Like `++LVALUE', but instead of adding, it subtracts. It
- decrements LVALUE and delivers the value that results.
-
-`LVALUE--'
- Like `LVALUE++', but instead of adding, it subtracts. It
- decrements LVALUE. The value of the expression is the *old*
- value of LVALUE.
-
-
-
-File: gawk-info, Node: Conversion, Next: Conditional Exp, Prev: Increment Ops, Up: Expressions
-
-Conversion of Strings and Numbers
-=================================
-
-Strings are converted to numbers, and numbers to strings, if the
-context of your `awk' statement demands it. For example, if the
-values of `foo' or `bar' in the expression `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:
-
- two = 2; three = 3
- print (two three) + 4
-
-This eventually prints the (numeric) value `27'. The numeric
-variables `two' and `three' are converted to strings and concatenated
-together, and the resulting string is converted back to a number
-before adding `4'. The resulting numeric value `27' is printed.
-
-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.
-
-The exact manner in which numbers are converted into strings is
-controlled by the `awk' special variable `OFMT' (*note Special::.).
-Numbers are converted using a special version of the `sprintf'
-function (*note Built-in::.) with `OFMT' as the format specifier.
-
-`OFMT''s default value is `"%.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 `awk' uses double precision
-arithmetic. Double precision on most modern machines gives you 16 or
-17 decimal digits of precision.
-
-Strange results can happen if you set `OFMT' to a string that doesn't
-tell `sprintf' how to format floating point numbers in a useful way.
-For example, if you forget the `%' in the format, all numbers will be
-converted to the same constant string.
-
-
-
-File: gawk-info, Node: Conditional Exp, Next: Function Calls, Prev: Conversion, Up: Expressions
-
-Conditional Expressions
-=======================
-
-A "conditional expression" is a special kind of expression with three
-operands. It allows you to use one expression's value to select one
-of two other expressions.
-
-The conditional expression looks the same as in the C language:
-
- SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP
-
-There are three subexpressions. The first, SELECTOR, is always
-computed first. If it is ``true'' (not zero) then IF-TRUE-EXP is
-computed next and its value becomes the value of the whole expression.
-Otherwise, IF-FALSE-EXP is computed next and its value becomes the
-value of the whole expression.
-
-For example, this expression produces the absolute value of `x':
-
- x > 0 ? x : -x
-
-Each time the conditional expression is computed, exactly one of
-IF-TRUE-EXP and IF-FALSE-EXP is computed; the other is ignored. This
-is important when the expressions contain side effects. For example,
-this conditional expression examines element `i' of either array `a'
-or array `b', and increments `i'.
-
- x == y ? a[i++] : b[i++]
-
-This is guaranteed to increment `i' exactly once, because each time
-one or the other of the two increment expressions will be executed
-and the other will not be.
-
-
-
-File: gawk-info, Node: Function Calls, Prev: Conditional Exp, Up: Expressions
-
-Function Calls
-==============
-
-A "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
-example, the function `sqrt' computes the square root of a number.
-
-A fixed set of functions are "built in", which means they are
-available in every `awk' program. The `sqrt' function is one of
-these. *Note 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. *Note User-defined::,
-for how to do this.
-
-The way to use a function is with a "function call" expression, which
-consists of the function name followed by a list of "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 `()' after the function name.
-
-*Do not put any space between the function name and the
-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 function one day by mistake.
-
-Each function needs a particular number of arguments. For example,
-the `sqrt' function must be called with a single argument, like this:
-
- sqrt(ARGUMENT)
-
-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. *Note 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 (*note User-defined::.).
-
-Like every other expression, the function call has a value, which is
-computed by the function based on the arguments you give it. In this
-example, the value of `sqrt(ARGUMENT)' is the square root of the
-argument. A function can also have side effects, such as assigning
-the values of certain variables or doing I/O.
-
-Here is a command to read numbers, one number per line, and print the
-square root of each one:
-
- awk '{ print "The square root of", $1, "is", sqrt($1) }'
-
-
-
-File: gawk-info, Node: Statements, Next: Arrays, Prev: Expressions, Up: Top
-
-Actions: Statements
-*******************
-
-"Control statements" such as `if', `while', and so on control the
-flow of execution in `awk' programs. Most of the control statements
-in `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 `if' and `while', to
-distinguish them from simple expressions.
-
-In all the examples in this chapter, 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.
-
-* Menu:
-
-* Expressions:: One kind of statement simply computes an expression.
-
-* If:: Conditionally execute some `awk' statements.
-
-* While:: Loop until some condition is satisfied.
-
-* Do:: Do specified action while looping until some
- condition is satisfied.
-
-* For:: Another looping statement, that provides
- initialization and increment clauses.
-
-* Break:: Immediately exit the innermost enclosing loop.
-
-* Continue:: Skip to the end of the innermost enclosing loop.
-
-* Next:: Stop processing the current input record.
-
-* Exit:: Stop execution of `awk'.
-
-
-
-File: gawk-info, Node: If, Next: While, Up: Statements
-
-The `if' Statement
-==================
-
-The `if'-`else' statement is `awk''s decision--making statement. The
-`else' part of the statement is optional.
-
- `if (CONDITION) BODY1 else BODY2'
-
-Here CONDITION is an expression that controls what the rest of the
-statement will do. If CONDITION is true, BODY1 is executed;
-otherwise, BODY2 is executed (assuming that the `else' clause is
-present). The condition is considered true if it is nonzero or
-nonnull.
-
-Here is an example:
-
- awk '{ if (x % 2 == 0)
- print "x is even"
- else
- print "x is odd" }'
-
-In this example, if the statement containing `x' is found to be true
-(that is, x is divisible by 2), then the first `print' statement is
-executed, otherwise the second `print' statement is performed.
-
-If the `else' appears on the same line as BODY1, and BODY1 is a
-single statement, then a semicolon must separate BODY1 from `else'.
-To illustrate this, let's rewrite the previous example:
-
- awk '{ if (x % 2 == 0) print "x is even"; else
- print "x is odd" }'
-
-If you forget the `;', `awk' won't be able to parse it, 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 `else' if it were not the first thing on
-its line.
-
-
-
-File: gawk-info, Node: While, Next: Do, Prev: If, Up: Statements
-
-The `while' Statement
-=====================
-
-In programming, a loop means a part of a program that is (or at least
-can be) executed two or more times in succession.
-
-The `while' statement is the simplest looping statement in `awk'. It
-repeatedly executes a statement as long as a condition is true. It
-looks like this:
-
- while (CONDITION)
- BODY
-
-Here BODY is a statement that we call the "body" of the loop, and
-CONDITION is an expression that controls how long the loop keeps
-running.
-
-The first thing the `while' statement does is test CONDITION. If
-CONDITION is true, it executes the statement BODY. After BODY has
-been executed, CONDITION is tested again and this process is repeated
-until CONDITION is no longer true. If CONDITION is initially false,
-the body of the loop is never executed.
-
- awk '{ i = 1
- while (i <= 3) {
- print $i
- i++
- }
- }'
-
-This example prints the first three input fields, one per line.
-
-The loop works like this: first, the value of `i' is set to 1. Then,
-the `while' tests whether `i' is less than or equal to three. This
-is the case when `i' equals one, so the `i'-th field is printed.
-Then the `i++' increments the value of `i' and the loop repeats.
-
-When `i' reaches 4, the loop exits. Here 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.
-
-
-
-File: gawk-info, Node: Do, Next: For, Prev: While, Up: Statements
-
-The `do'--`while' Statement
-===========================
-
-The `do' loop is a variation of the `while' looping statement. The
-`do' loop executes the BODY once, then repeats BODY as long as
-CONDITION is true. It looks like this:
-
- do
- BODY
- while (CONDITION)
-
-Even if CONDITION is false at the start, BODY is executed at least
-once (and only once, unless executing BODY makes CONDITION true).
-Contrast this with the corresponding `while' statement:
-
- while (CONDITION)
- BODY
-
-This statement will not execute BODY even once if CONDITION is false
-to begin with.
-
-Here is an example of a `do' statement:
-
- awk '{ i = 1
- do {
- print $0
- i++
- } while (i <= 10)
- }'
-
-prints each input record ten times. It isn't a very realistic
-example, since in this case an ordinary `while' would do just as
-well. But this is normal; there is only occasionally a real use for
-a `do' statement.
-
-
-
-File: gawk-info, Node: For, Next: Break, Prev: Do, Up: Statements
-
-The `for' Statement
-===================
-
-The `for' statement makes it more convenient to count iterations of a
-loop. The general form of the `for' statement looks like this:
-
- for (INITIALIZATION; CONDITION; INCREMENT)
- BODY
-
-This statement starts by executing INITIALIZATION. Then, as long as
-CONDITION is true, it repeatedly executes BODY and then INCREMENT.
-Typically INITIALIZATION sets a variable to either zero or one,
-INCREMENT adds 1 to it, and CONDITION compares it against the desired
-number of iterations.
-
-Here is an example of a `for' statement:
-
- awk '{ for (i = 1; i <= 3; i++)
- print $i
- }'
-
-This prints the first three fields of each input record, one field
-per line.
-
-In the `for' statement, BODY stands for any statement, but
-INITIALIZATION, CONDITION and INCREMENT are just expressions. You
-cannot set more than one variable in the INITIALIZATION part unless
-you use a multiple assignment statement such as `x = y = 0', which is
-possible only if all the initial values are equal. (But you can
-initialize additional variables by writing their assignments as
-separate statements preceding the `for' loop.)
-
-The same is true of the INCREMENT part; to increment additional
-variables, you must write separate statements at the end of the loop.
-The C compound expression, using C's comma operator, would be useful
-in this context, but it is not supported in `awk'.
-
-Most often, 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:
-
- # print odd numbers from 1 to 100
- for (i = 1; i <= 100; i += 2)
- print i
-
-Any of the three expressions following `for' may be omitted if you
-don't want it to do anything. Thus, `for (;x > 0;)' is equivalent to
-`while (x > 0)'. If the CONDITION part is empty, it is treated as
-TRUE, effectively yielding an infinite loop.
-
-In most cases, a `for' loop is an abbreviation for a `while' loop, as
-shown here:
-
- INITIALIZATION
- while (CONDITION) {
- BODY
- INCREMENT
- }
-
-(The only exception is when the `continue' statement (*note
-Continue::.) is used inside the loop; changing a `for' statement to a
-`while' statement in this way can change the effect of the `continue'
-statement inside the loop.)
-
-The `awk' language has a `for' statement in addition to a `while'
-statement because often a `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 `for' loops.
-
-There is an alternate version of the `for' loop, for iterating over
-all the indices of an array:
-
- for (i in array)
- PROCESS array[i]
-
-*Note Arrays::, for more information on this version of the `for' loop.
-
-
-
-File: gawk-info, Node: Break, Next: Continue, Prev: For, Up: Statements
-
-The `break' Statement
-=====================
-
-The `break' statement jumps out of the innermost `for', `while', or
-`do'--`while' loop that encloses it. The following example finds the
-smallest divisor of any number, and also identifies prime numbers:
-
- awk '# find smallest divisor of num
- { num = $1
- for (div = 2; div*div <= num; div++)
- if (num % div == 0)
- break
- if (num % div == 0)
- printf "Smallest divisor of %d is %d\n", num, div
- else
- printf "%d is prime\n", num }'
-
-When the remainder is zero in the first `if' statement, `awk'
-immediately "breaks" out of the containing `for' loop. This means
-that `awk' proceeds immediately to the statement following the loop
-and continues processing. (This is very different from the `exit'
-statement (*note Exit::.) which stops the entire `awk' program.)
-
-Here is another program equivalent to the previous one. It
-illustrates how the CONDITION of a `for' or `while' could just as
-well be replaced with a `break' inside an `if':
-
- awk '# find smallest divisor of num
- { num = $1
- for (div = 2; ; div++) {
- if (num % div == 0) {
- printf "Smallest divisor of %d is %d\n", num, div
- break
- }
- if (div*div > num) {
- printf "%d is prime\n", num
- break
- }
- }
- }'
-
-
-
-File: gawk-info, Node: Continue, Next: Next, Prev: Break, Up: Statements
-
-The `continue' Statement
-========================
-
-The `continue' statement, like `break', is used only inside `for',
-`while', and `do'--`while' loops. It skips over the rest of the loop
-body, causing the next cycle around the loop to begin immediately.
-Contrast this with `break', which jumps out of the loop altogether.
-Here is an example:
-
- # print names that don't contain the string "ignore"
-
- # first, save the text of each line
- { names[NR] = $0 }
-
- # print what we're interested in
- END {
- for (x in names) {
- if (names[x] ~ /ignore/)
- continue
- print names[x]
- }
- }
-
-If any of the input records contain the string `ignore', this example
-skips the print statement and continues back to the first statement
-in the loop.
-
-This isn't a practical example of `continue', since it would be just
-as easy to write the loop like this:
-
- for (x in names)
- if (x !~ /ignore/)
- print x
-
-The `continue' statement causes `awk' to skip the rest of what is
-inside a `for' loop, but it resumes execution with the increment part
-of the `for' loop. The following program illustrates this fact:
-
- awk 'BEGIN {
- for (x = 0; x <= 20; x++) {
- if (x == 5)
- continue
- printf ("%d ", x)
- }
- print ""
- }'
-
-This program prints all the numbers from 0 to 20, except for 5, for
-which the `printf' is skipped. Since the increment `x++' is not
-skipped, `x' does not remain stuck at 5.
-
-
-
-File: gawk-info, Node: Next, Next: Exit, Prev: Continue, Up: Statements
-
-The `next' Statement
-====================
-
-The `next' statement forces `awk' to immediately stop processing the
-current record and go on to the next record. This means that no
-further rules are executed for the current record. The rest of the
-current rule's action is not executed either.
-
-Contrast this with the effect of the `getline' function (*note
-Getline::.). That too causes `awk' to read the next record
-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, `awk' program execution is a loop that reads
-an input record and then tests each rule pattern against it. If you
-think of this loop as a `for' statement whose body contains the
-rules, then the `next' statement is analogous to a `continue'
-statement: it skips to the end of the body of the loop, and executes
-the increment (which reads another record).
-
-For example, if your `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:
-
- NF != 4 {
- printf ("line %d skipped: doesn't have 4 fields", FNR) > "/dev/tty"
- next
- }
-
-so that the following rules will not see the bad record. The error
-message is redirected to `/dev/tty' (the terminal), so that it won't
-get lost amid the rest of the program's regular output.
-
-
-
-File: gawk-info, Node: Exit, Prev: Next, Up: Statements
-
-The `exit' Statement
-====================
-
-The `exit' statement causes `awk' to immediately stop executing the
-current rule and to stop processing input; any remaining input is
-ignored.
-
-If an `exit' statement is executed from a `BEGIN' rule the program
-stops processing everything immediately. No input records will be
-read. However, if an `END' rule is present, it will be executed
-(*note BEGIN/END::.).
-
-If `exit' is used as part of an `END' rule, it causes the program to
-stop immediately.
-
-An `exit' statement that is part an ordinary rule (that is, not part
-of a `BEGIN' or `END' rule) stops the execution of any further
-automatic rules, but the `END' rule is executed if there is one. If
-you don't want the `END' rule to do its job in this case, you can set
-a variable to nonzero before the `exit' statement, and check that
-variable in the `END' rule.
-
-If an argument is supplied to `exit', its value is used as the exit
-status code for the `awk' process. If no argument is supplied,
-`exit' returns status zero (success).
-
-For example, let's say you've discovered an error condition you
-really don't know how to handle. Conventionally, programs report
-this by exiting with a nonzero status. Your `awk' program can do
-this using an `exit' statement with a nonzero argument. Here's an
-example of this:
-
- BEGIN {
- if (("date" | getline date_now) < 0) {
- print "Can't get system date"
- exit 4
- }
- }
-
-
-
-File: gawk-info, Node: Arrays, Next: Built-in, Prev: Statements, Up: Top
-
-Actions: Using Arrays in `awk'
-******************************
-
-An "array" is a table of various values, called "elements". The
-elements of an array are distinguished by their "indices". Names of
-arrays in `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 `awk' program.
-
-* Menu:
-
-* Intro: Array Intro. Basic facts abou arrays in `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.
-
-* Scanning an Array:: A variation of the `for' statement. It loops
- through the indices of an array's existing elements.
-
-* Delete:: The `delete' statement removes an element from an array.
-
-* Multi-dimensional:: Emulating multi--dimensional arrays in `awk'.
-* Multi-scanning:: Scanning multi--dimensional arrays.
-
-
-
-File: gawk-info, Node: Array Intro, Next: Reference to Elements, Up: Arrays
-
-Introduction to Arrays
-======================
-
-The `awk' language has one--dimensional "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 `awk' program.
-
-Arrays in `awk' superficially resemble arrays in other programming
-languages; but there are fundamental differences. In `awk', you
-don't need to declare the size of an array before you start to use it.
-What's more, in `awk' any number or even a string may be used as an
-array index.
-
-In most other languages, you have to "declare" an array and specify
-how many elements or components it has. In such languages, the
-declaration causes a contiguous block of memory to be allocated for
-that many elements. An index in the array must be a positive
-integer; for example, the index 0 specifies the first element in the
-array, which is 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, `"foo"', `""' and 30:
-
- +--------+--------+-------+--------+
- | 8 | "foo" | "" | 30 | value
- +--------+--------+-------+--------+
- 0 1 2 3 index
-
-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.
-
-Arrays in `awk' are different: they are "associative". This means
-that each array is a collection of pairs: an index, and its
-corresponding array element value:
-
- Element 4 Value 30
- Element 2 Value "foo"
- Element 1 Value 8
- Element 3 Value ""
-
-We have shown the pairs in jumbled order because their order doesn't
-mean anything.
-
-One advantage of an associative array is that new pairs can be added
-at any time. For example, suppose we add to that array a tenth
-element whose value is `"number ten"'. The result is this:
-
- Element 10 Value "number ten"
- Element 4 Value 30
- Element 2 Value "foo"
- Element 1 Value 8
- Element 3 Value ""
-
-Now the array is "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.
-
-Another consequence of associative arrays is that the indices don't
-have to be positive integers. Any number, or even a string, can be
-an index. For example, here is an array which translates words from
-English into French:
-
- Element "dog" Value "chien"
- Element "cat" Value "chat"
- Element "one" Value "un"
- Element 1 Value "un"
-
-Here we decided to translate the number 1 in both spelled--out and
-numeral form--thus illustrating that a single array can have both
-numbers and strings as indices.
-
-When `awk' creates an array for you, e.g. with the `split' built--in
-function (*note String Functions::.), that array's indices start at
-the number one.
-
-
-
-File: gawk-info, Node: Reference to Elements, Next: Assigning Elements, Prev: Array Intro, Up: Arrays
-
-Referring to an Array Element
-=============================
-
-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:
-
- ARRAY[INDEX]
-
-Here ARRAY is the name of an array. The expression 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.
-
-For example, `foo[4.3]' is an expression for the element of array
-`foo' at index 4.3.
-
-If you refer to an array element that has no recorded value, the
-value of the reference is `""', the null string. This includes
-elements to which you have not assigned any value, and elements that
-have been deleted (*note 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
-`awk').
-
-You can find out if an element exists in an array at a certain index
-with the expression:
-
- INDEX in ARRAY
-
-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 `ARRAY[SUBSCRIPT]' exists,
-and 0 (false) if it does not exist.
-
-For example, to find out whether the array `frequencies' contains the
-subscript `"2"', you would ask:
-
- if ("2" in frequencies) print "Subscript \"2\" is present."
-
-Note that this is *not* a test of whether or not the array
-`frequencies' contains an element whose *value* is `"2"'. (There is
-no way to that except to scan all the elements.) Also, this *does
-not* create `frequencies["2"]', while the following (incorrect)
-alternative would:
-
- if (frequencies["2"] != "") print "Subscript \"2\" is present."
-
-
-
-File: gawk-info, Node: Assigning Elements, Next: Array Example, Prev: Reference to Elements, Up: Arrays
-
-Assigning Array Elements
-========================
-
-Array elements are lvalues: they can be assigned values just like
-`awk' variables:
-
- ARRAY[SUBSCRIPT] = VALUE
-
-Here ARRAY is the name of your array. The expression SUBSCRIPT is
-the index of the element of the array that you want to assign a
-value. The expression VALUE is the value you are assigning to that
-element of the array.
-
-
-
-File: gawk-info, Node: Array Example, Next: Scanning an Array, Prev: Assigning Elements, Up: Arrays
-
-Basic Example of an Array
-=========================
-
-The following program takes a list of lines, each beginning with a
-line 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 numbers, gaps, or lines that
-don't begin with a number.
-
- BEGIN {
- max=0
- }
-
- {
- if ($1 > max)
- max = $1
- arr[$1] = $0
- }
-
- END {
- for (x = 1; x <= max; x++)
- print arr[x]
- }
-
-The first rule just initializes the variable `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.)
-
-The second rule keeps track of the largest line number seen so far;
-it also stores each line into the array `arr', at an index that is
-the line's number.
-
-The third rule runs after all the input has been read, to print out
-all the lines.
-
-When this program is run with the following input:
-
- 5 I am the Five man
- 2 Who are you? The new number two!
- 4 . . . And four on the floor
- 1 Who is number one?
- 3 I three you.
-
- its output is this:
-
- 1 Who is number one?
- 2 Who are you? The new number two!
- 3 I three you.
- 4 . . . And four on the floor
- 5 I am the Five man
-
-
-
-File: gawk-info, Node: Scanning an Array, Next: Delete, Prev: Array Example, Up: Arrays
-
-Scanning All Elements of an Array
-=================================
-
-In programs that use arrays, often you need a loop that will execute
-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 find all the valid indices by counting from zero up to that
-value. This technique won't do the job in `awk', since any number or
-string may be an array index. So `awk' has a special kind of `for'
-statement for scanning an array:
-
- for (VAR in ARRAY)
- BODY
-
-This loop executes BODY once for each different value that your
-program has previously used as an index in ARRAY, with the variable
-VAR set to that index.
-
-Here is a program that uses this form of the `for' statement. The
-first rule scans the input records and notes which words appear (at
-least once) in the input, by storing a 1 into the array `used' with
-the word as index. The second rule scans the elements of `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. *Note Built-in::, for more information on the
-built--in function `length'.
-
- # Record a 1 for each word that is used at least once.
- {
- for (i = 0; i < NF; i++)
- used[$i] = 1
- }
-
- # Find number of distinct words more than 10 characters long.
- END {
- num_long_words = 0
- for (x in used)
- if (length(x) > 10) {
- ++num_long_words
- print x
- }
- print num_long_words, "words longer than 10 characters"
- }
-
-*Note Sample Program::, for a more detailed example of this type.
-
-The order in which elements of the array are accessed by this
-statement is determined by the internal arrangement of the array
-elements within `awk' and cannot be controlled or changed. This can
-lead to problems if new elements are added to ARRAY by statements in
-BODY; you cannot predict whether or not the `for' loop will reach
-them. Similarly, changing VAR inside the loop can produce strange
-results. It is best to avoid such things.
-
-
-
-File: gawk-info, Node: Delete, Next: Multi-dimensional, Prev: Scanning an Array, Up: Arrays
-
-The `delete' Statement
-======================
-
-You can remove an individual element of an array using the `delete'
-statement:
-
- delete ARRAY[INDEX]
-
-When an array element is deleted, it is as if you had never referred
-to it and had never given it any value. Any value the element
-formerly had can no longer be obtained.
-
-Here is an example of deleting elements in an array:
-
- awk '{ for (i in frequencies)
- delete frequencies[i]
- }'
-
-This example removes all the elements from the array `frequencies'.
-
-If you delete an element, the `for' statement to scan the array will
-not report that element, and the `in' operator to check for the
-presence of that element will return 0:
-
- delete foo[4]
- if (4 in foo)
- print "This will never be printed"
-
-
-
-File: gawk-info, Node: Multi-dimensional, Next: Multi-scanning, Prev: Delete, Up: Arrays
-
-Multi--dimensional arrays
-=========================
-
-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 languages, including `awk') to refer to an element of a
-two--dimensional array named `grid' is with `grid[x,y]'.
-
-Multi--dimensional arrays are supported in `awk' through
-concatenation of indices into one string. What happens is that `awk'
-converts the indices into strings (*note 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 variable `SUBSEP'.
-
-For example, suppose the value of `SUBSEP' is `","' and the
-expression `foo[5,12]="value"' is executed. The numbers 5 and 12
-will be concatenated with a comma between them, yielding `"5,12"';
-thus, the array element `foo["5,12"]' will be set to `"value"'.
-
-Once the element's value is stored, `awk' has no record of whether it
-was stored with a single index or a sequence of indices. The two
-expressions `foo[5,12]' and `foo[5 SUBSEP 12]' always have the same
-value.
-
-The default value of `SUBSEP' is not a comma; it is the string
-`"\034"', which contains a nonprinting character that is unlikely to
-appear in an `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 `SUBSEP' lead to
-combined strings that are ambiguous. Suppose that `SUBSEP' is a
-comma; then `foo["a,b", "c"]' and `foo["a", "b,c"]' will be
-indistinguishable because both are actually stored as `foo["a,b,c"]'.
-Because `SUBSEP' is `"\034"', such confusion can actually happen only
-when an index contains the character `"\034"', which is a rare event.
-
-You can test whether a particular index--sequence exists in a
-``multi--dimensional'' array with the same operator `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:
-
- (SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY
-
-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.
-
- awk 'BEGIN {
- max_nf = max_nr = 0
- }
-
- {
- if (max_nf < NF)
- max_nf = NF
- max_nr = NR
- for (x = 1; x <= NF; x++)
- vector[x, NR] = $x
- }
-
- END {
- for (x = 1; x <= max_nf; x++) {
- for (y = max_nr; y >= 1; --y)
- printf("%s ", vector[x, y])
- printf("\n")
- }
- }'
-
-When given the input:
-
- 1 2 3 4 5 6
- 2 3 4 5 6 1
- 3 4 5 6 1 2
- 4 5 6 1 2 3
-
-it produces:
-
- 4 3 2 1
- 5 4 3 2
- 6 5 4 3
- 1 6 5 4
- 2 1 6 5
- 3 2 1 6
-
-
-
-File: gawk-info, Node: Multi-scanning, Prev: Multi-dimensional, Up: Arrays
-
-Scanning Multi--dimensional Arrays
-==================================
-
-There is no special `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 *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 the scanning `for' statement (*note Scanning an Array::.)
-with the `split' built--in function (*note String Functions::.). It
-works like this:
-
- for (combined in ARRAY) {
- split (combined, separate, SUBSEP)
- ...
- }
-
-This finds each concatenated, combined index in the array, and splits
-it into the individual indices by breaking it apart where the value
-of `SUBSEP' appears. The split--out indices become the elements of
-the array `separate'.
-
-Thus, suppose you have previously stored in `ARRAY[1, "foo"]'; then
-an element with index `"1\034foo"' exists in ARRAY. (Recall that the
-default value of `SUBSEP' contains the character with code 034.)
-Sooner or later the `for' statement will find that index and do an
-iteration with `combined' set to `"1\034foo"'. Then the `split'
-function will be called as follows:
-
- split ("1\034foo", separate, "\034")
-
-The result of this is to set `separate[1]' to 1 and `separate[2]' to
-`"foo"'. Presto, the original sequence of separate indices has been
-recovered.
-
-
-
-File: gawk-info, Node: Built-in, Next: User-defined, Prev: Arrays, Up: Top
-
-Built--in functions
-*******************
-
-"Built--in" functions are functions always available for your `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 new
-functions yourself. *Note 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:
-
- i = 4
- j = myfunc(i++)
-
-the variable `i' will be set to 5 before `myfunc' is called with a
-value of 4 for its actual parameter.
-
-* Menu:
-
-* Numeric Functions:: Functions that work with numbers,
- including `int', `sin' and `rand'.
-
-* String Functions:: Functions for string manipulation,
- such as `split', `match', and `sprintf'.
-
-* I/O Functions:: Functions for files and shell commands
-
-
-
-File: gawk-info, Node: Numeric Functions, Next: String Functions, Up: Built-in
-
-Numeric Built--in Functions
-===========================
-
-The general syntax of the numeric built--in functions is the same for
-each. Here is an example of that syntax:
-
- 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)) }'
-
-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.
-
-Here is the full list of numeric built--in functions:
-
-`int(X)'
- This gives you the integer part of X, truncated toward 0. This
- produces the nearest integer to X, located between X and 0.
-
- For example, `int(3)' is 3, `int(3.9)' is 3, `int(-3.9)' is -3,
- and `int(-3)' is -3 as well.
-
-`sqrt(X)'
- This gives you the positive square root of X. It reports an
- error if X is negative.
-
-`exp(X)'
- This gives you the exponential of X, or reports an error if X is
- out of range. The range of values X can have depends on your
- machine's floating point representation.
-
-`log(X)'
- This gives you the natural logarithm of X, if X is positive;
- otherwise, it reports an error.
-
-`sin(X)'
- This gives you the sine of X, with X in radians.
-
-`cos(X)'
- This gives you the cosine of X, with X in radians.
-
-`atan2(Y, X)'
- This gives you the arctangent of Y/X, with both in radians.
-
-`rand()'
- This gives you a random number. The values of `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 you can use to obtain a random nonnegative integer less
- than N:
-
- function randint(n) {
- return int(n * rand())
- }
-
- The multiplication produces a random real number at least 0, and
- less than N. We then make it an integer (using `int') between 0
- and `N-1'.
-
- Here is an example where a similar function is used to produce
- random integers between 1 and N:
-
- 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.
- {
- printf("%d points\n", roll(6)+roll(6)+roll(6))
- }'
-
- *Note* that `rand()' starts generating numbers from the same
- point, or "seed", each time you run `awk'. This means that the
- same program will produce the same results each time you run it.
- The numbers are random within one `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 the seed to a value that will be different in each
- run. To do this, use `srand'.
-
-`srand(X)'
- The function `srand(X)' sets the starting point, or "seed", for
- generating random numbers to the value X.
-
- Each seed value leads to a particular sequence of ``random''
- numbers. Thus, if you set the seed to the same value a second
- time, you will get the same sequence of ``random'' numbers again.
-
- If you omit the argument X, as in `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 `srand()' is the previous seed. This makes
- it easy to keep track of the seeds for use in consistently
- reproducing sequences of random numbers.
-
-
-
-File: gawk-info, Node: String Functions, Next: I/O Functions, Prev: Numeric Functions, Up: Built-in
-
-Built--in Functions for String Manipulation
-===========================================
-
-`index(IN, FIND)'
- This searches the string IN for the first occurrence of the
- string FIND, and returns the position where that occurrence
- begins in the string IN. For example:
-
- awk 'BEGIN { print index("peanut", "an") }'
-
- prints `3'. If FIND is not found, `index' returns 0.
-
-`length(STRING)'
- This gives you the number of characters in STRING. If STRING is
- a number, the length of the digit string representing that
- number is returned. For example, `length("abcde")' is 5.
- Whereas, `length(15 * 35)' works out to 3. How? Well, 15 * 35
- = 525, and 525 is then converted to the string `"525"', which
- has three characters.
-
-`match(STRING, REGEXP)'
- The `match' function searches the string, STRING, for the
- longest, leftmost substring matched by the regular expression,
- REGEXP. It returns the character position, or "index", of where
- that substring begins (1, if it starts at the beginning of
- STRING). If no match if found, it returns 0.
-
- The `match' function sets the special variable `RSTART' to the
- index. It also sets the special variable `RLENGTH' to the
- length of the matched substring. If no match is found, `RSTART'
- is set to 0, and `RLENGTH' to -1.
-
- For example:
-
- awk '{
- if ($1 == "FIND")
- regex = $2
- else {
- where = match($0, regex)
- if (where)
- print "Match of", regex, "found at", where, "in", $0
- }
- }'
-
- This program looks for lines that match the regular expression
- stored in the variable `regex'. This regular expression can be
- changed. If the first word on a line is `FIND', `regex' is
- changed to be the second word on that line. Therefore, given:
-
- FIND fo*bar
- My program was a foobar
- 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.
-
- `awk' prints:
-
- 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.
-
-`split(STRING, ARRAY, FIELD_SEPARATOR)'
- This divides STRING up into pieces separated by FIELD_SEPARATOR,
- and stores the pieces in ARRAY. The first piece is stored in
- `ARRAY[1]', the second piece in `ARRAY[2]', and so forth. The
- string value of the third argument, FIELD_SEPARATOR, is used as
- a regexp to search for to find the places to split STRING. If
- the FIELD_SEPARATOR is omitted, the value of `FS' is used.
- `split' returns the number of elements created.
-
- The `split' function, then, splits strings into pieces in a
- manner similar to the way input lines are split into fields.
- For example:
-
- split("auto-da-fe", a, "-")
-
- splits the string `auto-da-fe' into three fields using `-' as
- the separator. It sets the contents of the array `a' as follows:
-
- a[1] = "auto"
- a[2] = "da"
- a[3] = "fe"
-
- The value returned by this call to `split' is 3.
-
-`sprintf(FORMAT, EXPRESSION1,...)'
- This returns (without printing) the string that `printf' would
- have printed out with the same arguments (*note Printf::.). For
- example:
-
- sprintf("pi = %.2f (approx.)", 22/7)
-
- returns the string `"pi = 3.14 (approx.)"'.
-
-`sub(REGEXP, REPLACEMENT_STRING, TARGET_VARIABLE)'
- The `sub' function alters the value of TARGET_VARIABLE. It
- searches this value, which should be a string, for the leftmost
- substring matched by the regular expression, REGEXP, extending
- this match as far as possible. Then the entire string is
- changed by replacing the matched text with REPLACEMENT_STRING.
- The modified string becomes the new value of TARGET_VARIABLE.
-
- This function is peculiar because TARGET_VARIABLE 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 `sub' can
- store a modified value there. If this argument is omitted, then
- the default is to use and alter `$0'.
-
- For example:
-
- str = "water, water, everywhere"
- sub(/at/, "ith", str)
-
- sets `str' to `"wither, water, everywhere"', by replacing the
- leftmost, longest occurrence of `at' with `ith'.
-
- The `sub' function returns the number of substitutions made
- (either one or zero).
-
- The special character, `&', in the replacement string,
- REPLACEMENT_STRING, stands for the precise substring that was
- matched by REGEXP. (If the regexp can match more than one
- string, then this precise substring may vary.) For example:
-
- awk '{ sub(/candidate/, "& and his wife"); print }'
-
- will change the first occurrence of ``candidate'' to ``candidate
- and his wife'' on each input line.
-
- The effect of this special character can be turned off by
- preceding it with a backslash (`\&'). To include a backslash in
- the replacement string, it too must be preceded with a (second)
- backslash.
-
- Note: if you use `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:
-
- sub(/USA/, "United States", "the USA and Canada")
-
- will indeed produce a string `"the United States and Canada"',
- but there will be no way to use that string!
-
-`gsub(REGEXP, REPLACEMENT_STRING, TARGET_VARIABLE)'
- This is similar to the `sub' function, except `gsub' replaces
- *all* of the longest, leftmost, *non--overlapping* matching
- substrings it can find. The ``g'' in `gsub' stands for
- "global", which means replace *everywhere*. For example:
-
- awk '{ gsub(/Britain/, "United Kingdom"); print }'
-
- replaces all occurrences of the string `Britain' with `United
- Kingdom' for all input records.
-
- The `gsub' function returns the number of substitutions made.
- If the variable to be searched and altered, TARGET_VARIABLE, is
- omitted, then the entire input record, `$0', is used.
-
- The characters `&' and `\' are special in `gsub' as they are in
- `sub' (see immediately above).
-
-`substr(STRING, START, LENGTH)'
- This returns a LENGTH--character--long substring of STRING,
- starting at character number START. The first character of a
- string is character number one. For example,
- `substr("washington", 5, 3)' returns `"ing"'.
-
- If LENGTH is not present, this function returns the whole suffix
- of STRING that begins at character number START. For example,
- `substr("washington", 5)' returns `"ington"'.
-
-
-
-File: gawk-info, Node: I/O Functions, Prev: String Functions, Up: Built-in
-
-Built--in Functions for I/O to Files and Commands
-=================================================
-
-`close(FILENAME)'
- Close the file FILENAME. The argument may alternatively be a
- shell command that was used for redirecting to or from a pipe;
- then the pipe is closed.
-
- *Note Close Input::, regarding closing input files and pipes.
- *Note Close Output::, regarding closing output files and pipes.
-
-`system(COMMAND)'
- The system function allows the user to execute operating system
- commands and then return to the `awk' program. The `system'
- function executes the command given by the string value of
- COMMAND. It returns, as its value, the status returned by the
- command that was executed. This is known as returning the "exit
- status".
-
- For example, if the following fragment of code is put in your
- `awk' program:
-
- END {
- system("mail -s 'awk run done' operator < /dev/null")
- }
-
- the system operator will be sent mail when the `awk' program
- finishes processing input and begins its end--of--input
- processing.
-
- Note that much the same result can be obtained by redirecting
- `print' or `printf' into a pipe. However, if your `awk' program
- is interactive, this function is useful for cranking up large
- self--contained programs, such as a shell or an editor.
-
-
-
-File: gawk-info, Node: User-defined, Next: Special, Prev: Built-in, Up: Top
-
-User--defined Functions
-***********************
-
-Complicated `awk' programs can often be simplified by defining your
-own functions. User--defined functions can be called just like
-built--in ones (*note Function Calls::.), but it is up to you to
-define them--to tell `awk' what they should do.
-
-* Menu:
-
-* Definition Syntax:: How to write definitions and what they mean.
-* Function Example:: An example function definition and what it does.
-* Function Caveats:: Things to watch out for.
-* Return Statement:: Specifying the value a function returns.
-
-
-
-File: gawk-info, Node: Definition Syntax, Next: Function Example, Up: User-defined
-
-Syntax of Function Definitions
-==============================
-
-The definition of a function named NAME looks like this:
-
- function NAME (PARAMETER-LIST) {
- BODY-OF-FUNCTION
- }
-
-A valid function name is like a valid variable name: a sequence of
-letters, digits and underscores, not starting with a digit.
-
-Such function definitions can appear anywhere between the rules of
-the `awk' program. The general format of an `awk' program, then, is
-now modified to include sequences of rules *and* user--defined
-function definitions.
-
-The function definition need not precede all the uses of the function.
-This is because `awk' reads the entire program before starting to
-execute any of it.
-
-The PARAMETER-LIST is a list of the function's "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.
-
-The local variable values hide or "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 `awk' program can be
-referenced or set normally in the function definition.
-
-The local variables last only as long as the function is executing.
-Once the function finishes, the shadowed variables come back.
-
-The BODY-OF-FUNCTION part of the definition is the most important
-part, because this is what says what the function should actually *do*.
-The local variables exist to give the body a way to talk about the
-arguments.
-
-Functions may be "recursive", i.e., they can call themselves, either
-directly, or indirectly (via calling a second function that calls the
-first again).
-
-The keyword `function' may also be written `func'.
-
-
-
-File: gawk-info, Node: Function Example, Next: Function Caveats, Prev: Definition Syntax, Up: User-defined
-
-Function Definition Example
-===========================
-
-Here is an example of a user--defined function, called `myprint',
-that takes a number and prints it in a specific format.
-
- function myprint(num)
- {
- printf "%6.3g\n", num
- }
-
-To illustrate, let's use the following `awk' rule to use, or "call",
-our `myprint' function:
-
- $3 > 0 { myprint($3) }'
-
-This program prints, in our special format, all the third fields that
-contain a positive number in our input. Therefore, when given:
-
- 1.2 3.4 5.6 7.8
- 9.10 11.12 13.14 15.16
- 17.18 19.20 21.22 23.24
-
-this program, using our function to format the results, will print:
-
- 5.6
- 13.1
- 21.2
-
-Here is a rather contrived example of a recursive function. It
-prints a string backwards:
-
- function rev (str, len) {
- if (len == 0) {
- printf "\n"
- return
- }
- printf "%c", substr(str, len, 1)
- rev(str, len - 1)
- }
-
-
-
-File: gawk-info, Node: Function Caveats, Next: Return Statement, Prev: Function Example, Up: User-defined
-
-Caveats of Function Calling
-===========================
-
-*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 `awk' can tell you are not trying to concatenate the value
-of a variable with the value of an expression inside the parentheses.
-
-When a function is called, it is given a *copy* of the values of its
-arguments. This is called "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:
-
- foo = "bar"
- z = myfunc(foo)
-
-then you should not think of the argument to `myfunc' as being ``the
-variable `foo'''. Instead, think of the argument as the string
-value, `"bar"'.
-
-If the function `myfunc' alters the values of its local variables,
-this has no effect on any other variables. In particular, if
-`myfunc' does this:
-
- function myfunc (win) {
- print win
- win = "zzz"
- print win
- }
-
-to change its first argument variable `win', this *does not* change
-the value of `foo' in the caller. The role of `foo' in calling
-`myfunc' ended when its value, `"bar"', was computed. If `win' also
-exists outside of `myfunc', this definition will not change it--that
-value is shadowed during the execution of `myfunc' and cannot be seen
-or changed from there.
-
-However, when arrays are the parameters to functions, they are *not*
-copied. Instead, the array itself is made available for direct
-manipulation by the function. This is usually called "passing by
-reference". Changes made to an array parameter inside the body of a
-function *are* visible outside that function. *This can be very
-dangerous if you don't watch what you are doing.* For example:
-
- function changeit (array, ind, nvalue) {
- array[ind] = nvalue
- }
-
- BEGIN {
- a[1] = 1 ; a[2] = 2 ; a[3] = 3
- changeit(a, 2, "two")
- printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3]
- }
-
-will print `a[1] = 1, a[2] = two, a[3] = 3', because the call to
-`changeit' stores `"two"' in the second element of `a'.
-
-
-
-File: gawk-info, Node: Return Statement, Prev: Function Caveats, Up: User-defined
-
-The `return' statement
-======================
-
-The body of a user--defined function can contain a `return' statement.
-This statement returns control to the rest of the `awk' program. It
-can also be used to return a value for use in the rest of the `awk'
-program. It looks like:
-
- `return EXPRESSION'
-
-The EXPRESSION part is optional. If it is omitted, then the returned
-value is undefined and, therefore, unpredictable.
-
-A `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
-for the largest number among the elements of an array:
-
- function maxelt (vec, i, ret) {
- for (i in vec) {
- if (ret == "" || vec[i] > ret)
- ret = vec[i]
- }
- return ret
- }
-
-You call `maxelt' with one argument, an array name. The local
-variables `i' and `ret' are not intended to be arguments; while there
-is nothing to stop you from passing two or three arguments to
-`maxelt', the results would be strange.
-
-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 `maxelt'.
-
-Here is a program that uses, or calls, our `maxelt' function. This
-program loads an array, calls `maxelt', and then reports the maximum
-number in that array:
-
- awk '
- function maxelt (vec, i, ret) {
- for (i in vec) {
- if (ret == "" || vec[i] > ret)
- ret = vec[i]
- }
- return ret
- }
-
- # Load all fields of each record into nums.
- {
- for(i = 1; i <= NF; i++)
- nums[NR, i] = $i
- }
-
- END {
- print maxelt(nums)
- }'
-
-Given the following input:
-
- 1 5 23 8 16
- 44 3 5 2 8 26
- 256 291 1396 2962 100
- -6 467 998 1101
- 99385 11 0 225
-
-our program tells us (predictably) that:
-
- 99385
-
-is the largest number in our array.
-
-
-
-File: gawk-info, Node: Special, Next: Sample Program, Prev: User-defined, Up: Top
-
-Special Variables
-*****************
-
-Most `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.
-
-A few variables have special meanings. Some of them `awk' examines
-automatically, so that they enable you to tell `awk' how to do
-certain things. Others are set automatically by `awk', so that they
-carry information from the internal workings of `awk' to your program.
-
-Most of these variables are also documented in the chapters where
-their areas of activity are described.
-
-* Menu:
-
-* User-modified:: Special variables that you change to control `awk'.
-
-* Auto-set:: Special variables where `awk' gives you information.
-
-
-
-File: gawk-info, Node: User-modified, Next: Auto-set, Up: Special
-
-Special Variables That Control `awk'
-====================================
-
-This is a list of the variables which you can change to control how
-`awk' does certain things.
-
-`FS'
- `FS' is the input field separator (*note Field Separators::.).
- The value is a regular expression that matches the separations
- between fields in an input record.
-
- The default value is `" "', a string consisting of a single
- space. As a special exception, this value actually means that
- any sequence of spaces and tabs is a single separator. It also
- causes spaces and tabs at the beginning or end of a line to be
- ignored.
-
- You can set the value of `FS' on the command line using the `-F'
- option:
-
- awk -F, 'PROGRAM' INPUT-FILES
-
-`OFMT'
- This string is used by `awk' to control conversion of numbers to
- strings (*note Conversion::.). It works by being passed, in
- effect, as the first argument to the `sprintf' function. Its
- default value is `"%.6g"'.
-
-`OFS'
- This is the output field separator (*note Output Separators::.).
- It is output between the fields output by a `print' statement.
- Its default value is `" "', a string consisting of a single space.
-
-`ORS'
- This is the output record separator (*note Output
- Separators::.). It is output at the end of every `print'
- statement. Its default value is the newline character, often
- represented in `awk' programs as `\n'.
-
-`RS'
- This is `awk''s record separator (*note 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.
-
-`SUBSEP'
- `SUBSEP' is a subscript separator (*note Multi-dimensional::.).
- It has the default value of `"\034"', and is used to separate
- the parts of the name of a multi--dimensional array. Thus, if
- you access `foo[12,3]', it really accesses `foo["12\0343"]'.
-
-
-
-File: gawk-info, Node: Auto-set, Prev: User-modified, Up: Special
-
-Special Variables That Convey Information to You
-================================================
-
-This is a list of the variables that are set automatically by `awk'
-on certain occasions so as to provide information for your program.
-
-`ARGC'
-`ARGV'
- The command--line arguments available to `awk' are stored in an
- array called `ARGV'. `ARGC' is the number of command--line
- arguments present. `ARGV' is indexed from zero to `ARGC' - 1.
- For example:
-
- awk '{ print ARGV[$1] }' inventory-shipped BBS-list
-
- In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
- `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.
- `ARGC' is 3, one more than the index of the last element in
- `ARGV' since the elements are numbered from zero.
-
- Notice that the `awk' program is not treated as an argument.
- The `-f' `FILENAME' option, and the `-F' option, are also not
- treated as arguments for this purpose.
-
- Variable assignments on the command line *are* treated as
- arguments, and do show up in the `ARGV' array.
-
- Your program can alter `ARGC' the elements of `ARGV'. Each time
- `awk' reaches the end of an input file, it uses the next element
- of `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 `-' to represent the standard input. By
- storing additional elements and incrementing `ARGC' you can
- cause additional files to be read.
-
- If you decrease the value of `ARGC', that eliminates input files
- from the end of the list. By recording the old value of `ARGC'
- elsewhere, your program can treat the eliminated arguments as
- something other than file names.
-
- To eliminate a file from the middle of the list, store the null
- string (`""') into `ARGV' in place of the file's name. As a
- special feature, `awk' ignores file names that have been
- replaced with the null string.
-
-`ENVIRON'
- This is an array that contains the values of the environment.
- The array indices are the environment variable names; the values
- are the values of the particular environment variables. For
- example, `ENVIRON["HOME"]' might be `/u/close'. Changing this
- array does not affect the environment passed on to any programs
- that `awk' may spawn via redirection or the `system' function.
- (This may not work under operating systems other than MS-DOS,
- Unix, or GNU.)
-
-`FILENAME'
- This is the name of the file that `awk' is currently reading.
- If `awk' is reading from the standard input (in other words,
- there are no files listed on the command line), `FILENAME' is
- set to `"-"'. `FILENAME' is changed each time a new file is
- read (*note Reading Files::.).
-
-`FNR'
- `FNR' is the current record number in the current file. `FNR'
- is incremented each time a new record is read (*note Getline::.).
- It is reinitialized to 0 each time a new input file is started.
-
-`NF'
- `NF' is the number of fields in the current input record. `NF'
- is set each time a new record is read, when a new field is
- created, or when $0 changes (*note Fields::.).
-
-`NR'
- This is the number of input records `awk' has processed since
- the beginning of the program's execution. (*note Records::.).
- `NR' is set each time a new record is read.
-
-`RLENGTH'
- `RLENGTH' is the length of the string matched by the `match'
- function (*note String Functions::.). `RLENGTH' is set by
- invoking the `match' function. Its value is the length of the
- matched string, or -1 if no match was found.
-
-`RSTART'
- `RSTART' is the start of the string matched by the `match'
- function (*note String Functions::.). `RSTART' is set by
- invoking the `match' function. Its value is the position of the
- string where the matched string starts, or 0 if no match was
- found.
-
-
-
-File: gawk-info, Node: Sample Program, Next: Notes, Prev: Special, Up: Top
-
-Sample Program
-**************
-
-The following example is a complete `awk' program, which prints the
-number of occurrences of each word in its input. It illustrates the
-associative nature of `awk' arrays by using strings as subscripts.
-It also demonstrates the `for X in ARRAY' construction. Finally, it
-shows how `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.
-
- awk '
- # Print list of word frequencies
- {
- for (i = 1; i <= NF; i++)
- freq[$i]++
- }
-
- END {
- for (word in freq)
- printf "%s\t%d\n", word, freq[word]
- }'
-
-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 `awk''s field--accessing
-mechanism (*note Fields::.) to pick out the individual words from the
-line, and the special variable `NF' (*note Special::.) to know how
-many fields are available.
-
-For each input word, an element of the array `freq' is incremented to
-reflect that the word has been seen an additional time.
-
-The second rule, because it has the pattern `END', is not executed
-until the input has been exhausted. It prints out the contents of
-the `freq' table that has been built up inside the first action.
-
-Note that this program has several problems that would prevent it
-from being useful by itself on real text files:
-
- * Words are detected using the `awk' convention that fields are
- separated by whitespace and that other characters in the input
- (except newlines) don't have any special meaning to `awk'. This
- means that punctuation characters count as part of words.
-
- * The `awk' language considers upper and lower case characters to
- be distinct. Therefore, `foo' and `Foo' will not be 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.
-
- * The output does not come out in any useful order. You're more
- likely to be interested in which words occur most frequently, or
- having an alphabetized table of how frequently each word occurs.
-
-The way to solve these problems is to use other operating system
-utilities to process the input and output of the `awk' script.
-Suppose the script shown above is saved in the file `frequency.awk'.
-Then the shell command:
-
- tr A-Z a-z < file1 | tr -cd 'a-z\012' \
- | awk -f frequency.awk \
- | sort +1 -nr
-
-produces a table of the words appearing in `file1' in order of
-decreasing frequency.
-
-The first `tr' command in this pipeline translates all the upper case
-characters in `file1' to lower case. The second `tr' command deletes
-all the characters in the input except lower case characters and
-newlines. The second argument to the second `tr' is quoted to
-protect the backslash in it from being interpreted by the shell. The
-`awk' program reads this suitably massaged data and produces a word
-frequency table, which is not ordered.
-
-The `awk' script's output is now sorted by the `sort' command and
-printed on the terminal. The options given to `sort' in this example
-specify to sort by the second field of each input line (skipping one
-field), that the sort keys should be treated as numeric quantities
-(otherwise `15' would come before `5'), and that the sorting should
-be done in descending (reverse) order.
-
-See the general operating system documentation for more information
-on how to use the `tr' and `sort' commands.
-
-
-
-File: gawk-info, Node: Notes, Next: Glossary, Prev: Sample Program, Up: Top
-
-Implementation Notes
-********************
-
-This appendix contains information mainly of interest to implementors
-and maintainers of `gawk'. Everything in it applies specifically to
-`gawk', and not to other implementations.
-
-* Menu:
-
-* Extensions:: Things`gawk' does that Unix `awk' does not.
-
-* Future Extensions:: Things likely to appear in a future release.
-
-* Improvements:: Suggestions for future improvements.
-
-* Manual Improvements:: Suggestions for improvements to this manual.
-
-
-
-File: gawk-info, Node: Extensions, Next: Future Extensions, Up: Notes
-
-GNU Extensions to the AWK Language
-==================================
-
-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 `awk', too.
-
-All of these features can be turned off either by compiling `gawk'
-with `-DSTRICT', or by invoking `gawk' as `awk'.
-
-The `AWKPATH' environment variable
- When opening a file supplied via the `-f' option, if the
- filename does not contain a `/', `gawk' will perform a "path
- search" for the file, similar to that performed by the shell.
- `gawk' gets its search path from the `AWKPATH' environment
- variable. If that variable does not exist, it uses the default
- path `".:/usr/lib/awk:/usr/local/lib/awk"'.
-
-Case Independent Matching
- Two new operators have been introduced, `~~', and `!~~'. These
- perform regular expression match and no-match operations that
- are case independent. In other words, `A' and `a' would both
- match `/a/'.
-
-The `-i' option
- This option causes the `~' and `!~' operators to behave like the
- `~~' and `!~~' operators described above.
-
-The `-v' option
- This option prints version information for this particular copy
- of `gawk'. This is so you can determine if your copy of `gawk'
- is up to date with respect to whatever the Free Software
- Foundation is currently distributing. It may disappear in a
- future version of `gawk'.
-
-
-
-File: gawk-info, Node: Future Extensions, Next: Improvements, Prev: Extensions, Up: Notes
-
-Extensions Likely To Appear In A Future Release
-===============================================
-
-Here are some more extensions that indicate the directions we are
-currently considering for `gawk'. Like the previous section, this
-section is also subject to change. None of these are implemented yet.
-
-The `IGNORECASE' special variable
- If `IGNORECASE' is non--zero, then *all* regular expression
- matching will be done in a case--independent fashion. The `-i'
- option and the `~~' and `!~~' operators will go away, as this
- mechanism generalizes those facilities.
-
-More Escape Sequences
- The ANSI C `\a', and `\x' escape sequences will be recognized.
- Unix `awk' does not recognize `\v', although `gawk' does.
-
-`RS' as a regexp
- The meaning of `RS' will be generalized along the lines of `FS'.
-
-Transliteration Functions
- We are planning on adding `toupper' and `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.
-
-Access To System File Descriptors
- `gawk' will recognize the special file names `/dev/stdin',
- `/dev/stdout', `/dev/stderr', and `/dev/fd/N' internally. These
- will allow access to inherited file descriptors from within an
- `awk' program.
-
-
-
-File: gawk-info, Node: Improvements, Next: Manual Improvements, Prev: Future Extensions, Up: Notes
-
-Suggestions for Future Improvements
-===================================
-
-Here are some projects that would--be `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 project.
-
- 1. State machine regexp matcher: At present, `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 `egrep'.
-
- 2. Compilation of `awk' programs: `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.
-
- It should be possible for `gawk' to convert the script's parse
- tree into a C program which the user would then compile, using
- the normal C compiler and a special `gawk' library to provide
- all the needed functions (regexps, fields, associative arrays,
- type coercion, and so on).
-
- An easier possibility might be for an intermediate phase of
- `awk' to convert the parse tree into a linear byte code form
- like the one used 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 `gawk' does now.
-
-
-
-File: gawk-info, Node: Manual Improvements, Prev: Improvements, Up: Notes
-
-Suggestions For Future Improvements of This Manual
-==================================================
-
- 1. 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.
-
- 2. A summary page has not been included, as the ``man'', or help,
- page that comes with the `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.
-
- 3. A function and variable index has not been included as we are
- not sure what to put in it.
-
- 4. A section summarizing the differences between V7 `awk' and
- System V Release 4 `awk' would be useful for long--time `awk'
- hackers.
-
-
-
-File: gawk-info, Node: Glossary, Next: Index, Prev: Notes, Up: Top
-
-Glossary
-********
-
-Action
- A series of `awk' statements attached to a rule. If the rule's
- pattern matches an input record, the `awk' language executes the
- rule's action. Actions are always enclosed in curly braces.
-
-Amazing `awk' assembler
- Henry Spencer at the University of Toronto wrote a retargetable
- assembler completely as `awk' scripts. It is thousands of lines
- long, including machine descriptions for several 8--bit
- microcomputers. It is distributed with `gawk' and is a good
- example of a program that would have been better written in
- another language.
-
-Assignment
- An `awk' expression that changes the value of some `awk'
- variable or data object. An object that you can assign to is
- called an "lvalue".
-
-Built-in function
- The `awk' language provides built--in functions that perform
- various numerical and string computations. Examples are `sqrt'
- (for the square root of a number) and `substr' (for a substring
- of a string).
-
-C
- The system programming language that most of GNU is written in.
- The `awk' programming language has C--like syntax, and this
- manual points out similarities between `awk' and C when
- appropriate.
-
-Compound statement
- A series of `awk' statements, enclosed in curly braces.
- Compound statements may be nested.
-
-Concatenation
- Concatenating two strings means sticking them together, one
- after another, giving a new string. For example, the string
- `foo' concatenated with the string `bar' gives the string
- `foobar'.
-
-Conditional expression
- A relation that is either true or false, such as `(a < b)'.
- Conditional expressions are used in `if' and `while' statements,
- and in patterns to select which input records to process.
-
-Curly braces
- The characters `{' and `}'. Curly braces are used in `awk' for
- delimiting actions, compound statements, and function bodies.
-
-Data objects
- These are numbers and strings of characters. Numbers are
- converted into strings and vice versa, as needed.
-
-Escape Sequences
- A special sequence of characters used for describing
- non--printable characters, such as `\n' for newline, or `\033'
- for the ASCII ESC (escape) character.
-
-Field
- When `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 `FS'). Such
- pieces are called fields.
-
-Format
- Format strings are used to control the appearance of output in
- the `printf' statement. Also, data conversions from numbers to
- strings are controlled by the format string contained in the
- special variable `OFMT'.
-
-Function
- A specialized group of statements often used to encapsulate
- general or program--specific tasks. `awk' has a number of
- built--in functions, and also allows you to define your own.
-
-`gawk'
- The GNU implementation of `awk'.
-
-`awk' language
- The language in which `awk' programs are written.
-
-`awk' program
- An `awk' program consists of a series of "patterns" and
- "actions", collectively known as "rules". For each input record
- given to the program, the program's rules are all processed in
- turn. `awk' programs may also contain function definitions.
-
-`awk' script
- Another name for an `awk' program.
-
-Input record
- A single chunk of data read in by `awk'. Usually, an `awk'
- input record consists of one line of text.
-
-Keyword
- In the `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: `if', `else', `while', `do...while', `for',
- `for...in', `break', `continue', `delete', `next', `function',
- `func', and `exit'.
-
-Lvalue
- An expression that can appear on the left side of an assignment
- operator. In most languages, lvalues can be variables or array
- elements. In `awk', a field designator can also be used as an
- lvalue.
-
-Number
- A numeric valued data object. The `gawk' implementation uses
- double precision floating point to represent numbers.
-
-Pattern
- Patterns tell `awk' which input records are interesting to which
- rules.
-
- A pattern is an arbitrary conditional expression against which
- input is tested. If the condition is satisfied, the pattern is
- said to "match" the input record. A typical pattern might
- compare the input record against a regular expression.
-
-Range (of input lines)
- A sequence of consecutive lines from the input file. A pattern
- can specify ranges of input lines for `awk' to process, or it
- can specify single lines.
-
-Recursion
- When a function calls itself, either directly or indirectly. If
- this isn't clear, refer to the entry for ``recursion''.
-
-Redirection
- 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 `print' and `printf'
- statements to a file or a system command, using the `>', `>>',
- and `|' operators. You can redirect input to the `getline'
- statement using the `<' and `|' operators.
-
-Regular Expression
- See ``regexp''.
-
-Regexp
- Short for "regular expression". A regexp is a pattern that
- denotes a set of strings, possibly an infinite set. For
- example, the regexp `R.*xp' matches any string starting with the
- letter `R' and ending with the letters `xp'. In `awk', regexps
- are used in patterns and in conditional expressions.
-
-Rule
- A segment of an `awk' program, that specifies how to process
- single input records. A rule consists of a "pattern" and an
- "action". `awk' reads an input record; then, for each rule, if
- the input record satisfies the rule's pattern, `awk' executes
- the rule's action. Otherwise, the rule does nothing for that
- input record.
-
-Special Variable
- The variables `ARGC', `ARGV', `ENVIRON', `FILENAME', `FNR',
- `FS', `NF', `NR', `OFMT', `OFS', `ORS', `RLENGTH', `RSTART',
- `RS', `SUBSEP', have special meaning to `awk'. Changing some of
- them affects `awk''s running environment.
-
-Stream Editor
- A program that reads records from an input stream and processes
- them one or more at a time. This is in contrast with batch
- programs, which may expect to read their input files in entirety
- before starting to do anything, and with interactive programs,
- which require input from the user.
-
-String
- A datum consisting of a sequence of characters, such as `I am a
- string'. Constant strings are written with double--quotes in
- the `awk' language, and may contain "escape sequences".
-
-Whitespace
- A sequence of blank or tab characters occurring inside an input
- record or a string.
-
-
-
-File: gawk-info, Node: Index, Prev: Glossary, Up: Top
-
-Index
-*****
-
-* Menu:
-
-* #!: Executable Scripts.
-* -f option: Long.
-* `$NF', last field in record: Fields.
-* `$' (field operator): Fields.
-* `>>': Redirection.
-* `>': Redirection.
-* `BEGIN', special pattern: BEGIN/END.
-* `END', special pattern: BEGIN/END.
-* `awk' language: This Manual.
-* `awk' program: This Manual.
-* `break' statement: Break.
-* `close' statement for input: Close Input.
-* `close' statement for output: Close Output.
-* `continue' statement: Continue.
-* `delete' statement: Delete.
-* `exit' statement: Exit.
-* `for (x in ...)': Scanning an Array.
-* `for' statement: For.
-* `if' statement: If.
-* `next' statement: Next.
-* `print $0': Very Simple.
-* `printf' statement, format of: Basic Printf.
-* `printf', format-control characters: Format-Control.
-* `printf', modifiers: Modifiers.
-* `print' statement: Print.
-* `return' statement: Return Statement.
-* `while' statement: While.
-* `|': Redirection.
-* `BBS-list' file: The Files.
-* `inventory-shipped' file: The Files.
-* Accessing fields: Fields.
-* Acronym: History.
-* Action, curly braces: Actions.
-* Action, curly braces: Getting Started.
-* Action, default: Very Simple.
-* Action, definition of: Getting Started.
-* Action, general: Actions.
-* Action, separating statements: Actions.
-* Applications of `awk': When.
-* Arguments in function call: Function Calls.
-* Arguments, Command Line: Command Line.
-* Arithmetic operators: Arithmetic Ops.
-* Array assignment: Assigning Elements.
-* Array reference: Reference to Elements.
-* Arrays: Array Intro.
-* Arrays, definition of: Array Intro.
-* Arrays, deleting an element: Delete.
-* Arrays, determining presence of elements: Reference to Elements.
-* Arrays, multi-dimensional subscripts: Multi-dimensional.
-* Arrays, special `for' statement: Scanning an Array.
-* Assignment operators: Assignment Ops.
-* Associative arrays: Array Intro.
-* Backslash Continuation: Statements/Lines.
-* Basic function of `gawk': Getting Started.
-* Body of a loop: While.
-* Boolean expressions: Boolean Ops.
-* Boolean operators: Boolean Ops.
-* Boolean patterns: Boolean.
-* Built-in functions, list of: Built-in.
-* Built-in variables: Variables.
-* Calling a function: Function Calls.
-* Case sensitivity and gawk: Read Terminal.
-* Changing contents of a field: Changing Fields.
-* Changing the record separator: Records.
-* Closing files and pipes: Close Output.
-* Command Line: Command Line.
-* Command line formats: Running gawk.
-* Command line, setting `FS' on: Field Separators.
-* Comments: Comments.
-* Comparison expressions: Comparison Ops.
-* Comparison expressions as patterns: Comparison Patterns.
-* Compound statements: Actions.
-* Computed Regular Expressions: Regexp Usage.
-* Concatenation: Concatenation.
-* Conditional Patterns: Conditional Patterns.
-* Conditional expression: Conditional Exp.
-* Constants, types of: Constants.
-* Continuing statements on the next line: Statements/Lines.
-* Conversion of strings and numbers: Conversion.
-* Curly braces: Actions.
-* Curly braces: Getting Started.
-* Default action: Very Simple.
-* Default pattern: Very Simple.
-* Deleting elements of arrays: Delete.
-* Differences between `gawk' and `awk': Arithmetic Ops.
-* Differences between `gawk' and `awk': Constants.
-* Documenting `awk' programs: Comments.
-* Dynamic Regular Expressions: Regexp Usage.
-* Element assignment: Assigning Elements.
-* Element of array: Reference to Elements.
-* Emacs Lisp: When.
-* Empty pattern: Empty.
-* Escape sequence notation: Constants.
-* Examining fields: Fields.
-* Executable Scripts: Executable Scripts.
-* Expression, conditional: Conditional Exp.
-* Expressions: Actions.
-* Expressions, boolean: Boolean Ops.
-* Expressions, comparison: Comparison Ops.
-* Field separator, `FS': Field Separators.
-* Field separator, choice of: Field Separators.
-* Field separator, setting on command line: Field Separators.
-* Field, changing contents of: Changing Fields.
-* Fields: Fields.
-* Fields, negative-numbered: Non-Constant Fields.
-* Fields, semantics of: Field Separators.
-* Fields, separating: Field Separators.
-* Format specifier: Format-Control.
-* Format string: Basic Printf.
-* Formatted output: Printf.
-* Function call: Function Calls.
-* Function definitions: Actions.
-* Functions, user-defined: User-defined.
-* General input: Reading Files.
-* History of `awk': History.
-* How gawk works: Two Rules.
-* Increment operators: Increment Ops.
-* Input file, sample: The Files.
-* Input, `getline' function: Getline.
-* Input, general: Reading Files.
-* Input, multiple line records: Multiple.
-* Input, standard: Read Terminal.
-* Input, standard: Reading Files.
-* Interaction of `awk' with other programs: I/O Functions.
-* Invocation of `gawk': Command Line.
-* Language, `awk': This Manual.
-* Loop: While.
-* Loops, breaking out of: Break.
-* Lvalue: Assignment Ops.
-* Manual, using this: This Manual.
-* Metacharacters: Regexp Operators.
-* Mod function, semantics of: Arithmetic Ops.
-* Modifiers (in format specifiers): Modifiers.
-* Multiple line records: Multiple.
-* Multiple passes over data: Command Line.
-* Multiple statements on one line: Statements/Lines.
-* Negative-numbered fields: Non-Constant Fields.
-* Number of fields, `NF': Fields.
-* Number of records, `FNR': Records.
-* Number of records, `NR': Records.
-* Numerical constant: Constants.
-* Numerical value: Constants.
-* One-liners: One-liners.
-* Operator, Ternary: Conditional Patterns.
-* Operators, `$': Fields.
-* Operators, arithmetic: Arithmetic Ops.
-* Operators, assignment: Assignment Ops.
-* Operators, boolean: Boolean Ops.
-* Operators, increment: Increment Ops.
-* Operators, regular expression matching: Regexp Usage.
-* Operators, relational: Comparison Ops.
-* Operators, relational: Comparison Patterns.
-* Operators, string: Concatenation.
-* Operators, string-matching: Regexp Usage.
-* Options, Command Line: Command Line.
-* Output: Printing.
-* Output field separator, `OFS': Output Separators.
-* Output record separator, `ORS': Output Separators.
-* Output redirection: Redirection.
-* Output, formatted: Printf.
-* Output, piping: Redirection.
-* Passes, Multiple: Command Line.
-* Pattern, case sensitive: Read Terminal.
-* Pattern, comparison expressions: Comparison Patterns.
-* Pattern, default: Very Simple.
-* Pattern, definition of: Getting Started.
-* Pattern, empty: Empty.
-* Pattern, regular expressions: Regexp.
-* Patterns, `BEGIN': BEGIN/END.
-* Patterns, `END': BEGIN/END.
-* Patterns, Conditional: Conditional Patterns.
-* Patterns, boolean: Boolean.
-* Patterns, definition of: Patterns.
-* Patterns, types of: Patterns.
-* Pipes for output: Redirection.
-* Printing, general: Printing.
-* Program, `awk': This Manual.
-* Program, Self contained: Executable Scripts.
-* Program, definition of: Getting Started.
-* Programs, documenting: Comments.
-* Range pattern: Ranges.
-* Reading files, `getline' function: Getline.
-* Reading files, general: Reading Files.
-* Reading files, multiple line records: Multiple.
-* Record separator, `RS': Records.
-* Records, multiple line: Multiple.
-* Redirection of output: Redirection.
-* Reference to array: Reference to Elements.
-* Regexp: Regexp.
-* Regular Expressions, Computed: Regexp Usage.
-* Regular Expressions, Dynamic: Regexp Usage.
-* Regular expression matching operators: Regexp Usage.
-* Regular expression, metacharacters: Regexp Operators.
-* Regular expressions as patterns: Regexp.
-* Regular expressions, field separators and: Field Separators.
-* Relational operators: Comparison Patterns.
-* Relational operators: Comparison Ops.
-* Removing elements of arrays: Delete.
-* Rule, definition of: Getting Started.
-* Running gawk programs: Running gawk.
-* Sample input file: The Files.
-* Scanning an array: Scanning an Array.
-* Script, definition of: Getting Started.
-* Scripts, Executable: Executable Scripts.
-* Scripts, Shell: Executable Scripts.
-* Self contained Programs: Executable Scripts.
-* Separator character, choice of: Field Separators.
-* Shell Scripts: Executable Scripts.
-* Single quotes, why they are needed: One-shot.
-* Special variables, user modifiable: User-modified.
-* Standard input: Read Terminal.
-* Standard input: Reading Files.
-* Statements: Statements.
-* Statements: Actions.
-* String constants: Constants.
-* String operators: Concatenation.
-* String value: Constants.
-* String-matching operators: Regexp Usage.
-* Subscripts, multi-dimensional in arrays: Multi-dimensional.
-* Ternary Operator: Conditional Patterns.
-* Use of comments: Comments.
-* User-defined functions: User-defined.
-* User-defined variables: Variables.
-* Uses of `awk': Preface.
-* Using this manual: This Manual.
-* Variables, built-in: Variables.
-* Variables, user-defined: Variables.
-* What is `awk': Preface.
-* When to use `awk': When.
-* file, `awk' program: Long.
-* patterns, range: Ranges.
-* program file: Long.
-* regexp search operators: Regexp Usage.
-* running long programs: Long.
-
-
- 
-Tag Table:
-Node: Top918
-Node: Preface2804
-Node: History4267
-Node: License5644
-Node: This Manual18989
-Node: The Files20330
-Node: Getting Started22914
-Node: Very Simple24249
-Node: Two Rules26030
-Node: More Complex28066
-Node: Running gawk30908
-Node: One-shot31827
-Node: Read Terminal32945
-Node: Long33862
-Node: Executable Scripts34991
-Node: Command Line36534
-Node: Comments40168
-Node: Statements/Lines41067
-Node: When43498
-Node: Reading Files45420
-Node: Records47119
-Node: Fields49902
-Node: Non-Constant Fields52789
-Node: Changing Fields54591
-Node: Field Separators57302
-Node: Multiple62004
-Node: Assignment Options64393
-Node: Getline65608
-Node: Close Input74958
-Node: Printing76023
-Node: Print76748
-Node: Print Examples78712
-Node: Output Separators80751
-Node: Redirection82417
-Node: Close Output85886
-Node: Printf88132
-Node: Basic Printf88908
-Node: Format-Control90261
-Node: Modifiers91806
-Node: Printf Examples93108
-Node: One-liners95707
-Node: Patterns97642
-Node: Empty100130
-Node: Regexp100402
-Node: Regexp Usage101173
-Node: Regexp Operators102947
-Node: Comparison Patterns107890
-Node: Ranges109336
-Node: BEGIN/END110722
-Node: Boolean113151
-Node: Conditional Patterns115605
-Node: Actions116105
-Node: Expressions117435
-Node: Constants119124
-Node: Variables121097
-Node: Arithmetic Ops122454
-Node: Concatenation123840
-Node: Comparison Ops124569
-Node: Boolean Ops125973
-Node: Assignment Ops128266
-Node: Increment Ops131817
-Node: Conversion134112
-Node: Conditional Exp136066
-Node: Function Calls137384
-Node: Statements139939
-Node: If141253
-Node: While142627
-Node: Do144232
-Node: For145265
-Node: Break148306
-Node: Continue149848
-Node: Next151476
-Node: Exit152985
-Node: Arrays154514
-Node: Array Intro155624
-Node: Reference to Elements159227
-Node: Assigning Elements161115
-Node: Array Example161615
-Node: Scanning an Array163336
-Node: Delete165642
-Node: Multi-dimensional166529
-Node: Multi-scanning169746
-Node: Built-in171303
-Node: Numeric Functions172806
-Node: String Functions176601
-Node: I/O Functions183717
-Node: User-defined185189
-Node: Definition Syntax185834
-Node: Function Example187928
-Node: Function Caveats189034
-Node: Return Statement191386
-Node: Special193612
-Node: User-modified194478
-Node: Auto-set196511
-Node: Sample Program200558
-Node: Notes204316
-Node: Extensions204909
-Node: Future Extensions206490
-Node: Improvements207922
-Node: Manual Improvements210034
-Node: Glossary210928
-Node: Index217934
-
-End Tag Table
diff --git a/gawk-info-1 b/gawk-info-1
deleted file mode 100644
index b40278a4..00000000
--- a/gawk-info-1
+++ /dev/null
@@ -1,1231 +0,0 @@
-Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
-file gawk.texinfo.
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them.
-
-Copyright (C) 1989 Free Software Foundation, Inc.
-
-Permission is granted to make and distribute verbatim copies of this
-manual provided the copyright notice and this permission notice are
-preserved on all copies.
-
-Permission is granted to copy and distribute modified versions of
-this manual under the conditions for verbatim copying, provided that
-the entire resulting derived work is distributed under the terms of a
-permission notice identical to this one.
-
-Permission is granted to copy and distribute translations of this
-manual into another language, under the above conditions for modified
-versions, except that this permission notice may be stated in a
-translation approved by the Foundation.
-
-
-
-File: gawk-info, Node: Top, Next: Preface, Prev: (dir), Up: (dir)
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them; it
-contains the following chapters:
-
-* Menu:
-
-* Preface:: What you can do with `awk'; brief history
- and acknowledgements.
-
-* License:: Your right to copy and distribute `gawk'.
-
-* This Manual:: Using this manual.
-
- Includes sample input files that you can use.
-
-* Getting Started:: A basic introduction to using `awk'.
- How to run an `awk' program. Command line syntax.
-
-* Reading Files:: How to read files and manipulate fields.
-
-* Printing:: How to print using `awk'. Describes the
- `print' and `printf' statements.
- Also describes redirection of output.
-
-* One-liners:: Short, sample `awk' programs.
-
-* Patterns:: The various types of patterns explained in detail.
-
-* Actions:: The various types of actions are introduced here.
- Describes expressions and the various operators in
- detail. Also describes comparison expressions.
-
-* Statements:: The various control statements are described in
- detail.
-
-* Arrays:: The description and use of arrays. Also includes
- array--oriented control statements.
-
-* User-defined:: User--defined functions are described in detail.
-
-* Built-in:: The built--in functions are summarized here.
-
-* Special:: The special variables are summarized here.
-
-* Sample Program:: A sample `awk' program with a complete explanation.
-
-* Notes:: Something about the implementation of `gawk'.
-
-* Glossary:: An explanation of some unfamiliar terms.
-
-* Index::
-
-
-
-File: gawk-info, Node: Preface, Next: License, Prev: Top, Up: Top
-
-Preface
-*******
-
-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 may be easier with `awk'.
-
-The `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 `awk' is called `gawk'; it is fully upward
-compatible with the System V Release 3.1 and later version of `awk'.
-All properly written `awk' programs should work with `gawk'. So we
-usually don't distinguish between `gawk' and other `awk'
-implementations in this manual.
-
-This manual teaches you what `awk' does and how you can use `awk'
-effectively. You should already be familiar with basic,
-general--purpose, operating system commands such as `ls'. Using
-`awk' you can:
-
- * manage small, personal databases,
-
- * generate reports,
-
- * validate data,
-
- * produce indexes, and perform other document preparation tasks,
-
- * even experiment with algorithms that can be adapted later to
- other computer languages!
-
-* Menu:
-
-* History:: The history of gawk and awk. Acknowledgements.
-
-
-
-File: gawk-info, Node: History, Up: Preface
-
-History of `awk' and `gawk'
-===========================
-
-The name `awk' comes from the initials of its designers: Alfred V.
-Aho, Peter J. Weinberger, and Brian W. Kernighan. The original
-version of `awk' was written in 1977. In 1985 a new version made the
-programming language more powerful, introducing user--defined
-functions, multiple input streams, and computed regular expressions.
-
-The GNU implementation, `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 `gawk' for compatibility with the
-newer `awk'.
-
-Many people need to be thanked for their assistance in producing this
-manual. Jay Fenlason contributed many ideas and sample programs.
-Richard Mlynarik and Robert Chassell gave helpful comments on drafts
-of this manual. The paper ``A Supplemental Document for `awk''' by
-John W. Pierce of the Chemistry Department at UC San Diego,
-pinpointed several issues relevant both to `awk' implementation and
-to this manual, that would otherwise have escaped us.
-
-Finally, we would like to thank Brian Kernighan of Bell Labs for
-invaluable assistance during the testing and debugging of `gawk', and
-for help in clarifying several points about the language.
-
-
-
-File: gawk-info, Node: License, Next: This Manual, Prev: Preface, Up: Top
-
-GNU GENERAL PUBLIC LICENSE
-**************************
-
- Version 1, February 1989
-
- Copyright (C) 1989 Free Software Foundation, Inc.
- 675 Mass Ave, Cambridge, MA 02139, USA
-
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-=========
-
- The license agreements of most software companies try to keep users
-at the mercy of those companies. By contrast, our General Public
-License is intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-The General Public License applies to the Free Software Foundation's
-software and to any other program whose authors commit to using it.
-You can use it for your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Specifically, the General Public License is designed to make
-sure that you have the freedom to give away or sell copies of free
-software, that you receive source code or can get it if you want it,
-that you can change the software or use pieces of it in new free
-programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if
-you distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of a such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must tell them their rights.
-
- We protect your rights with two steps: (1) copyright the software,
-and (2) offer you this license which gives you legal permission to
-copy, distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on,
-we want its recipients to know that what they have is not the
-original, so that any problems introduced by others will not reflect
-on the original authors' reputations.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 1. This License Agreement applies to any program or other work
- which contains a notice placed by the copyright holder saying it
- may be distributed under the terms of this General Public
- License. The ``Program'', below, refers to any such program or
- work, and a ``work based on the Program'' means either the
- Program or any work containing the Program or a portion of it,
- either verbatim or with modifications. Each licensee is
- addressed as ``you''.
-
- 2. You may copy and distribute verbatim copies of the Program's
- source code as you receive it, in any medium, provided that you
- conspicuously and appropriately publish on each copy an
- appropriate copyright notice and disclaimer of warranty; keep
- intact all the notices that refer to this General Public License
- and to the absence of any warranty; and give any other
- recipients of the Program a copy of this General Public License
- along with the Program. You may charge a fee for the physical
- act of transferring a copy.
-
- 3. You may modify your copy or copies of the Program or any portion
- of it, and copy and distribute such modifications under the
- terms of Paragraph 1 above, provided that you also do the
- following:
-
- * cause the modified files to carry prominent notices stating
- that you changed the files and the date of any change; and
-
- * cause the whole of any work that you distribute or publish,
- that in whole or in part contains the Program or any part
- thereof, either with or without modifications, to be
- licensed at no charge to all third parties under the terms
- of this General Public License (except that you may choose
- to grant warranty protection to some or all third parties,
- at your option).
-
- * If the modified program normally reads commands
- interactively when run, you must cause it, when started
- running for such interactive use in the simplest and most
- usual way, to print or display an announcement including an
- appropriate copyright notice and a notice that there is no
- warranty (or else, saying that you provide a warranty) and
- that users may redistribute the program under these
- conditions, and telling the user how to view a copy of this
- General Public License.
-
- * You may charge a fee for the physical act of transferring a
- copy, and you may at your option offer warranty protection
- in exchange for a fee.
-
- Mere aggregation of another independent work with the Program
- (or its derivative) on a volume of a storage or distribution
- medium does not bring the other work under the scope of these
- terms.
-
- 4. You may copy and distribute the Program (or a portion or
- derivative of it, under Paragraph 2) in object code or
- executable form under the terms of Paragraphs 1 and 2 above
- provided that you also do one of the following:
-
- * accompany it with the complete corresponding
- machine-readable source code, which must be distributed
- under the terms of Paragraphs 1 and 2 above; or,
-
- * accompany it with a written offer, valid for at least three
- years, to give any third party free (except for a nominal
- charge for the cost of distribution) a complete
- machine-readable copy of the corresponding source code, to
- be distributed under the terms of Paragraphs 1 and 2 above;
- or,
-
- * accompany it with the information you received as to where
- the corresponding source code may be obtained. (This
- alternative is allowed only for noncommercial distribution
- and only if you received the program in object code or
- executable form alone.)
-
- Source code for a work means the preferred form of the work for
- making modifications to it. For an executable file, complete
- source code means all the source code for all modules it
- contains; but, as a special exception, it need not include
- source code for modules which are standard libraries that
- accompany the operating system on which the executable file
- runs, or for standard header files or definitions files that
- accompany that operating system.
-
- 5. You may not copy, modify, sublicense, distribute or transfer the
- Program except as expressly provided under this General Public
- License. Any attempt otherwise to copy, modify, sublicense,
- distribute or transfer the Program is void, and will
- automatically terminate your rights to use the Program under
- this License. However, parties who have received copies, or
- rights to use copies, from you under this General Public License
- will not have their licenses terminated so long as such parties
- remain in full compliance.
-
- 6. By copying, distributing or modifying the Program (or any work
- based on the Program) you indicate your acceptance of this
- license to do so, and all its terms and conditions.
-
- 7. Each time you redistribute the Program (or any work based on the
- Program), the recipient automatically receives a license from
- the original licensor to copy, distribute or modify the Program
- subject to these terms and conditions. You may not impose any
- further restrictions on the recipients' exercise of the rights
- granted herein.
-
- 8. The Free Software Foundation may publish revised and/or new
- versions of the General Public License from time to time. Such
- new versions will be similar in spirit to the present version,
- but may differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
- Program specifies a version number of the license which applies
- to it and ``any later version'', you have the option of
- following the terms and conditions either of that version or of
- any later version published by the Free Software Foundation. If
- the Program does not specify a version number of the license,
- you may choose any version ever published by the Free Software
- Foundation.
-
- 9. If you wish to incorporate parts of the Program into other free
- programs whose distribution conditions are different, write to
- the author to ask for permission. For software which is
- copyrighted by the Free Software Foundation, write to the Free
- Software Foundation; we sometimes make exceptions for this. Our
- decision will be guided by the two goals of preserving the free
- status of all derivatives of our free software and of promoting
- the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 10. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
- WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE
- LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
- HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM ``AS IS''
- WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
- INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
- ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS
- WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE
- COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 11. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
- WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY
- MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
- LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
- INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR
- INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS
- OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
- YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH
- ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN
- ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
-Appendix: How to Apply These Terms to Your 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
-free software which everyone can redistribute and change under these
-terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the ``copyright'' line and a pointer to where the full notice is found.
-
- ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES.
- Copyright (C) 19YY NAME OF AUTHOR
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 1, or (at your option)
- any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-
- Also add information on how to contact you by electronic and paper
-mail.
-
-If the program is interactive, make it output a short notice like
-this when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) 19YY NAME OF AUTHOR
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
- The hypothetical commands `show w' and `show c' should show the
-appropriate parts of the General Public License. Of course, the
-commands you use may be called something other than `show w' and
-`show c'; they could even be mouse-clicks or menu items--whatever
-suits your program.
-
-You should also get your employer (if you work as a programmer) or
-your school, if any, to sign a ``copyright disclaimer'' for the
-program, if necessary. Here a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the
- program `Gnomovision' (a program to direct compilers to make passes
- at assemblers) written by James Hacker.
-
- SIGNATURE OF TY COON, 1 April 1989
- Ty Coon, President of Vice
-
-That's all there is to it!
-
-
-
-File: gawk-info, Node: This Manual, Next: Getting Started, Prev: License, Up: Top
-
-Using This Manual
-*****************
-
-The term `gawk' refers to a program (a version of `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
-`awk' utility'' and the language ``the `awk' language''. The purpose
-of this manual is to explain the `awk' language and how to run the
-`awk' utility.
-
-The term "`awk' program" refers to a program written by you in the
-`awk' programming language.
-
-*Note Getting Started::, for the bare essentials you need to know to
-start using `awk'.
-
-Useful ``one--liners'' are included to give you a feel for the `awk'
-language (*note One-liners::.).
-
-A sizable sample `awk' program has been provided for you (*note
-Sample Program::.).
-
-If you find terms that you aren't familiar with, try looking them up
-in the glossary (*note Glossary::.).
-
-Most of the time complete `awk' programs are used as examples, but in
-some of the more advanced sections, only the part of the `awk'
-program that illustrates the concept being described is shown.
-
-* Menu:
-
-This chapter contains the following sections:
-
-* The Files:: Sample data files for use in the `awk' programs
- illustrated in this manual.
-
-
-
-File: gawk-info, Node: The Files, Up: This Manual
-
-Input Files for the Examples
-============================
-
-This manual contains many sample programs. The data for many of
-those programs comes from two files. The first file, called
-`BBS-list', represents a list of computer bulletin board systems and
-information about those systems.
-
-Each line of this file is one "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 `A'
-in the last column means the board operates 24 hours all week. A `B'
-in the last column means the board operates evening and weekend
-hours, only. A `C' means the board operates only on weekends.
-
- aardvark 555-5553 1200/300 B
- alpo-net 555-3412 2400/1200/300 A
- barfly 555-7685 1200/300 A
- bites 555-1675 2400/1200/300 A
- camelot 555-0542 300 C
- core 555-2912 1200/300 C
- fooey 555-1234 2400/1200/300 B
- foot 555-6699 1200/300 B
- macfoo 555-6480 1200/300 A
- sdace 555-3430 2400/1200/300 A
- sabafoo 555-2127 1200/300 C
-
-The second data file, called `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.
-
- Jan 13 25 15 115
- Feb 15 32 24 226
- Mar 15 24 34 228
- Apr 31 52 63 420
- May 16 34 29 208
- Jun 31 42 75 492
- Jul 24 34 67 436
- Aug 15 34 47 316
- Sep 13 55 37 277
- Oct 29 54 68 525
- Nov 20 87 82 577
- Dec 17 35 61 401
-
- Jan 21 36 64 620
- Feb 26 58 80 652
- Mar 24 75 70 495
- Apr 21 70 74 514
-
-If you are reading this in GNU Emacs using Info, you can copy the
-regions of text showing these sample files into your own test files.
-This way you can try out the examples shown in the remainder of this
-document. You do this by using the command `M-x write-region' to
-copy text from the Info file into a file for use with `awk' (see your
-``GNU Emacs Manual'' for more information). Using this information,
-create your own `BBS-list' and `inventory-shipped' files, and
-practice what you learn in this manual.
-
-
-
-File: gawk-info, Node: Getting Started, Next: Reading Files, Prev: This Manual, Up: Top
-
-Getting Started With `awk'
-**************************
-
-The basic function of `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, `awk' performs specified actions on
-that line. Then `awk' keeps processing input lines until the end of
-the file is reached.
-
-An `awk' "program" or "script" consists of a series of "rules".
-(They may also contain "function definitions", but that is an
-advanced feature, so let's ignore it for now. *Note User-defined::.)
-
-A rule contains a "pattern", an "action", or both. Actions are
-enclosed in curly braces to distinguish them from patterns.
-Therefore, an `awk' program is a sequence of rules in the form:
-
- PATTERN { ACTION }
- PATTERN { ACTION }
- ...
-
- * Menu:
-
-* Very Simple:: A very simple example.
-* 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.
-* Statements/Lines:: Subdividing or combining statements into lines.
-
-* When:: When to use gawk and when to use other things.
-
-
-
-File: gawk-info, Node: Very Simple, Next: Two Rules, Up: Getting Started
-
-A Very Simple Example
-=====================
-
-The following command runs a simple `awk' program that searches the
-input file `BBS-list' for the string of characters: `foo'. (A string
-of characters is usually called, quite simply, a "string".)
-
- awk '/foo/ { print $0 }' BBS-list
-
-When lines containing `foo' are found, they are printed, because
-`print $0' means print the current line. (Just `print' by itself
-also means the same thing, so we could have written that instead.)
-
-You will notice that slashes, `/', surround the string `foo' in the
-actual `awk' program. The slashes indicate that `foo' is a pattern
-to search for. This type of pattern is called a "regular
-expression", and is covered in more detail later (*note Regexp::.).
-There are single quotes around the `awk' program so that the shell
-won't interpret any of it as special shell characters.
-
-Here is what this program prints:
-
- fooey 555-1234 2400/1200/300 B
- foot 555-6699 1200/300 B
- macfoo 555-6480 1200/300 A
- sabafoo 555-2127 1200/300 C
-
-In an `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 *every*
-input line.
-
-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 `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.)
-
-
-
-File: gawk-info, Node: Two Rules, Next: More Complex, Prev: Very Simple, Up: Getting Started
-
-An Example with Two Rules
-=========================
-
-The `awk' utility reads the input files one line at a time. For each
-line, `awk' tries the patterns of all the rules. If several patterns
-match then several actions are run, in the order in which they appear
-in the `awk' program. If no patterns match, then no actions are run.
-
-After processing all the rules (perhaps none) that match the line,
-`awk' reads the next line (however, *note Next::.). This continues
-until the end of the file is reached.
-
-For example, the `awk' program:
-
- /12/ { print $0 }
- /21/ { print $0 }
-
-contains two rules. The first rule has the string `12' as the
-pattern and `print $0' as the action. The second rule has the string
-`21' as the pattern and also has `print $0' as the action. Each
-rule's action is enclosed in its own pair of braces.
-
-This `awk' program prints every line that contains the string `12'
-*or* the string `21'. If a line contains both strings, it is printed
-twice, once by each rule.
-
-If we run this program on our two sample data files, `BBS-list' and
-`inventory-shipped', as shown here:
-
- awk '/12/ { print $0 }
- /21/ { print $0 }' BBS-list inventory-shipped
-
-we get the following output:
-
- aardvark 555-5553 1200/300 B
- alpo-net 555-3412 2400/1200/300 A
- barfly 555-7685 1200/300 A
- bites 555-1675 2400/1200/300 A
- core 555-2912 1200/300 C
- fooey 555-1234 2400/1200/300 B
- foot 555-6699 1200/300 B
- macfoo 555-6480 1200/300 A
- sdace 555-3430 2400/1200/300 A
- sabafoo 555-2127 1200/300 C
- sabafoo 555-2127 1200/300 C
- Jan 21 36 64 620
- Apr 21 70 74 514
-
-Note how the line in `BBS-list' beginning with `sabafoo' was printed
-twice, once for each rule.
-
-
-
-File: gawk-info, Node: More Complex, Next: Running gawk, Prev: Two Rules, Up: Getting Started
-
-A More Complex Example
-======================
-
-Here is an example to give you an idea of what typical `awk' programs
-do. This example shows how `awk' can be used to summarize, select,
-and rearrange the output of another utility. It uses features that
-haven't been covered yet, so don't worry if you don't understand all
-the details.
-
- ls -l | awk '$5 == "Nov" { sum += $4 }
- END { print sum }'
-
-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.)
-
-The `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:
-
- -rw-r--r-- 1 close 1933 Nov 7 13:05 Makefile
- -rw-r--r-- 1 close 10809 Nov 7 13:03 gawk.h
- -rw-r--r-- 1 close 983 Apr 13 12:14 gawk.tab.h
- -rw-r--r-- 1 close 31869 Jun 15 12:20 gawk.y
- -rw-r--r-- 1 close 22414 Nov 7 13:03 gawk1.c
- -rw-r--r-- 1 close 37455 Nov 7 13:03 gawk2.c
- -rw-r--r-- 1 close 27511 Dec 9 13:07 gawk3.c
- -rw-r--r-- 1 close 7989 Nov 7 13:03 gawk4.c
-
-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 `$5 == "Nov"' in our `awk' program is an expression that tests
-whether the fifth field of the output from `ls -l' matches the string
-`Nov'. Each time a line has the string `Nov' in its fifth field, the
-action `{ sum += $4 }' is performed. This adds the fourth field (the
-file size) to the variable `sum'. As a result, when `awk' has
-finished reading all the input lines, `sum' will be the sum of the
-sizes of files whose lines matched the pattern.
-
-After the last line of output from `ls' has been processed, the `END'
-pattern is executed, and the value of `sum' is printed. In this
-example, the value of `sum' would be 80600.
-
-These more advanced `awk' techniques are covered in later sections
-(*note Actions::.). Before you can move on to more advanced `awk'
-programming, you have to know how `awk' interprets your input and
-displays your output. By manipulating "fields" and using special
-"print" statements, you can produce some very useful and spectacular
-looking reports.
-
-
-
-File: gawk-info, Node: Running gawk, Next: Comments, Prev: More Complex, Up: Getting Started
-
-How to Run `awk' Programs
-=========================
-
-There are several ways to run an `awk' program. If the program is
-short, it is easiest to include it in the command that runs `awk',
-like this:
-
- awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
-
- where 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:
-
- awk -f PROGRAM-FILE INPUT-FILE1 INPUT-FILE2 ...
-
- * Menu:
-
-* One-shot:: Running a short throw--away `awk' program.
-* Read Terminal:: Using no input files (input from terminal instead).
-* Long:: Putting permanent `awk' programs in files.
-* Executable Scripts:: Making self--contained `awk' programs.
-* Command Line:: How the `awk' command line is laid out.
-
-
-
-File: gawk-info, Node: One-shot, Next: Read Terminal, Up: Running gawk
-
-One--shot Throw--away `awk' Programs
-------------------------------------
-
-Once you are familiar with `awk', you will often type simple programs
-at the moment you want to use them. Then you can write the program
-as the first argument of the `awk' command, like this:
-
- awk 'PROGRAM' INPUT-FILE1 INPUT-FILE2 ...
-
- where PROGRAM consists of a series of PATTERNS and ACTIONS, as
-described earlier.
-
-This command format tells the shell to start `awk' and use the
-PROGRAM to process records in the input file(s). There are single
-quotes around the PROGRAM so that the shell doesn't interpret any
-`awk' characters as special shell characters. They cause the shell
-to treat all of PROGRAM as a single argument for `awk'. They also
-allow PROGRAM to be more than one line long.
-
-This format is also useful for running short or medium--sized `awk'
-programs from shell scripts, because it avoids the need for a
-separate file for the `awk' program. A self--contained shell script
-is more reliable since there are no other files to misplace.
-
-
-
-File: gawk-info, Node: Read Terminal, Next: Long, Prev: One-shot, Up: Running gawk
-
-Running `awk' without Input Files
----------------------------------
-
-You can also use `awk' without any input files. If you type the
-command line:
-
- awk 'PROGRAM'
-
-then `awk' applies the PROGRAM to the "standard input", which usually
-means whatever you type on the terminal. This continues until you
-indicate end--of--file by typing `Control-d'.
-
-For example, if you type:
-
- awk '/th/'
-
-whatever you type next will be taken as data for that `awk' program.
-If you go on to type the following data,
-
- Kathy
- Ben
- Tom
- Beth
- Seth
- Karen
- Thomas
- `Control-d'
-
-then `awk' will print
-
- Kathy
- Beth
- Seth
-
-as matching the pattern `th'. Notice that it did not recognize
-`Thomas' as matching the pattern. The `awk' language is "case
-sensitive", and matches patterns *exactly*.
-
-
-
-File: gawk-info, Node: Long, Next: Executable Scripts, Prev: Read Terminal, Up: Running gawk
-
-Running Long Programs
----------------------
-
-Sometimes your `awk' programs can be very long. In this case it is
-more convenient to put the program into a separate file. To tell
-`awk' to use that file for its program, you type:
-
- awk -f SOURCE-FILE INPUT-FILE1 INPUT-FILE2 ...
-
- The `-f' tells the `awk' utility to get the `awk' program from the
-file SOURCE-FILE. Any file name can be used for SOURCE-FILE. For
-example, you could put the program:
-
- /th/
-
-into the file `th-prog'. Then the command:
-
- awk -f th-prog
-
-does the same thing as this one:
-
- awk '/th/'
-
-which was explained earlier (*note Read Terminal::.). Note that you
-don't usually need single quotes around the file name that you
-specify with `-f', because most file names don't contain any of the
-shell's special characters.
-
-If you want to identify your `awk' program files clearly as such, you
-can add the extension `.awk' to the filename. This doesn't affect
-the execution of the `awk' program, but it does make ``housekeeping''
-easier.
-
-
-
-File: gawk-info, Node: Executable Scripts, Next: Command Line, Prev: Long, Up: Running gawk
-
-Executable `awk' Programs
--------------------------
-
-(The following section assumes that you are already somewhat familiar
-with `awk'.)
-
-Once you have learned `awk', you may want to write self--contained
-`awk' scripts, using the `#!' script mechanism. You can do this on
-BSD Unix systems and GNU.
-
-For example, you could create a text file named `hello', containing
-the following (where `BEGIN' is a feature we have not yet discussed):
-
- #! /bin/awk -f
-
- # a sample awk program
-
- BEGIN { print "hello, world" }
-
-After making this file executable (with the `chmod' command), you can
-simply type:
-
- hello
-
-at the shell, and the system will arrange to run `awk' as if you had
-typed:
-
- awk -f hello
-
-Self--contained `awk' scripts are particularly useful for putting
-`awk' programs into production on your system, without your users
-having to know that they are actually using an `awk' program.
-
-If your system does not support the `#!' mechanism, you can get a
-similar effect using a regular shell script. It would look something
-like this:
-
- : a sample awk program
-
- awk 'PROGRAM' "$@"
-
-Using this technique, it is *vital* to enclose the PROGRAM in single
-quotes to protect it from interpretation by the shell. If you omit
-the quotes, only a shell wizard can predict the result.
-
-The `"$@"' causes the shell to forward all the command line arguments
-to the `awk' program, without interpretation.
-
-
-
-File: gawk-info, Node: Command Line, Prev: Executable Scripts, Up: Running gawk
-
-Details of the `awk' Command Line
----------------------------------
-
-(The following section assumes that you are already familiar with
-`awk'.)
-
-There are two ways to run `awk'. Here are templates for both of
-them; items enclosed in `[' and `]' in these templates are optional.
-
- awk [ -FFS ] [ -- ] 'PROGRAM' FILE ...
- awk [ -FFS ] -f SOURCE-FILE [ -f SOURCE-FILE ... ] [ -- ] FILE ...
-
- Options begin with a minus sign, and consist of a single character.
-The options and their meanings are as follows:
-
-`-FFS'
- This sets the `FS' variable to FS (*note Special::.). As a
- special case, if FS is `t', then `FS' will be set to the tab
- character (`"\t"').
-
-`-f SOURCE-FILE'
- Indicates that the `awk' program is to be found in SOURCE-FILE
- instead of in the first non--option argument.
-
-`--'
- This signals the end of the command line options. If you wish
- to specify an input file named `-f', you can precede it with the
- `--' argument to prevent the `-f' from being interpreted as an
- option. This handling of `--' follows the POSIX argument
- parsing conventions.
-
-Any other options will be flagged as invalid with a warning message,
-but are otherwise ignored.
-
-If the `-f' option is *not* used, then the first non--option command
-line argument is expected to be the program text.
-
-The `-f' option may be used more than once on the command line.
-`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 `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 `/dev/tty' as one of the arguments to a
-`-f'. Type your program, and end it with the keyboard end--of--file
-character `Control-d'.
-
-Any additional arguments on the command line are made available to
-your `awk' program in the `ARGV' array (*note Special::.). These
-arguments are normally treated as input files to be processed in the
-order specified. However, an argument that has the form VAR`='VALUE,
-means to assign the value VALUE to the variable VAR--it does not
-specify a file at all.
-
-Command line options and the program text (if present) are omitted
-from the `ARGV' array. All other arguments, including variable
-assignments, are included (*note Special::.).
-
-The distinction between file name arguments and variable--assignment
-arguments is made when `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, *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 *not* available
-inside a `BEGIN' rule (*note BEGIN/END::.), since such rules are run
-before `awk' begins scanning the argument list.
-
-The variable assignment feature is most useful for assigning to
-variables such as `RS', `OFS', and `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:
-
- awk 'pass == 1 { PASS 1 STUFF }
- pass == 2 { PASS 2 STUFF }' pass=1 datafile pass=2 datafile
-
-
-
-File: gawk-info, Node: Comments, Next: Statements/Lines, Prev: Running gawk, Up: Getting Started
-
-Comments in `awk' Programs
-==========================
-
-When you write a complicated `awk' program, you can put "comments" in
-the program file to help you remember what the program does, and how
-it works.
-
-A comment starts with the the sharp sign character, `#', and
-continues to the end of the line. The `awk' language ignores the
-rest of a line following a sharp sign. For example, we could have
-put the following into `th-prog':
-
- # This program finds records containing the pattern `th'. This is how
- # you continue comments on additional lines.
- /th/
-
-You can put comment lines into keyboard--composed throw--away `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 another time.
-
-
-
-File: gawk-info, Node: Statements/Lines, Next: When, Prev: Comments, Up: Getting Started
-
-`awk' Statements versus Lines
-=============================
-
-Most often, each line in an `awk' program is a separate statement or
-separate rule, like this:
-
- awk '/12/ { print $0 }
- /21/ { print $0 }' BBS-list inventory-shipped
-
-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:
-
- , { ? : || &&
-
-Lines ending in `do' or `else' automatically have their statements
-continued on the following line(s). A newline at any other point
-ends the statement.
-
-If you would like to split a single statement into two lines at a
-point where a newline would terminate it, you can "continue" it by
-ending the first line with a backslash character, `\'. This is
-allowed absolutely anywhere in the statement, even in the middle of a
-string or regular expression. For example:
-
- awk '/This program is too long, so continue it\
- on the next line/ { print $1 }'
-
-We have generally not used backslash continuation in the sample
-programs in this manual. Since there is no limit on the length of a
-line, it is never strictly necessary; it just makes programs
-prettier. We have preferred to make them even more pretty by keeping
-the statements short. Backslash continuation is most useful when
-your `awk' program is in a separate source file, instead of typed in
-on the command line.
-
-*Warning: this does not work if you are using the C shell.*
-Continuation with backslash works for `awk' programs in files, and
-also for one--shot programs *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.
-
-When `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, `;'. This also applies to the rules
-themselves. Thus, the above example program could have been written:
-
- /12/ { print $0 } ; /21/ { print $0 }
-
-*Note:* It is a new requirement that rules on the same line require
-semicolons as a separator in the `awk' language; it was done for
-consistency with the statements in the action part of rules.
-
-
-
-File: gawk-info, Node: When, Prev: Statements/Lines, Up: Getting Started
-
-When to Use `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 `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 `ls'. (*Note A More Complex Example: More Complex.)
-
-Programs written with `awk' are usually much smaller than they would
-be in other languages. This makes `awk' programs easy to compose and
-use. Often `awk' programs can be quickly composed at your terminal,
-used once, and thrown away. Since `awk' programs are interpreted,
-you can avoid the usually lengthy edit--compile--test--debug cycle of
-software development.
-
-Complex programs have been written in `awk', including a complete
-retargetable assembler for 8--bit microprocessors (*note Glossary::.
-for more information) and a microcode assembler for a special purpose
-Prolog computer. However, `awk''s capabilities are strained by tasks
-of such complexity.
-
-If you find yourself writing `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 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 `awk' programs,
-but they will be easier to maintain and usually run more efficiently.
-
-
-
-File: gawk-info, Node: Reading Files, Next: Printing, Prev: Getting Started, Up: Top
-
-Reading Files (Input)
-*********************
-
-In the typical `awk' program, all input is read either from the
-standard input (usually the keyboard) or from files whose names you
-specify on the `awk' command line. If you specify input files, `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 `FILENAME'
-(*note Special::.).
-
-The input is split automatically into "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 "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 `getline' command, which
-can do explicit input from any number of files.
-
-* 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 `getline' function.
-* Close Input:: Closing an input file (so you can read from
- the beginning once more).
-
-
-
-File: gawk-info, Node: Records, Next: Fields, Up: Reading Files
-
-How Input is Split into Records
-===============================
-
-The `awk' language divides its input into records and fields.
-Records are separated from each other by the "record separator". By
-default, the record separator is the "newline" character. Therefore,
-normally, a record is a line of text.
-
-Sometimes you may want to use a different character to separate your
-records. You can use different characters by changing the special
-variable `RS'.
-
-The value of `RS' is a string that says how to separate records; the
-default value is `"\n"', the string of just a newline character.
-This is why lines of text are the default record. Although `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. `RS' is exceptional in this regard; `awk' uses the full
-value of all its other special variables.
-
-The value of `RS' is changed by "assigning" it a new value (*note
-Assignment Ops::.). One way to do this is at the beginning of your
-`awk' program, before any input has been processed, using the special
-`BEGIN' pattern (*note BEGIN/END::.). This way, `RS' is changed to
-its new value before any input is read. The new value of `RS' is
-enclosed in quotation marks. For example:
-
- awk 'BEGIN { RS = "/" } ; { print $0 }' BBS-list
-
-changes the value of `RS' to `/', the slash character, before reading
-any input. Records are now separated by a slash. The second rule in
-the `awk' program (the action with no pattern) will proceed to print
-each record. Since each `print' statement adds a newline at the end
-of its output, the effect of this `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 (*note Command Line::.).
-
- awk '...' RS="/" SOURCE-FILE
-
-`RS' will be set to `/' before processing SOURCE-FILE.
-
-The empty string (a string of no characters) has a special meaning as
-the value of `RS': it means that records are separated only by blank
-lines. *Note Multiple::, for more details.
-
-The `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 `FNR'. It is reset to zero when a new file
-is started. Another variable, `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 `RS' in the middle of an `awk' run, the
-new value is used to delimit subsequent records, but the record
-currently being processed (and records already finished) are not
-affected.
-
-
diff --git a/gawk-info-2 b/gawk-info-2
deleted file mode 100644
index a228c5b9..00000000
--- a/gawk-info-2
+++ /dev/null
@@ -1,1265 +0,0 @@
-Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
-file gawk.texinfo.
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them.
-
-Copyright (C) 1989 Free Software Foundation, Inc.
-
-Permission is granted to make and distribute verbatim copies of this
-manual provided the copyright notice and this permission notice are
-preserved on all copies.
-
-Permission is granted to copy and distribute modified versions of
-this manual under the conditions for verbatim copying, provided that
-the entire resulting derived work is distributed under the terms of a
-permission notice identical to this one.
-
-Permission is granted to copy and distribute translations of this
-manual into another language, under the above conditions for modified
-versions, except that this permission notice may be stated in a
-translation approved by the Foundation.
-
-
-
-File: gawk-info, Node: Fields, Next: Non-Constant Fields, Prev: Records, Up: Reading Files
-
-Examining Fields
-================
-
-When `awk' reads an input record, the record is automatically
-separated or "parsed" by the interpreter into pieces called "fields".
-By default, fields are separated by whitespace, like words in a line.
-Whitespace in `awk' means any string of one or more spaces and/or
-tabs; other characters such as newline, formfeed, and so on, that are
-considered whitespace by other languages are *not* considered
-whitespace by `awk'.
-
-The purpose of fields is to make it more convenient for you to refer
-to these pieces of the record. You don't have to use them--you can
-operate on the whole record if you wish--but fields are what make
-simple `awk' programs so powerful.
-
-To refer to a field in an `awk' program, you use a dollar--sign, `$',
-followed by the number of the field you want. Thus, `$1' refers to
-the first field, `$2' to the second, and so on. For example, suppose
-the following is a line of input:
-
- This seems like a pretty nice example.
-
- Here the first field, or `$1', is `This'; the second field, or `$2',
-is `seems'; and so on. Note that the last field, `$7', is
-`example.'. Because there is no space between the `e' and the `.',
-the period is considered part of the seventh field.
-
-No matter how many fields there are, the last field in a record can
-be represented by `$NF'. So, in the example above, `$NF' would be
-the same as `$7', which is `example.'. Why this works is explained
-below (*note Non-Constant Fields::.). If you try to refer to a field
-beyond the last one, such as `$8' when the record has only 7 fields,
-you get the empty string.
-
-Plain `NF', with no `$', is a special variable whose value is the
-number of fields in the current record.
-
-`$0', which looks like an attempt to refer to the zeroth field, is a
-special case: it represents the whole input record. This is what you
-would use when you aren't interested in fields.
-
-Here are some more examples:
-
- awk '$1 ~ /foo/ { print $0 }' BBS-list
-
-This example contains the "matching" operator `~' (*note Comparison
-Ops::.). Using this operator, all records in the file `BBS-list'
-whose first field contains the string `foo' are printed.
-
-By contrast, the following example:
-
- awk '/foo/ { print $1, $NF }' BBS-list
-
-looks for the string `foo' in *the entire record* and prints the
-first field and the last field for each input record containing the
-pattern.
-
-The following program will search the system password file, and print
-the entries for users who have no password.
-
- awk -F: '$2 == ""' /etc/passwd
-
-This program uses the `-F' option on the command line to set the file
-separator. (Fields in `/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.)
-
-
-
-File: gawk-info, Node: Non-Constant Fields, Next: Changing Fields, Prev: Fields, Up: Reading Files
-
-Non-constant Field Numbers
-==========================
-
-The number of a field does not need to be a constant. Any expression
-in the `awk' language can be used after a `$' to refer to a field.
-The `awk' utility evaluates the expression and uses the "numeric
-value" as a field number. Consider this example:
-
- awk '{ print $NR }'
-
-Recall that `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.
-
-Here is another example of using expressions as field numbers:
-
- awk '{ print $(2*2) }' BBS-list
-
-The `awk' language must evaluate the expression `(2*2)' and use its
-value as the field number to print. The `*' sign represents
-multiplication, so the expression `2*2' evaluates to 4. This
-example, then, prints the hours of operation (the fourth field) for
-every line of the file `BBS-list'.
-
-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, `$(1-4)' would try to examine field number -3; it would
-result in an empty string.
-
-If the field number you compute is zero, you get the entire record.
-
-The number of fields in the current record is stored in the special
-variable `NF' (*note Special::.). The expression `$NF' is not a
-special feature: it is the direct consequence of evaluating `NF' and
-using its value as a field number.
-
-
-
-File: gawk-info, Node: Changing Fields, Next: Field Separators, Prev: Non-Constant Fields, Up: Reading Files
-
-Changing the Contents of a Field
-================================
-
-You can change the contents of a field as seen by `awk' within an
-`awk' program; this changes what `awk' perceives as the current input
-record. (The actual input is untouched: `awk' never modifies the
-input file.)
-
-Look at this example:
-
- awk '{ $3 = $2 - 10; print $2, $3 }' inventory-shipped
-
-The `-' sign represents subtraction, so this program reassigns field
-three, `$3', to be the value of field two minus ten, ``$2' - 10'.
-(*Note Arithmetic Ops::.) Then field two, and the new value for
-field three, are printed.
-
-In order for this to work, the text in field `$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. *Note Conversion::.
-
-When you change the value of a field (as perceived by `awk'), the
-text of the input record is recalculated to contain the new field
-where the old one was. `$0' will from that time on reflect the
-altered field. Thus,
-
- awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
-
-will print 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:
-
- awk '{ $6 = ($5 + $4 + $3 + $2)/4) ; print $6 }' inventory-shipped
-
-We've just created `$6', whose value is the average of fields `$2',
-`$3', `$4', and `$5'. The `+' sign represents addition, and the `/'
-sign represents division. For the file `inventory-shipped' `$6'
-represents the average number of parcels shipped for a particular
-month.
-
-Creating a new field changes what `awk' interprets as the current
-input record. The value of `$0' will be recomputed. This
-recomputation affects and is affected by features not yet discussed,
-in particular, the "Output Field Separator", `OFS', which is used to
-separate the fields (*note Output Separators::.), and `NF' (the
-number of fields; *note Fields::.). For example, the value of `NF'
-will be set to the number of the highest out--of--range field you
-create.
-
-Note, however, that merely *referencing* an out--of--range field will
-*not* change the value of either `$0' or `NF'. Referencing an
-out--of--range field merely produces a null string. For example:
-
- if ($(NF+1) != "")
- print "can't happen"
- else
- print "everything is normal"
-
-should print `everything is normal'. (*Note If::, for more
-information about `awk''s `if-else' statements.)
-
-
-
-File: gawk-info, Node: Field Separators, Next: Multiple, Prev: Changing Fields, Up: Reading Files
-
-Specifying How Fields Are Separated
-===================================
-
-You can change the way `awk' splits a record into fields by changing
-the value of the "field separator". The field separator is
-represented by the special variable `FS' in an `awk' program, and can
-be set by `-F' on the command line. The `awk' language scans each
-input line for the field separator character to determine the
-positions of fields within that line. Shell programmers take note!
-`awk' uses the variable `FS', not `IFS'.
-
-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 `FS' by "assigning" it a new value. You can
-do this using the special `BEGIN' pattern (*note BEGIN/END::.). This
-pattern allows you to change the value of `FS' before any input is
-read. The new value of `FS' is enclosed in quotations. For example,
-set the value of `FS' to the string `","':
-
- awk 'BEGIN { FS = "," } ; { print $2 }'
-
-and use the input line:
-
- John Q. Smith, 29 Oak St., Walamazoo, MI 42139
-
-This `awk' program will extract the string `29 Oak St.'.
-
-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 `John Q. Smith, LXIX'. If you assigned
-`FS' to be `,' then:
-
- awk 'BEGIN { FS = "," } ; { print $2 }
-
-would extract `LXIX', instead of `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.
-
-You can assign `FS' to be a series of characters. For example, the
-assignment:
-
- FS = ", \t"
-
-makes every area of an input line that consists of a comma followed
-by a space and a tab, into a field separator. (`\t' stands for a tab.)
-
-If `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 `FS' to a string longer than one character, that string
-is evaluated as a "regular expression" (*note Regexp::.). The value
-of the regular expression is used as a field separator.
-
-`FS' can be set on the command line. You use the `-F' argument to do
-so. For example:
-
- awk -F, 'PROGRAM' INPUT-FILES
-
-sets `FS' to be the `,' character. Notice that the argument uses a
-capital `F'. Contrast this with `-f', which specifies a file
-containing an `awk' program. Case is significant in command options:
-the `-F' and `-f' options have nothing to do with each other. You
-can use both options at the same time to set the `FS' argument *and*
-get an `awk' program from a file.
-
-As a special case, if the argument to `-F' is `t', then `FS' is set
-to the tab character. (This is because if you type `-F\t', without
-the quotes, at the shell, the `\' gets deleted, so `awk' figures that
-you really want your fields to be separated with tabs, and not `t's.
-Use `FS="t"' if you really do want to separate your fields with `t's.)
-
-For example, let's use an `awk' program file called `baud.awk' that
-contains the pattern `/300/', and the action `print $1'. We'll use
-the operating system utility `cat' to ``look'' at our program:
-
- % cat baud.awk
- /300/ { print $1 }
-
-Let's also set `FS' to be the `-' character. We will apply all this
-information to the file `BBS-list'. This `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.
-
- awk -F- -f baud.awk BBS-list
-
-produces this output:
-
- aardvark 555
- alpo
- barfly 555
- bites 555
- camelot 555
- core 555
- fooey 555
- foot 555
- macfoo 555
- sdace 555
- sabafoo 555
-
-Note the second line of output. If you check the original file, you
-will see that the second line looked like this:
-
- alpo-net 555-3412 2400/1200/300 A
-
-The `-' as part of the system's name was used as the field separator,
-instead of the `-' in the phone number that was originally intended.
-This demonstrates why you have to be careful in choosing your field
-and record separators.
-
-
-
-File: gawk-info, Node: Multiple, Next: Assignment Options, Prev: Field Separators, Up: Reading Files
-
-Multiple--Line Records
-======================
-
-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.
-
-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? 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
-`\f' in `awk', as in C) to separate them, making each record a page
-of the file. To do this, just set the variable `RS' to `"\f"' (a
-string containing the formfeed character), or whatever string you
-prefer to use.
-
-Another technique is to have blank lines separate records. By a
-special dispensation, a null string as the value of `RS' indicates
-that records are separated by one or more blank lines. If you set
-`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.
-
-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 `FS' to the string `"\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
-`"[ \t\n]+"' will do this nicely by treating the newlines inside the
-record just like spaces.
-
-When `RS' is set to the null string, the newline character *always*
-acts as a field separator. This is in addition to whatever value
-`FS' has. The probable reason for this rule is so that you get
-rational behavior in the default case (i.e. `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 `split' function to manually break up
-your data (*note String Functions::.).
-
-Here is how to use records separated by blank lines and break each
-line into fields normally:
-
- awk 'BEGIN { RS = ""; FS = "[ \t\n]+" } ; { print $0 }' BBS-list
-
-
-
-File: gawk-info, Node: Assignment Options, Next: Getline, Prev: Multiple, Up: Reading Files
-
-Assigning Variables on the Command Line
-=======================================
-
-You can include variable "assignments" among the file names on the
-command line used to invoke `awk' (*note Command Line::.). Such
-assignments have the form:
-
- VARIABLE=TEXT
-
-and allow you to change variables either at the beginning of the
-`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:
-
- awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
-
-prints the value of field number `n' for all input records. Before
-the first file is read, the command line sets the variable `n' equal
-to 4. This causes the fourth field of the file `inventory-shipped'
-to be printed. After the first file has finished, but before the
-second file is started, `n' is set to 2, so that the second field of
-the file `BBS-list' will be printed.
-
-Command line arguments are made available for explicit examination by
-the `awk' program in an array named `ARGV' (*note Special::.).
-
-
-
-File: gawk-info, Node: Getline, Prev: Assignment Options, Up: Reading Files
-
-Explicit Input with `getline'
-=============================
-
-So far we have been getting our input files from `awk''s main input
-stream--either the standard input (usually your terminal) or the
-files specified on the command line. The `awk' language has a
-special built--in function called `getline' that can be used to read
-input under your explicit control.
-
-This command is quite complex and should *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
-`getline' command include material that has not been covered yet.
-Therefore, come back and attempt the `getline' command *after* you
-have reviewed the rest of this manual and have a good knowledge of
-how `awk' works.
-
-When retrieving input, `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 `getline' returns a -1.
-
-In the following examples, COMMAND stands for a string value that
-represents a shell command.
-
-`getline'
- The `getline' function can be used by itself, in an `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
- *right now* on the next record. Here's an example:
-
- awk '{
- if (t = index($0, "/*")) {
- if(t > 1)
- tmp = substr($0, 1, t - 1)
- else
- tmp = ""
- u = index(substr($0, t + 2), "*/")
- while (! u) {
- getline
- t = -1
- u = index($0, "*/")
- }
- if(u <= length($0) - 2)
- $0 = tmp substr($0, t + u + 3)
- else
- $0 = tmp
- }
- print $0
- }'
-
- This `awk' program deletes all comments, `/* ... */', from the
- input. By replacing the `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 expression.
-
- This form of the `getline' command sets `NF' (the number of
- fields; *note Fields::.), `NR' (the number of records read so
- far), the `FNR' variable (*note Records::.), and the value of
- `$0'.
-
- *Note:* The new value of `$0' will be used in testing the
- patterns of any subsequent rules. The original value of `$0'
- that triggered the rule which executed `getline' is lost. By
- contrast, the `next' statement reads a new record but
- immediately begins processing it normally, starting with the
- first rule in the program. *Note Next::.
-
-`getline VAR'
- This form of `getline' reads a record into the variable 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.
-
- 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
- `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 `awk' never sees it.
-
- The following example swaps every two lines of input. For
- example, given:
-
- wan
- tew
- free
- phore
-
- it outputs:
-
- tew
- wan
- phore
- free
-
- Here's the program:
-
- awk '{
- if ((getline tmp) > 0) {
- print tmp
- print $0
- } else
- print $0
- }'
-
- The `getline' function used in this way sets only `NR' and `FNR'
- (and of course, VAR). The record is not split into fields, so
- the values of the fields (including `$0') and the value of `NF'
- do not change.
-
-`getline < FILE'
- This form of the `getline' function takes its input from the
- file FILE. Here FILE is a string--valued expression that
- specifies the file name.
-
- 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 program reads its input record from the
- file `foo.input' when it encounters a first field with a value
- equal to 10 in the current input file.
-
- awk '{
- if ($1 == 10) {
- getline < "foo.input"
- print
- } else
- print
- }'
-
- Since the main input stream is not used, the values of `NR' and
- `FNR' are not changed. But the record read is split into fields
- in the normal manner, so the values of `$0' and other fields are
- changed. So is the value of `NF'.
-
- This does not cause the record to be tested against all the
- patterns in the `awk' program, in the way that would happen if
- the record were read normally by the main processing loop of
- `awk'. However the new record is tested against any subsequent
- rules, just as when `getline' is used without a redirection.
-
-`getline VAR < FILE'
- This form of the `getline' function takes its input from the
- file FILE and puts it in the variable VAR. As above, FILE is a
- string--valued expression that specifies the file to read from.
-
- In this version of `getline', none of the built--in variables
- are changed, and the record is not split into fields. The only
- variable changed is VAR.
-
- For example, the following program copies all the input files to
- the output, except for records that say `@include FILENAME'.
- Such a record is replaced by the contents of the file FILENAME.
-
- awk '{
- if (NF == 2 && $1 == "@include") {
- while ((getline line < $2) > 0)
- print line
- close($2)
- } else
- print
- }'
-
- 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 `@include' line.
-
- The `close' command is used to ensure that if two identical
- `@include' lines appear in the input, the entire specified file
- is included twice. *Note Close Input::.
-
- One deficiency of this program is that it does not process
- nested `@include' statements the way a true macro preprocessor
- would.
-
-`COMMAND | getline'
- You can "pipe" the output of a command into `getline'. A pipe
- is simply a way to link the output of one program to the input
- of another. In this case, the string COMMAND is run as a shell
- command and its output is piped into `awk' to be used as input.
- This form of `getline' reads one record from the pipe.
-
- For example, the following program copies input to output,
- except for lines that begin with `@execute', which are replaced
- by the output produced by running the rest of the line as a
- shell command:
-
- awk '{
- if ($1 == "@execute") {
- tmp = substr($0, 10)
- while ((tmp | getline) > 0)
- print
- close(tmp)
- } else
- print
- }'
-
- The `close' command is used to ensure that if two identical
- `@execute' lines appear in the input, the command is run again
- for each one. *Note Close Input::.
-
- Given the input:
-
- foo
- bar
- baz
- @execute who
- bletch
-
- the program might produce:
-
- foo
- bar
- baz
- hack ttyv0 Jul 13 14:22
- hack ttyp0 Jul 13 14:23 (gnu:0)
- hack ttyp1 Jul 13 14:23 (gnu:0)
- hack ttyp2 Jul 13 14:23 (gnu:0)
- hack ttyp3 Jul 13 14:23 (gnu:0)
- bletch
-
- Notice that this program ran the command `who' and printed the
- result. (If you try this program yourself, you will get
- different results, showing you logged in.)
-
- This variation of `getline' splits the record into fields, sets
- the value of `NF' and recomputes the value of `$0'. The values
- of `NR' and `FNR' are not changed.
-
-`COMMAND | getline VAR'
- The output of the command COMMAND is sent through a pipe to
- `getline' and into the variable VAR. For example, the following
- program reads the current date and time into the variable
- `current_time', using the utility called `date', and then prints
- it.
-
- awk 'BEGIN {
- "date" | getline current_time
- close("date")
- print "Report printed on " current_time
- }'
-
- In this version of `getline', none of the built--in variables
- are changed, and the record is not split into fields.
-
-
-
-File: gawk-info, Node: Close Input, Up: Getline
-
-Closing Input Files
--------------------
-
-If the same file name or the same shell command is used with
-`getline' more than once during the execution of the `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
-`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 `close' statement:
-
- close (FILENAME)
-
-This statement closes a file or pipe, represented here by FILENAME.
-The string value of FILENAME must be the same value as the string
-used to open the file or pipe to begin with.
-
-Once this statement is executed, the next `getline' from that file or
-command will reopen the file or rerun the command.
-
-
-
-File: gawk-info, Node: Printing, Next: One-liners, Prev: Reading Files, Up: Top
-
-Printing Output
-***************
-
-One of the most common things that actions do is to output or "print"
-some or all of the input. For simple output, use the `print'
-statement. For fancier formatting use the `printf' statement. Both
-are described in this chapter.
-
-* Menu:
-
-* Print:: The `print' statement.
-* Print Examples:: Simple examples of `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 `printf' statement.
-
-
-
-File: gawk-info, Node: Print, Next: Print Examples, Up: Printing
-
-The `print' Statement
-=====================
-
-The `print' statement does output with simple, standardized
-formatting. You specify only the strings or numbers to be printed,
-in a list separated by commas. They are output, separated by single
-spaces, followed by a newline. The statement looks like this:
-
- print ITEM1, ITEM2, ...
-
- The entire list of items may optionally be enclosed in parentheses.
-The parentheses are necessary if any of the item expressions uses a
-relational operator; otherwise it could be confused with a
-redirection (*note Redirection::.). The relational operators are
-`==', `!=', `<', `>', `>=', `<=', `~' and `!~' (*note Comparison
-Ops::.).
-
-The items printed can be constant strings or numbers, fields of the
-current record (such as `$1'), variables, or any `awk' expressions.
-The `print' statement is completely general for computing *what*
-values to print. With one exception (*note Output Separators::.),
-what you can't do is specify *how* to print them--how many columns to
-use, whether to use exponential notation or not, and so on. For
-that, you need the `printf' statement (*note Printf::.).
-
-To print a fixed piece of text, write a string constant as one item,
-such as `"Hello there"'. If you forget to use the double--quote
-characters, your text will be taken as an `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 `print' with no items is equivalent to `print
-$0': it prints the entire current record. To print a blank line, use
-`print ""', where `""' is the null, or empty, string.
-
-Most often, each `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 single `print' can make any number of lines this way.
-
-
-
-File: gawk-info, Node: Print Examples, Next: Output Separators, Prev: Print, Up: Printing
-
-Examples of `print' Statements
-==============================
-
-Here is an example that prints the first two fields of each input
-record, with a space between them:
-
- awk '{ print $1, $2 }' inventory-shipped
-
-Its output looks like this:
-
- Jan 13
- Feb 15
- Mar 15
- ...
-
- A common mistake in using the `print' statement is to omit the comma
-between two items. This often has the effect of making the items run
-together in the output, with no space. The reason for this is that
-juxtaposing two string expressions in `awk' means to concatenate
-them. For example, without the comma:
-
- awk '{ print $1 $2 }' inventory-shipped
-
-prints:
-
- Jan13
- Feb15
- Mar15
- ...
-
- Neither example's output makes much sense to someone unfamiliar with
-the file `inventory-shipped'. A heading line at the beginning would
-make it clearer. Let's add some headings to our table of months
-(`$1') and green crates shipped (`$2'). We do this using the BEGIN
-pattern (*note BEGIN/END::.) to cause the headings to be printed only
-once:
-
- awk 'BEGIN { print "Month Crates"
- print "---- -----" }
- { print $1, $2 }' inventory-shipped
-
-Did you already guess what will happen? This program prints the
-following:
-
- Month Crates
- ---- -----
- Jan 13
- Feb 15
- Mar 15
- ...
-
- The headings and the table data don't line up! We can fix this by
-printing some spaces between the two fields:
-
- awk 'BEGIN { print "Month Crates"
- print "---- -----" }
- { print $1, " ", $2 }' inventory-shipped
-
-You can imagine that this way of lining up columns can get pretty
-complicated when you have many columns to fix. Counting spaces for
-two or three columns can be simple, but more than this and you can
-get ``lost'' quite easily. This is why the `printf' statement was
-created (*note Printf::.); one of its specialties is lining up
-columns of data.
-
-
-
-File: gawk-info, Node: Output Separators, Next: Redirection, Prev: Print Examples, Up: Printing
-
-Output Separators
-=================
-
-As mentioned previously, a `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 "output field separator", by setting the
-special variable `OFS'. The initial value of this variable is the
-string `" "'.
-
-The output from an entire `print' statement is called an "output
-record". Each `print' statement outputs one output record and then
-outputs a string called the "output record separator". The special
-variable `ORS' specifies this string. The initial value of the
-variable is the string `"\n"' containing a newline character; thus,
-normally each `print' statement makes a separate line.
-
-You can change how output fields and records are separated by
-assigning new values to the variables `OFS' and/or `ORS'. The usual
-place to do this is in the `BEGIN' rule (*note BEGIN/END::.), so that
-it happens before any input is processed. You may also do this with
-assignments on the command line, before the names of your input files.
-
-The following example prints the first and second fields of each
-input record separated by a semicolon, with a blank line added after
-each line:
-
- awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
- { print $1, $2 }' BBS-list
-
-If the value of `ORS' does not contain a newline, all your output
-will be run together on a single line, unless you output newlines
-some other way.
-
-
-
-File: gawk-info, Node: Redirection, Next: Printf, Prev: Output Separators, Up: Printing
-
-Redirecting Output of `print' and `printf'
-==========================================
-
-So far we have been dealing only with output that prints to the
-standard output, usually your terminal. Both `print' and `printf'
-can be told to send their output to other places. This is called
-"redirection".
-
-A redirection appears after the `print' or `printf' statement.
-Redirections in `awk' are written just like redirections in shell
-commands, except that they are written inside the `awk' program.
-
-Here are the three forms of output redirection. They are all shown
-for the `print' statement, but they work for `printf' also.
-
-`print ITEMS > OUTPUT-FILE'
- This type of redirection prints the items onto the output file
- OUTPUT-FILE. The file name OUTPUT-FILE can be any expression.
- Its value is changed to a string and then used as a filename
- (*note Expressions::.).
-
- When this type of redirection is used, the OUTPUT-FILE is erased
- before the first output is written to it. Subsequent writes do
- not erase OUTPUT-FILE, but append to it. If OUTPUT-FILE does
- not exist, then it is created.
-
- For example, here is how one `awk' program can write a list of
- BBS names to a file `name-list' and a list of phone numbers to a
- file `phone-list'. Each output file contains one name or number
- per line.
-
- awk '{ print $2 > "phone-list"
- print $1 > "name-list" }' BBS-list
-
-`print ITEMS >> OUTPUT-FILE'
- This type of redirection prints the items onto the output file
- OUTPUT-FILE. The difference between this and the single--`>'
- redirection is that the old contents (if any) of OUTPUT-FILE are
- not erased. Instead, the `awk' output is appended to the file.
-
-`print ITEMS | COMMAND'
- It is also possible to send output through a "pipe" instead of
- into a file. This type of redirection opens a pipe to COMMAND
- and writes the values of ITEMS through this pipe, to another
- process created to execute COMMAND.
-
- The redirection argument COMMAND is actually an `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:
-
- awk '{ print $1 > "names.unsorted"
- print $1 | "sort -r > names.sorted" }' BBS-list
-
- Here the unsorted list is written with an ordinary redirection
- while the sorted list is written by piping through the `sort'
- utility.
-
- Here is an example that uses redirection to mail a message to a
- mailing list `bug-system'. This might be useful when trouble is
- encountered in an `awk' script run periodically for system
- maintenance.
-
- print "Awk script failed:", $0 | "mail bug-system"
- print "processing record number", FNR, "of", FILENAME | "mail bug-system"
- close ("mail bug-system")
-
- We use a `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. *Note Close Output::, for more information on this.
-
-Redirecting output using `>', `>>', or `|' asks the system to open a
-file or pipe only if the particular FILE or COMMAND you've specified
-has not already been written to by your program.
-
-
-
-File: gawk-info, Node: Close Output, Up: Redirection
-
-Closing Output Files and Pipes
-------------------------------
-
-When a file or pipe is opened, the filename or command associated
-with it is remembered by `awk' and subsequent writes to the same file
-or command are appended to the previous writes. The file or pipe
-stays open until `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 `close' command, as follows:
-
- close (FILENAME)
-
-or
-
- close (COMMAND)
-
-The argument FILENAME or 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:
-
- print $1 | "sort -r > names.sorted"
-
-then you must close it with this:
-
- close ("sort -r > names.sorted")
-
-Here are some reasons why you might need to close an output file:
-
- * To write a file and read it back later on in the same `awk'
- program. Close the file when you are finished writing it; then
- you can start reading it with `getline' (*note Getline::.).
-
- * To write numerous files, successively, in the same `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.
-
- * 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 `mail' program, the
- message will not actually be sent until the pipe is closed.
-
- * 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 `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.
-
-
-
-File: gawk-info, Node: Printf, Prev: Redirection, Up: Printing
-
-Using `printf' Statements For Fancier Printing
-==============================================
-
-If you want more precise control over the output format than `print'
-gives you, use `printf'. With `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 "format string".
-
-* Menu:
-
-* Basic Printf:: Syntax of the `printf' statement.
-* Format-Control:: Format-control letters.
-* Modifiers:: Format--specification modifiers.
-* Printf Examples:: Several examples.
-
-
-
-File: gawk-info, Node: Basic Printf, Next: Format-Control, Up: Printf
-
-Introduction to the `printf' Statement
---------------------------------------
-
-The `printf' statement looks like this:
-
- printf FORMAT, ITEM1, ITEM2, ...
-
- The entire list of items may optionally be enclosed in parentheses.
-The parentheses are necessary if any of the item expressions uses a
-relational operator; otherwise it could be confused with a
-redirection (*note Redirection::.). The relational operators are
-`==', `!=', `<', `>', `>=', `<=', `~' and `!~' (*note Comparison
-Ops::.).
-
-The difference between `printf' and `print' is the argument 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 the
-"format string".
-
-The format string is essentially the same as in the C library
-function `printf'. Most of FORMAT is text to be output verbatim.
-Scattered among this text are "format specifiers", one per item.
-Each format specifier says to output the next item at that place in
-the format.
-
-The `printf' statement does not automatically append a newline to its
-output. It outputs nothing but what the format specifies. So if you
-want a newline, you must include one in the format. The output
-separator variables `OFS' and `ORS' have no effect on `printf'
-statements.
-
-
-
-File: gawk-info, Node: Format-Control, Next: Modifiers, Prev: Basic Printf, Up: Printf
-
-Format--Control Characters
---------------------------
-
-A format specifier starts with the character `%' and ends with a
-"format--control letter"; it tells the `printf' statement how to
-output one item. (If you actually want to output a `%', write `%%'.)
-The format--control letter specifies what kind of value to print.
-The rest of the format specifier is made up of optional "modifiers"
-which are parameters such as the field width to use.
-
-Here is a list of them:
-
-`c'
- This prints a number as an ASCII character. Thus, `printf "%c",
- 65' outputs the letter `A'. The output for a string value is
- the first character of the string.
-
-`d'
- This prints a decimal integer.
-
-`e'
- This prints a number in scientific (exponential) notation. For
- example,
-
- printf "%4.3e", 1950
-
- prints `1.950e+03', with a total of 4 significant figures of
- which 3 follow the decimal point. The `4.3' are "modifiers",
- discussed below.
-
-`f'
- This prints a number in floating point notation.
-
-`g'
- This prints either scientific notation or floating point
- notation, whichever is shorter.
-
-`o'
- This prints an unsigned octal integer.
-
-`s'
- This prints a string.
-
-`x'
- This prints an unsigned hexadecimal integer.
-
-`%'
- This isn't really a format--control letter, but it does have a
- meaning when used after a `%': the sequence `%%' outputs one
- `%'. It does not consume an argument.
-
-
-
-File: gawk-info, Node: Modifiers, Next: Printf Examples, Prev: Format-Control, Up: Printf
-
-Modifiers for `printf' Formats
-------------------------------
-
-A format specification can also include "modifiers" that can control
-how much of the item's value is printed and how much space it gets.
-The modifiers come between the `%' and the format--control letter.
-Here are the possible modifiers, in the order in which they may appear:
-
-`-'
- 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.
-
-`WIDTH'
- This is a number representing the desired width of a field.
- Inserting any number between the `%' 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.
-
-`.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.
-
-The C library `printf''s dynamic WIDTH and PREC capability (for
-example, `"%*.*s"') is not supported. However, it can be easily
-simulated using concatenation to dynamically build the format string.
-
-
-
-File: gawk-info, Node: Printf Examples, Prev: Modifiers, Up: Printf
-
-Examples of Using `printf'
---------------------------
-
-Here is how to use `printf' to make an aligned table:
-
- awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
-
-prints the names of bulletin boards (`$1') of the file `BBS-list' as
-a string of 10 characters, left justified. It also prints the phone
-numbers (`$2') afterward on the line. This will produce an aligned
-two--column table of names and phone numbers, like so:
-
- aardvark 555-5553
- alpo-net 555-3412
- barfly 555-7685
- bites 555-1675
- camelot 555-0542
- core 555-2912
- fooey 555-1234
- foot 555-6699
- macfoo 555-6480
- sdace 555-3430
- sabafoo 555-2127
-
-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 (*note
-BEGIN/END::.) to cause the header to be printed only once, at the
-beginning of the `awk' program:
-
- awk 'BEGIN { print "Name Number"
- print "--- -----" }
- { printf "%-10s %s\n", $1, $2 }' BBS-list
-
-Did you notice that we mixed `print' and `printf' statements in the
-above example? We could have used just `printf' statements to get
-the same results:
-
- awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
- printf "%-10s %s\n", "---", "-----" }
- { printf "%-10s %s\n", $1, $2 }' BBS-list
-
-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.
-
-The fact that the same format specification is used can be emphasized
-by storing it in a variable, like so:
-
- awk 'BEGIN { format = "%-10s %s\n"
- printf format, "Name", "Number"
- printf format, "---", "-----" }
- { printf format, $1, $2 }' BBS-list
-
-See if you can use the `printf' statement to line up the headings and
-table data for our `inventory-shipped' example covered earlier in the
-section on the `print' statement (*note Print::.).
-
-
-
-File: gawk-info, Node: One-liners, Next: Patterns, Prev: Printing, Up: Top
-
-Useful ``One-liners''
-*********************
-
-Useful `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 of the program will give you a good idea of what is going
-on, but please read the rest of the manual to become an `awk' expert!
-
-`awk '{ num_fields = num_fields + NF }'
-`` END { print num_fields }'''
- This program prints the total number of fields in all input lines.
-
-`awk 'length($0) > 80''
- This program prints every line longer than 80 characters. The
- sole rule has a relational expression as its pattern, and has no
- action (so the default action, printing the record, is used).
-
-`awk 'NF > 0''
- This program prints every line that has at least one field.
- This is an 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).
-
-`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.
-
-`awk 'BEGIN { for (i = 1; i <= 7; i++)'
-`` print int(101 * rand()) }'''
- This program prints 7 random numbers from 0 to 100, inclusive.
-
-`ls -l FILES | awk '{ x += $4 } ; END { print "total bytes: " x }''
- This program prints the total number of bytes used by FILES.
-
-`expand FILE | awk '{ if (x < length()) x = length() }'
-`` END { print "maximum line length is " x }'''
- This program prints the maximum line length of FILE. The input
- is piped through the `expand' program to change tabs into
- spaces, so the widths compared are actually the right--margin
- columns.
-
-
diff --git a/gawk-info-3 b/gawk-info-3
deleted file mode 100644
index b333f57c..00000000
--- a/gawk-info-3
+++ /dev/null
@@ -1,1385 +0,0 @@
-Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
-file gawk.texinfo.
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them.
-
-Copyright (C) 1989 Free Software Foundation, Inc.
-
-Permission is granted to make and distribute verbatim copies of this
-manual provided the copyright notice and this permission notice are
-preserved on all copies.
-
-Permission is granted to copy and distribute modified versions of
-this manual under the conditions for verbatim copying, provided that
-the entire resulting derived work is distributed under the terms of a
-permission notice identical to this one.
-
-Permission is granted to copy and distribute translations of this
-manual into another language, under the above conditions for modified
-versions, except that this permission notice may be stated in a
-translation approved by the Foundation.
-
-
-
-File: gawk-info, Node: Patterns, Next: Actions, Prev: One-liners, Up: Top
-
-Patterns
-********
-
-Patterns control the execution of rules: a rule is executed when its
-pattern matches the input record. The `awk' language provides
-several special patterns that are described in the sections that
-follow. Patterns include:
-
-NULL
- The empty pattern, which matches every input record. (*Note The
- Empty Pattern: Empty.)
-
-/REGULAR EXPRESSION/
- A regular expression as a pattern. It matches when the text of
- the input record fits the regular expression. (*Note Regular
- Expressions as Patterns: Regexp.)
-
-CONDEXP
- A single comparison expression. It matches when it is true.
- (*Note Comparison Expressions as Patterns: Comparison Patterns.)
-
-`BEGIN'
-`END'
- Special patterns to supply start--up or clean--up information to
- `awk'. (*Note Specifying Record Ranges With Patterns: BEGIN/END.)
-
-PAT1, PAT2
- A pair of patterns separated by a comma, specifying a range of
- records. (*Note Specifying Record Ranges With Patterns: Ranges.)
-
-CONDEXP1 BOOLEAN CONDEXP2
- A "compound" pattern, which combines expressions with the
- operators `and', `&&', and `or', `||'. (*Note Boolean
- Operators and Patterns: Boolean.)
-
-! CONDEXP
- The pattern CONDEXP is evaluated. Then the `!' performs a
- boolean ``not'' or logical negation operation; if the input line
- matches the pattern in CONDEXP then the associated action is
- *not* executed. If the input line did not match that pattern,
- then the action *is* executed. (*Note Boolean Operators and
- Patterns: Boolean.)
-
-(EXPR)
- Parentheses may be used to control how operators nest.
-
-PAT1 ? PAT2 : 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. (*Note Conditional Patterns: Conditional
- Patterns.)
-
-* Menu:
-
-The following subsections describe these forms in detail:
-
-* Empty:: The empty pattern, which matches every record.
-
-* Regexp:: Regular expressions such as `/foo/'.
-
-* Comparison Patterns:: Comparison expressions such as `$1 > 10'.
-
-* Boolean:: Combining comparison expressions.
-
-* Ranges:: Using pairs of patterns to specify record ranges.
-
-* BEGIN/END:: Specifying initialization and cleanup rules.
-
-* Conditional Patterns:: Patterns such as `pat1 ? pat2 : pat3'.
-
-
-
-File: gawk-info, Node: Empty, Next: Regexp, Up: Patterns
-
-The Empty Pattern
-=================
-
-An empty pattern is considered to match *every* input record. For
-example, the program:
-
- awk '{ print $1 }' BBS-list
-
-prints just the first field of every record.
-
-
-
-File: gawk-info, Node: Regexp, Next: Comparison Patterns, Prev: Empty, Up: Patterns
-
-Regular Expressions as Patterns
-===============================
-
-A "regular expression", or "regexp", is a way of describing classes
-of strings. When enclosed in slashes (`/'), it makes an `awk'
-pattern that matches every input record that contains a match for the
-regexp.
-
-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 `foo' matches any string containing `foo'. (More
-complicated regexps let you specify classes of similar strings.)
-
-* Menu:
-
-* Usage: Regexp Usage. How regexps are used in patterns.
-* Operators: Regexp Operators. How to write a regexp.
-
-
-
-File: gawk-info, Node: Regexp Usage, Next: Regexp Operators, Up: Regexp
-
-How to use Regular Expressions
-------------------------------
-
-When you enclose `foo' in slashes, you get a pattern that matches a
-record that contains `foo'. For example, this prints the second
-field of each record that contains `foo' anywhere:
-
- awk '/foo/ { print $2 }' BBS-list
-
-Regular expressions can also be used in comparison expressions. Then
-you can specify the string to match against; it need not be the
-entire current input record. These comparison expressions can be
-used as patterns or in `if' and `while' statements.
-
-`EXP ~ /REGEXP/'
- This is true if the expression EXP (taken as a character string)
- is matched by REGEXP. The following example matches, or
- selects, all input records with the letter `J' in the first field:
-
- awk '$1 ~ /J/' inventory-shipped
-
- So does this:
-
- awk '{ if ($1 ~ /J/) print }' inventory-shipped
-
-`EXP !~ /REGEXP/'
- This is true if the expression EXP (taken as a character string)
- is *not* matched by REGEXP. The following example matches, or
- selects, all input records whose first field *does not* contain
- the letter `J':
-
- awk '$1 !~ /J/' inventory-shipped
-
-The right hand side of a `~' or `!~' operator need not be a constant
-regexp (i.e. a string of characters between `/'s). It can also be
-"computed", or "dynamic". For example:
-
- identifier = "[A-Za-z_][A-Za-z_0-9]+"
- $0 ~ identifier
-
-sets `identifier' to a regexp that describes `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.
-
-
-
-File: gawk-info, Node: Regexp Operators, Prev: Regexp Usage, Up: Regexp
-
-Regular Expression Operators
-----------------------------
-
-You can combine regular expressions with the following characters,
-called "regular expression operators", or "metacharacters", to
-increase the power and versatility of regular expressions. This is a
-table of metacharacters:
-
-`\'
- This is used to suppress the special meaning of a character when
- matching. For example:
-
- \$
-
- matches the character `$'.
-
-`^'
- This matches the beginning of the string or the beginning of a
- line within the string. For example:
-
- ^@chapter
-
- matches the `@chapter' at the beginning of a string, and can be
- used to identify chapter beginnings in Texinfo source files.
-
-`$'
- This is similar to `^', but it matches only at the end of a
- string or the end of a line within the string. For example:
-
- /p$/
-
- as a pattern matches a record that ends with a `p'.
-
-`.'
- This matches any single character except a newline. For example:
-
- .P
-
- matches any single character followed by a `P' in a string.
- Using concatenation we can make regular expressions like `U.A',
- which matches any three--character string that begins with `U'
- and ends with `A'.
-
-`[...]'
- This is called a "character set". It matches any one of a group
- of characters that are enclosed in the square brackets. For
- example:
-
- [MVX]
-
- matches any of the characters `M', `V', or `X' in a string.
-
- Ranges of characters are indicated by using a hyphen between the
- beginning and ending characters, and enclosing the whole thing
- in brackets. For example:
-
- [0-9]
-
- matches any string that contains a digit.
-
- Note that special patterns have to be followed to match the
- characters, `]', `-', and `^' when they are enclosed in the
- square brackets. To match a `]', make it the first character in
- the set. For example:
-
- []d]
-
- matches either `]', or `d'.
-
- To match `-', write it as `--', which is a range containing only
- `-'. You may also make the `-' be the first or last character
- in the set. To match `^', make it any character except the
- first one of a set.
-
-`[^ ...]'
- This is the "complemented character set". The first character
- after the `[' *must* be a `^'. This matches any characters
- *except* those in the square brackets. For example:
-
- [^0-9]
-
- matches any characters that are not digits.
-
-`|'
- This is the "alternation operator" and it is used to specify
- alternatives. For example:
-
- ^P|[0-9]
-
- matches any string that matches either `^P' or `[0-9]'. This
- means it matches any string that contains a digit or starts with
- `P'.
-
-`(...)'
- Parentheses are used for grouping in regular expressions as in
- arithmetic. They can be used to concatenate regular expressions
- containing the alternation operator, `|'.
-
-`*'
- This symbol means that the preceding regular expression is to be
- repeated as many times as possible to find a match. For example:
-
- ph*
-
- applies the `*' symbol to the preceding `h' and looks for
- matches to one `p' followed by any number of `h''s. This will
- also match just `p' if no `h''s are present.
-
- The `*' means repeat the *smallest* possible preceding
- expression in order to find a match. The `awk' language
- processes a `*' by matching as many repetitions as can be found.
- For example:
-
- awk '/\(c[ad][ad]*r x\)/ { print }' sample
-
- matches every record in the input containing a string of the
- form `(car x)', `(cdr x)', `(cadr x)', and so on.
-
-`+'
- This symbol is similar to `*', but the preceding expression must
- be matched at least once. This means that:
-
- wh+y
-
- would match `why' and `whhy' but not `wy', whereas `wh*y' would
- match all three of these strings. And this is a simpler way of
- writing the last `*' example:
-
- awk '/\(c[ad]+r x\)/ { print }' sample
-
-`?'
- This symbol is similar to `*', but the preceding expression can
- be matched once or not at all. For example:
-
- fe?d
-
- will match `fed' or `fd', but nothing else.
-
-In regular expressions, the `*', `+', and `?' operators have the
-highest precedence, followed by concatenation, and finally by `|'.
-As in arithmetic, parentheses can change how operators are grouped.
-
-Any other character stands for itself. However, it is important to
-note that case in regular expressions *is* significant, both when
-matching ordinary (i.e. non--metacharacter) characters, and inside
-character sets. Thus a `w' in a regular expression matches only a
-lower case `w' and not either an uppercase or lowercase `w'. When
-you want to do a case--independent match, you have to use a character
-set: `[Ww]'.
-
-
-
-File: gawk-info, Node: Comparison Patterns, Next: Ranges, Prev: Regexp, Up: Patterns
-
-Comparison Expressions as Patterns
-==================================
-
-"Comparison patterns" use "relational operators" to compare strings
-or numbers. The relational operators are the same as in C. Here is
-a table of them:
-
-`X < Y'
- True if X is less than Y.
-
-`X <= Y'
- True if X is less than or equal to Y.
-
-`X > Y'
- True if X is greater than Y.
-
-`X >= Y'
- True if X is greater than or equal to Y.
-
-`X == Y'
- True if X is equal to Y.
-
-`X != Y'
- True if X is not equal to Y.
-
-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 "true".
-
-The operands of a relational operator are compared as numbers if they
-are both numbers. Otherwise they are converted to, and compared as,
-strings (*note Conversion::.). Strings are compared by comparing the
-first character of each, then the second character of each, and so on.
-Thus, `"10"' is less than `"9"'.
-
-The following example prints the second field of each input record
-whose first field is precisely `foo'.
-
- awk '$1 == "foo" { print $2 }' BBS-list
-
-Contrast this with the following regular expression match, which
-would accept any record with a first field that contains `foo':
-
- awk '$1 ~ "foo" { print $2 }' BBS-list
-
-
-
-File: gawk-info, Node: Ranges, Next: BEGIN/END, Prev: Comparison Patterns, Up: Patterns
-
-Specifying Record Ranges With Patterns
-======================================
-
-A "range pattern" is made of two patterns separated by a comma:
-`BEGPAT, ENDPAT'. It matches ranges of consecutive input records.
-The first pattern BEGPAT controls where the range begins, and the
-second one ENDPAT controls where it ends.
-
-They work as follows: BEGPAT is matched against every input record;
-when a record matches BEGPAT, the range pattern becomes "turned on".
-The range pattern matches this record. As long as it stays turned
-on, it automatically matches every input record read. But meanwhile,
-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 BEGPAT against each record. For example:
-
- awk '$1 == "on", $1 == "off"'
-
-prints every record between on/off pairs, inclusive.
-
-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
-these records, you can write `if' statements in the rule's action to
-distinguish them.
-
-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.
-
-
-
-File: gawk-info, Node: BEGIN/END, Next: Boolean, Prev: Ranges, Up: Patterns
-
-`BEGIN' and `END' Special Patterns
-==================================
-
-`BEGIN' and `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 `awk' script. A `BEGIN' rule is
-executed, once, before the first input record has been read. An
-`END' rule is executed, once, after all the input has been read. For
-example:
-
- awk 'BEGIN { print "Analysis of ``foo'' program" }
- /foo/ { ++foobar }
- END { print "``foo'' appears " foobar " times." }' BBS-list
-
-This program finds out how many times the string `foo' appears in the
-input file `BBS-list'. The `BEGIN' pattern prints out a title for
-the report. There is no need to use the `BEGIN' pattern to
-initialize the counter `foobar' to zero, as `awk' does this for us
-automatically (*note Variables::.). The second rule increments the
-variable `foobar' every time a record containing the pattern `foo' is
-read. The last rule prints out the value of `foobar' at the end of
-the run.
-
-The special patterns `BEGIN' and `END' do not combine with other
-kinds of patterns.
-
-An `awk' program may have multiple `BEGIN' and/or `END' rules. The
-contents of multiple `BEGIN' or `END' rules are treated as if they
-had been enclosed in a single rule, in the order that the rules are
-encountered in the `awk' program. (This feature was introduced with
-the new version of `awk'.)
-
-Multiple `BEGIN' and `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 `BEGIN' and
-`END' rules will be executed. Therefore you have to be careful how
-you write your library functions. (*Note Command Line::, for more
-information on using library functions.)
-
-If an `awk' program only has a `BEGIN' rule, and no other rules, then
-the program will exit after the `BEGIN' rule has been run. Older
-versions of `awk' used to read their input until end of file was
-seen. However, if an `END' rule exists as well, then the input will
-be read, even if there are no other rules in the program.
-
-`BEGIN' and `END' rules must have actions; there is no default action
-for these rules since there is no current record when they run.
-
-
-
-File: gawk-info, Node: Boolean, Next: Conditional Patterns, Prev: BEGIN/END, Up: Patterns
-
-Boolean Operators and Patterns
-==============================
-
-A boolean pattern is a combination of other patterns using the
-boolean operators ``or'' (`||'), ``and'' (`&&'), and ``not'' (`!'),
-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 `BEGIN' and `END', which never match any
-input record.
-
-Here are descriptions of the three boolean operators.
-
-`PAT1 && PAT2'
- Matches if both PAT1 and PAT2 match by themselves. For example,
- the following command prints all records in the input file
- `BBS-list' that contain both `2400' and `foo'.
-
- awk '/2400/ && /foo/' BBS-list
-
- Whether PAT2 matches is tested only if PAT1 succeeds. This can
- make a difference when PAT2 contains expressions that have side
- effects: in the case of `/foo/ && ($2 == bar++)', the variable
- `bar' is not incremented if there is no `foo' in the record.
-
-`PAT1 || PAT2'
- Matches if at least one of PAT1 and PAT2 matches the current
- input record. For example, the following command prints all
- records in the input file `BBS-list' that contain *either*
- `2400' or `foo', or both.
-
- awk '/2400/ || /foo/' BBS-list
-
- Whether PAT2 matches is tested only if PAT1 fails to match.
- This can make a difference when PAT2 contains expressions that
- have side effects.
-
-`!PAT'
- Matches if PAT does not match. For example, the following
- command prints all records in the input file `BBS-list' that do
- *not* contain the string `foo'.
-
- awk '! /foo/' BBS-list
-
-Note that boolean patterns are built from other patterns just as
-boolean expressions are built from other expressions (*note Boolean
-Ops::.). Any boolean expression is also a valid boolean pattern.
-But the converse is not true: simple regular expression patterns such
-as `/foo/' are not allowed in boolean expressions. Regular
-expressions can appear in boolean expressions only in conjunction
-with the matching operators, `~' and `!~'.
-
-
-
-File: gawk-info, Node: Conditional Patterns, Prev: Boolean, Up: Patterns
-
-Conditional Patterns
-====================
-
-Patterns may use a "conditional expression" much like the conditional
-expression of the C language. This takes the form:
-
- PAT1 ? PAT2 : PAT3
-
-The first pattern is evaluated. If it evaluates to TRUE, then the
-input record is tested against PAT2. Otherwise it is tested against
-PAT3. The conditional pattern matches if PAT2 or PAT3 (whichever one
-is selected) matches.
-
-
-
-File: gawk-info, Node: Actions, Next: Expressions, Prev: Patterns, Up: Top
-
-Actions: The Basics
-*******************
-
-The "action" part of an `awk' rule tells `awk' what to do once a
-match for the pattern is found. An action consists of one or more
-`awk' "statements", enclosed in curly braces (`{' and `}'). 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.
-
-Besides the print statements already covered (*note Printing::.),
-there are four kinds of action statements: expressions, control
-statements, compound statements, and function definitions.
-
- * "Expressions" include assignments, arithmetic, function calls,
- and more (*note Expressions::.).
-
- * "Control statements" specify the control flow of `awk' programs.
- The `awk' language gives you C--like constructs (`if', `for',
- `while', and so on) as well as a few special ones (*note
- Statements::.).
-
- * A "compound statement" is just one or more `awk' statements
- enclosed in curly braces. This way you can group several
- statements to form the body of an `if' or similar statement.
-
- * You can define "user--defined functions" for use elsewhere in
- the `awk' program (*note User-defined::.).
-
-
-
-File: gawk-info, Node: Expressions, Next: Statements, Prev: Actions, Up: Top
-
-Actions: Expressions
-********************
-
-Expressions are the basic building block of `awk' actions. An
-expression evaluates to a value, which you can print, test, store in
-a 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 `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 `$1' are also expressions.
-* Arrays:: Array element references are expressions.
-
-* Arithmetic Ops:: Arithmetic operations (`+', `-', etc.)
-* Concatenation:: Concatenating strings.
-* Comparison Ops:: Comparison of numbers and strings with `<', etc.
-* Boolean Ops:: Combining comparison expressions using boolean operators
- `||' (``or''), `&&' (``and'') and `!' (``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.
-* Function Calls:: A function call is an expression.
-
-
-
-File: gawk-info, Node: Constants, Next: Variables, Up: Expressions
-
-Constant Expressions
-====================
-
-There are two types of constants: numeric constants and string
-constants.
-
-The "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 `awk' in
-double--precision floating point. Here are some examples of numeric
-constants, which all have the same value:
-
- 105
- 1.05e+2
- 1050e-1
-
-A string constant consists of a sequence of characters enclosed in
-double--quote marks. For example:
-
- "parrot"
-
-represents the string constant `parrot'. Strings in `gawk' can be of
-any length and they can contain all the possible 8--bit ASCII
-characters including ASCII NUL. Other `awk' implementations may have
-difficulty with some character codes.
-
-Some characters cannot be included literally in a string. You
-represent them instead with "escape sequences", which are character
-sequences beginning with a backslash (`\').
-
-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 `\"'. Backslash itself is another character that can't be
-included normally; you write `\\' to put one backslash in the string.
-
-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 `awk' program, they may look ugly.
-
-`\b'
- Represents a backspaced, H'.
-
-`\f'
- Represents a formfeed, L'.
-
-`\n'
- Represents a newline, J'.
-
-`\r'
- Represents a carriage return, M'.
-
-`\t'
- Represents a horizontal tab, I'.
-
-`\v'
- Represents a vertical tab, K'.
-
-`\NNN'
- Represents the octal value NNN, where NNN is one to three digits
- between 0 and 7. For example, the code for the ASCII ESC
- (escape) character is `\033'.
-
-
-
-File: gawk-info, Node: Variables, Next: Arithmetic Ops, Prev: Constants, Up: Expressions
-
-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 must be a sequence of letters, digits and underscores, but
-it may not begin with a digit. Case is significant in variable
-names; `a' and `A' are distinct variables.
-
-A variable name is a valid expression by itself; it represents the
-variable's current value. Variables are given new values with
-"assignment operators" and "increment operators". *Note Assignment
-Ops::.
-
-A few variables have special built--in meanings, such as `FS', the
-field separator, and `NF', the number of fields in the current input
-record. *Note 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 `awk'. Each special
-variable's name is made entirely of upper case letters.
-
-Variables in `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 `awk', the way you would
-need to do in C or most other traditional programming languages.
-
-
-
-File: gawk-info, Node: Arithmetic Ops, Next: Concatenation, Prev: Variables, Up: Expressions
-
-Arithmetic Operators
-====================
-
-The `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:
-
- awk '{ $1 = $2 + $3 / $4; print }' inventory-shipped
-
-The arithmetic operators in `awk' are:
-
-`X + Y'
- Addition.
-
-`X - Y'
- Subtraction.
-
-`- X'
- Negation.
-
-`X / Y'
- Division. Since all numbers in `awk' are double--precision
- floating point, the result is not rounded to an integer: `3 / 4'
- has the value 0.75.
-
-`X * Y'
- Multiplication.
-
-`X % Y'
- Remainder. The quotient is rounded toward zero to an integer,
- multiplied by Y and this result is subtracted from X. This
- operation is sometimes known as ``trunc--mod''. The following
- relation always holds:
-
- `b * int(a / b) + (a % b) == a'
-
- One undesirable effect of this definition of remainder is that X
- % Y is negative if X is negative. Thus,
-
- -17 % 8 = -1
-
-`X ^ Y'
-`X ** Y'
- Exponentiation: X raised to the Y power. `2 ^ 3' has the value
- 8. The character sequence `**' is equivalent to `^'.
-
-
-
-File: gawk-info, Node: Concatenation, Next: Comparison Ops, Prev: Arithmetic Ops, Up: Expressions
-
-String 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:
-
- awk '{ print "Field number one: " $1 }' BBS-list
-
-produces, for the first record in `BBS-list':
-
- Field number one: aardvark
-
-If you hadn't put the space after the `:', the line would have run
-together. For example:
-
- awk '{ print "Field number one:" $1 }' BBS-list
-
-produces, for the first record in `BBS-list':
-
- Field number one:aardvark
-
-
-
-File: gawk-info, Node: Comparison Ops, Next: Boolean Ops, Prev: Concatenation, Up: Expressions
-
-Comparison Expressions
-======================
-
-"Comparison expressions" use "relational operators" to compare
-strings or numbers. The relational operators are the same as in C.
-Here is a table of them:
-
-`X < Y'
- True if X is less than Y.
-
-`X <= Y'
- True if X is less than or equal to Y.
-
-`X > Y'
- True if X is greater than Y.
-
-`X >= Y'
- True if X is greater than or equal to Y.
-
-`X == Y'
- True if X is equal to Y.
-
-`X != Y'
- True if X is not equal to Y.
-
-`X ~ REGEXP'
- True if regexp REGEXP matches the string X.
-
-`X !~ REGEXP'
- True if regexp REGEXP does not match the string X.
-
-`SUBSCRIPT in ARRAY'
- True if array ARRAY has an element with the subscript SUBSCRIPT.
-
-Comparison expressions have the value 1 if true and 0 if false.
-
-The operands of a relational operator are compared as numbers if they
-are both numbers. Otherwise they are converted to, and compared as,
-strings (*note Conversion::.). Strings are compared by comparing the
-first character of each, then the second character of each, and so on.
-Thus, `"10"' is less than `"9"'.
-
-For example,
-
- $1 == "foo"
-
-has the value of 1, or is true, if the first field of the current
-input record is precisely `foo'. By contrast,
-
- $1 ~ /foo/
-
-has the value 1 if the first field contains `foo'.
-
-
-
-File: gawk-info, Node: Boolean Ops, Next: Assignment Ops, Prev: Comparison Ops, Up: Expressions
-
-Boolean Operators
-=================
-
-A boolean expression is combination of comparison expressions or
-matching expressions, using the boolean operators ``or'' (`||'),
-``and'' (`&&'), and ``not'' (`!'), 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 `if' and `while'
-statements. They have numeric values (1 if true, 0 if false).
-
-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 (*note Boolean::.), which use
-the same boolean operators in patterns instead of expressions.
-
-`BOOLEAN1 && BOOLEAN2'
- True if both BOOLEAN1 and BOOLEAN2 are true. For example, the
- following statement prints the current input record if it
- contains both `2400' and `foo'.
-
- if ($0 ~ /2400/ && $0 ~ /foo/) print
-
- The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is
- true. This can make a difference when BOOLEAN2 contains
- expressions that have side effects: in the case of `$0 ~ /foo/
- && ($2 == bar++)', the variable `bar' is not incremented if
- there is no `foo' in the record.
-
-`BOOLEAN1 || BOOLEAN2'
- True if at least one of BOOLEAN1 and BOOLEAN2 is true. For
- example, the following command prints all records in the input
- file `BBS-list' that contain *either* `2400' or `foo', or both.
-
- awk '{ if ($0 ~ /2400/ || $0 ~ /foo/) print }' BBS-list
-
- The subexpression BOOLEAN2 is evaluated only if BOOLEAN1 is
- true. This can make a difference when BOOLEAN2 contains
- expressions that have side effects.
-
-`!BOOLEAN'
- True if BOOLEAN is false. For example, the following program
- prints all records in the input file `BBS-list' that do *not*
- contain the string `foo'.
-
- awk '{ if (! ($0 ~ /foo/)) print }' BBS-list
-
-
-
-File: gawk-info, Node: Assignment Ops, Next: Increment Ops, Prev: Boolean Ops, Up: Expressions
-
-Assignment Operators
-====================
-
-An "assignment" is an expression that stores a new value into a
-variable. For example, let's assign the value 1 to the variable `z':
-
- z = 1
-
-After this expression is executed, the variable `z' has the value 1.
-Whatever old value `z' had before the assignment is forgotten.
-
-The `=' sign is called an "assignment operator". It is the simplest
-assignment operator because the value of the right--hand operand is
-stored unchanged.
-
-The left--hand operand of an assignment can be a variable (*note
-Variables::.), a field (*note Changing Fields::.) or an array element
-(*note Arrays::.). These are all called "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 `"this food is good"' in the variable `message':
-
- thing = "food"
- predicate = "good"
- message = "this " thing " is " predicate
-
-(This also illustrates concatenation of strings.)
-
-It is important to note that variables do *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 `foo' has a numeric value at first, and a string value
-later on:
-
- foo = 1
- print foo
- foo = "bar"
- print foo
-
-When the second assignment gives `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, `z = 1' as an expression has the value 1.
-One consequence of this is that you can write multiple assignments
-together:
-
- x = y = z = 0
-
-stores the value 0 in all three variables. It does this because the
-value of `z = 0', which is 0, is stored into `y', and then the value
-of `y = z = 0', which is 0, is stored into `x'.
-
-You can use an assignment anywhere an expression is called for. For
-example, it is valid to write `x != (y = 1)' to set `y' to 1 and then
-test whether `x' equals 1. But this style tends to make 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 `=', there are several other assignment operators that do
-arithmetic with the old value of the variable. For example, the
-operator `+=' 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 `foo':
-
- foo += 5
-
-This is precisely equivalent to the following:
-
- 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 to a number.
-
-`LVALUE += INCREMENT'
- Adds INCREMENT to the value of LVALUE to make the new value of
- LVALUE.
-
-`LVALUE -= DECREMENT'
- Subtracts DECREMENT from the value of LVALUE.
-
-`LVALUE *= COEFFICIENT'
- Multiplies the value of LVALUE by COEFFICIENT.
-
-`LVALUE /= QUOTIENT'
- Divides the value of LVALUE by QUOTIENT.
-
-`LVALUE %= MODULUS'
- Sets LVALUE to its remainder by MODULUS.
-
-`LVALUE ^= POWER'
-`LVALUE **= POWER'
- Raises LVALUE to the power POWER.
-
-
-
-File: gawk-info, Node: Increment Ops, Next: Conversion, Prev: Assignment Ops, Up: Expressions
-
-Increment Operators
-===================
-
-"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 `awk' language; but they are
-convenient abbreviations for something very common.
-
-The operator to add 1 is written `++'. There are two ways to use
-this operator: pre--incrementation and post--incrementation.
-
-To pre--increment a variable V, write `++V'. This adds 1 to the
-value of V and that new value is also the value of this expression.
-The assignment expression `V += 1' is completely equivalent.
-
-Writing the `++' 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 *old*
-value. Thus, if `foo' has value 4, then the expression `foo++' has
-the value 4, but it changes the value of `foo' to 5.
-
-The post--increment `foo++' is nearly equivalent to writing `(foo +=
-1) - 1'. It is not perfectly equivalent because all numbers in `awk'
-are floating point: in floating point, `foo + 1 - 1' does not
-necessarily equal `foo'. But the difference will be 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 `--' works just like `++' except that it
-subtracts 1 instead of adding. Like `++', 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.
-
-`++LVALUE'
- This expression increments LVALUE and the new value becomes the
- value of this expression.
-
-`LVALUE++'
- This expression causes the contents of LVALUE to be incremented.
- The value of the expression is the *old* value of LVALUE.
-
-`--LVALUE'
- Like `++LVALUE', but instead of adding, it subtracts. It
- decrements LVALUE and delivers the value that results.
-
-`LVALUE--'
- Like `LVALUE++', but instead of adding, it subtracts. It
- decrements LVALUE. The value of the expression is the *old*
- value of LVALUE.
-
-
-
-File: gawk-info, Node: Conversion, Next: Conditional Exp, Prev: Increment Ops, Up: Expressions
-
-Conversion of Strings and Numbers
-=================================
-
-Strings are converted to numbers, and numbers to strings, if the
-context of your `awk' statement demands it. For example, if the
-values of `foo' or `bar' in the expression `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:
-
- two = 2; three = 3
- print (two three) + 4
-
-This eventually prints the (numeric) value `27'. The numeric
-variables `two' and `three' are converted to strings and concatenated
-together, and the resulting string is converted back to a number
-before adding `4'. The resulting numeric value `27' is printed.
-
-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.
-
-The exact manner in which numbers are converted into strings is
-controlled by the `awk' special variable `OFMT' (*note Special::.).
-Numbers are converted using a special version of the `sprintf'
-function (*note Built-in::.) with `OFMT' as the format specifier.
-
-`OFMT''s default value is `"%.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 `awk' uses double precision
-arithmetic. Double precision on most modern machines gives you 16 or
-17 decimal digits of precision.
-
-Strange results can happen if you set `OFMT' to a string that doesn't
-tell `sprintf' how to format floating point numbers in a useful way.
-For example, if you forget the `%' in the format, all numbers will be
-converted to the same constant string.
-
-
-
-File: gawk-info, Node: Conditional Exp, Next: Function Calls, Prev: Conversion, Up: Expressions
-
-Conditional Expressions
-=======================
-
-A "conditional expression" is a special kind of expression with three
-operands. It allows you to use one expression's value to select one
-of two other expressions.
-
-The conditional expression looks the same as in the C language:
-
- SELECTOR ? IF-TRUE-EXP : IF-FALSE-EXP
-
-There are three subexpressions. The first, SELECTOR, is always
-computed first. If it is ``true'' (not zero) then IF-TRUE-EXP is
-computed next and its value becomes the value of the whole expression.
-Otherwise, IF-FALSE-EXP is computed next and its value becomes the
-value of the whole expression.
-
-For example, this expression produces the absolute value of `x':
-
- x > 0 ? x : -x
-
-Each time the conditional expression is computed, exactly one of
-IF-TRUE-EXP and IF-FALSE-EXP is computed; the other is ignored. This
-is important when the expressions contain side effects. For example,
-this conditional expression examines element `i' of either array `a'
-or array `b', and increments `i'.
-
- x == y ? a[i++] : b[i++]
-
-This is guaranteed to increment `i' exactly once, because each time
-one or the other of the two increment expressions will be executed
-and the other will not be.
-
-
-
-File: gawk-info, Node: Function Calls, Prev: Conditional Exp, Up: Expressions
-
-Function Calls
-==============
-
-A "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
-example, the function `sqrt' computes the square root of a number.
-
-A fixed set of functions are "built in", which means they are
-available in every `awk' program. The `sqrt' function is one of
-these. *Note 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. *Note User-defined::,
-for how to do this.
-
-The way to use a function is with a "function call" expression, which
-consists of the function name followed by a list of "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 `()' after the function name.
-
-*Do not put any space between the function name and the
-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 function one day by mistake.
-
-Each function needs a particular number of arguments. For example,
-the `sqrt' function must be called with a single argument, like this:
-
- sqrt(ARGUMENT)
-
-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. *Note 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 (*note User-defined::.).
-
-Like every other expression, the function call has a value, which is
-computed by the function based on the arguments you give it. In this
-example, the value of `sqrt(ARGUMENT)' is the square root of the
-argument. A function can also have side effects, such as assigning
-the values of certain variables or doing I/O.
-
-Here is a command to read numbers, one number per line, and print the
-square root of each one:
-
- awk '{ print "The square root of", $1, "is", sqrt($1) }'
-
-
-
-File: gawk-info, Node: Statements, Next: Arrays, Prev: Expressions, Up: Top
-
-Actions: Statements
-*******************
-
-"Control statements" such as `if', `while', and so on control the
-flow of execution in `awk' programs. Most of the control statements
-in `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 `if' and `while', to
-distinguish them from simple expressions.
-
-In all the examples in this chapter, 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.
-
-* Menu:
-
-* Expressions:: One kind of statement simply computes an expression.
-
-* If:: Conditionally execute some `awk' statements.
-
-* While:: Loop until some condition is satisfied.
-
-* Do:: Do specified action while looping until some
- condition is satisfied.
-
-* For:: Another looping statement, that provides
- initialization and increment clauses.
-
-* Break:: Immediately exit the innermost enclosing loop.
-
-* Continue:: Skip to the end of the innermost enclosing loop.
-
-* Next:: Stop processing the current input record.
-
-* Exit:: Stop execution of `awk'.
-
-
-
-File: gawk-info, Node: If, Next: While, Up: Statements
-
-The `if' Statement
-==================
-
-The `if'-`else' statement is `awk''s decision--making statement. The
-`else' part of the statement is optional.
-
- `if (CONDITION) BODY1 else BODY2'
-
-Here CONDITION is an expression that controls what the rest of the
-statement will do. If CONDITION is true, BODY1 is executed;
-otherwise, BODY2 is executed (assuming that the `else' clause is
-present). The condition is considered true if it is nonzero or
-nonnull.
-
-Here is an example:
-
- awk '{ if (x % 2 == 0)
- print "x is even"
- else
- print "x is odd" }'
-
-In this example, if the statement containing `x' is found to be true
-(that is, x is divisible by 2), then the first `print' statement is
-executed, otherwise the second `print' statement is performed.
-
-If the `else' appears on the same line as BODY1, and BODY1 is a
-single statement, then a semicolon must separate BODY1 from `else'.
-To illustrate this, let's rewrite the previous example:
-
- awk '{ if (x % 2 == 0) print "x is even"; else
- print "x is odd" }'
-
-If you forget the `;', `awk' won't be able to parse it, 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 `else' if it were not the first thing on
-its line.
-
-
-
-File: gawk-info, Node: While, Next: Do, Prev: If, Up: Statements
-
-The `while' Statement
-=====================
-
-In programming, a loop means a part of a program that is (or at least
-can be) executed two or more times in succession.
-
-The `while' statement is the simplest looping statement in `awk'. It
-repeatedly executes a statement as long as a condition is true. It
-looks like this:
-
- while (CONDITION)
- BODY
-
-Here BODY is a statement that we call the "body" of the loop, and
-CONDITION is an expression that controls how long the loop keeps
-running.
-
-The first thing the `while' statement does is test CONDITION. If
-CONDITION is true, it executes the statement BODY. After BODY has
-been executed, CONDITION is tested again and this process is repeated
-until CONDITION is no longer true. If CONDITION is initially false,
-the body of the loop is never executed.
-
- awk '{ i = 1
- while (i <= 3) {
- print $i
- i++
- }
- }'
-
-This example prints the first three input fields, one per line.
-
-The loop works like this: first, the value of `i' is set to 1. Then,
-the `while' tests whether `i' is less than or equal to three. This
-is the case when `i' equals one, so the `i'-th field is printed.
-Then the `i++' increments the value of `i' and the loop repeats.
-
-When `i' reaches 4, the loop exits. Here 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.
-
-
-
-File: gawk-info, Node: Do, Next: For, Prev: While, Up: Statements
-
-The `do'--`while' Statement
-===========================
-
-The `do' loop is a variation of the `while' looping statement. The
-`do' loop executes the BODY once, then repeats BODY as long as
-CONDITION is true. It looks like this:
-
- do
- BODY
- while (CONDITION)
-
-Even if CONDITION is false at the start, BODY is executed at least
-once (and only once, unless executing BODY makes CONDITION true).
-Contrast this with the corresponding `while' statement:
-
- while (CONDITION)
- BODY
-
-This statement will not execute BODY even once if CONDITION is false
-to begin with.
-
-Here is an example of a `do' statement:
-
- awk '{ i = 1
- do {
- print $0
- i++
- } while (i <= 10)
- }'
-
-prints each input record ten times. It isn't a very realistic
-example, since in this case an ordinary `while' would do just as
-well. But this is normal; there is only occasionally a real use for
-a `do' statement.
-
-
diff --git a/gawk-info-4 b/gawk-info-4
deleted file mode 100644
index c8e9b7ee..00000000
--- a/gawk-info-4
+++ /dev/null
@@ -1,1400 +0,0 @@
-Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
-file gawk.texinfo.
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them.
-
-Copyright (C) 1989 Free Software Foundation, Inc.
-
-Permission is granted to make and distribute verbatim copies of this
-manual provided the copyright notice and this permission notice are
-preserved on all copies.
-
-Permission is granted to copy and distribute modified versions of
-this manual under the conditions for verbatim copying, provided that
-the entire resulting derived work is distributed under the terms of a
-permission notice identical to this one.
-
-Permission is granted to copy and distribute translations of this
-manual into another language, under the above conditions for modified
-versions, except that this permission notice may be stated in a
-translation approved by the Foundation.
-
-
-
-File: gawk-info, Node: For, Next: Break, Prev: Do, Up: Statements
-
-The `for' Statement
-===================
-
-The `for' statement makes it more convenient to count iterations of a
-loop. The general form of the `for' statement looks like this:
-
- for (INITIALIZATION; CONDITION; INCREMENT)
- BODY
-
-This statement starts by executing INITIALIZATION. Then, as long as
-CONDITION is true, it repeatedly executes BODY and then INCREMENT.
-Typically INITIALIZATION sets a variable to either zero or one,
-INCREMENT adds 1 to it, and CONDITION compares it against the desired
-number of iterations.
-
-Here is an example of a `for' statement:
-
- awk '{ for (i = 1; i <= 3; i++)
- print $i
- }'
-
-This prints the first three fields of each input record, one field
-per line.
-
-In the `for' statement, BODY stands for any statement, but
-INITIALIZATION, CONDITION and INCREMENT are just expressions. You
-cannot set more than one variable in the INITIALIZATION part unless
-you use a multiple assignment statement such as `x = y = 0', which is
-possible only if all the initial values are equal. (But you can
-initialize additional variables by writing their assignments as
-separate statements preceding the `for' loop.)
-
-The same is true of the INCREMENT part; to increment additional
-variables, you must write separate statements at the end of the loop.
-The C compound expression, using C's comma operator, would be useful
-in this context, but it is not supported in `awk'.
-
-Most often, 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:
-
- # print odd numbers from 1 to 100
- for (i = 1; i <= 100; i += 2)
- print i
-
-Any of the three expressions following `for' may be omitted if you
-don't want it to do anything. Thus, `for (;x > 0;)' is equivalent to
-`while (x > 0)'. If the CONDITION part is empty, it is treated as
-TRUE, effectively yielding an infinite loop.
-
-In most cases, a `for' loop is an abbreviation for a `while' loop, as
-shown here:
-
- INITIALIZATION
- while (CONDITION) {
- BODY
- INCREMENT
- }
-
-(The only exception is when the `continue' statement (*note
-Continue::.) is used inside the loop; changing a `for' statement to a
-`while' statement in this way can change the effect of the `continue'
-statement inside the loop.)
-
-The `awk' language has a `for' statement in addition to a `while'
-statement because often a `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 `for' loops.
-
-There is an alternate version of the `for' loop, for iterating over
-all the indices of an array:
-
- for (i in array)
- PROCESS array[i]
-
-*Note Arrays::, for more information on this version of the `for' loop.
-
-
-
-File: gawk-info, Node: Break, Next: Continue, Prev: For, Up: Statements
-
-The `break' Statement
-=====================
-
-The `break' statement jumps out of the innermost `for', `while', or
-`do'--`while' loop that encloses it. The following example finds the
-smallest divisor of any number, and also identifies prime numbers:
-
- awk '# find smallest divisor of num
- { num = $1
- for (div = 2; div*div <= num; div++)
- if (num % div == 0)
- break
- if (num % div == 0)
- printf "Smallest divisor of %d is %d\n", num, div
- else
- printf "%d is prime\n", num }'
-
-When the remainder is zero in the first `if' statement, `awk'
-immediately "breaks" out of the containing `for' loop. This means
-that `awk' proceeds immediately to the statement following the loop
-and continues processing. (This is very different from the `exit'
-statement (*note Exit::.) which stops the entire `awk' program.)
-
-Here is another program equivalent to the previous one. It
-illustrates how the CONDITION of a `for' or `while' could just as
-well be replaced with a `break' inside an `if':
-
- awk '# find smallest divisor of num
- { num = $1
- for (div = 2; ; div++) {
- if (num % div == 0) {
- printf "Smallest divisor of %d is %d\n", num, div
- break
- }
- if (div*div > num) {
- printf "%d is prime\n", num
- break
- }
- }
- }'
-
-
-
-File: gawk-info, Node: Continue, Next: Next, Prev: Break, Up: Statements
-
-The `continue' Statement
-========================
-
-The `continue' statement, like `break', is used only inside `for',
-`while', and `do'--`while' loops. It skips over the rest of the loop
-body, causing the next cycle around the loop to begin immediately.
-Contrast this with `break', which jumps out of the loop altogether.
-Here is an example:
-
- # print names that don't contain the string "ignore"
-
- # first, save the text of each line
- { names[NR] = $0 }
-
- # print what we're interested in
- END {
- for (x in names) {
- if (names[x] ~ /ignore/)
- continue
- print names[x]
- }
- }
-
-If any of the input records contain the string `ignore', this example
-skips the print statement and continues back to the first statement
-in the loop.
-
-This isn't a practical example of `continue', since it would be just
-as easy to write the loop like this:
-
- for (x in names)
- if (x !~ /ignore/)
- print x
-
-The `continue' statement causes `awk' to skip the rest of what is
-inside a `for' loop, but it resumes execution with the increment part
-of the `for' loop. The following program illustrates this fact:
-
- awk 'BEGIN {
- for (x = 0; x <= 20; x++) {
- if (x == 5)
- continue
- printf ("%d ", x)
- }
- print ""
- }'
-
-This program prints all the numbers from 0 to 20, except for 5, for
-which the `printf' is skipped. Since the increment `x++' is not
-skipped, `x' does not remain stuck at 5.
-
-
-
-File: gawk-info, Node: Next, Next: Exit, Prev: Continue, Up: Statements
-
-The `next' Statement
-====================
-
-The `next' statement forces `awk' to immediately stop processing the
-current record and go on to the next record. This means that no
-further rules are executed for the current record. The rest of the
-current rule's action is not executed either.
-
-Contrast this with the effect of the `getline' function (*note
-Getline::.). That too causes `awk' to read the next record
-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, `awk' program execution is a loop that reads
-an input record and then tests each rule pattern against it. If you
-think of this loop as a `for' statement whose body contains the
-rules, then the `next' statement is analogous to a `continue'
-statement: it skips to the end of the body of the loop, and executes
-the increment (which reads another record).
-
-For example, if your `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:
-
- NF != 4 {
- printf ("line %d skipped: doesn't have 4 fields", FNR) > "/dev/tty"
- next
- }
-
-so that the following rules will not see the bad record. The error
-message is redirected to `/dev/tty' (the terminal), so that it won't
-get lost amid the rest of the program's regular output.
-
-
-
-File: gawk-info, Node: Exit, Prev: Next, Up: Statements
-
-The `exit' Statement
-====================
-
-The `exit' statement causes `awk' to immediately stop executing the
-current rule and to stop processing input; any remaining input is
-ignored.
-
-If an `exit' statement is executed from a `BEGIN' rule the program
-stops processing everything immediately. No input records will be
-read. However, if an `END' rule is present, it will be executed
-(*note BEGIN/END::.).
-
-If `exit' is used as part of an `END' rule, it causes the program to
-stop immediately.
-
-An `exit' statement that is part an ordinary rule (that is, not part
-of a `BEGIN' or `END' rule) stops the execution of any further
-automatic rules, but the `END' rule is executed if there is one. If
-you don't want the `END' rule to do its job in this case, you can set
-a variable to nonzero before the `exit' statement, and check that
-variable in the `END' rule.
-
-If an argument is supplied to `exit', its value is used as the exit
-status code for the `awk' process. If no argument is supplied,
-`exit' returns status zero (success).
-
-For example, let's say you've discovered an error condition you
-really don't know how to handle. Conventionally, programs report
-this by exiting with a nonzero status. Your `awk' program can do
-this using an `exit' statement with a nonzero argument. Here's an
-example of this:
-
- BEGIN {
- if (("date" | getline date_now) < 0) {
- print "Can't get system date"
- exit 4
- }
- }
-
-
-
-File: gawk-info, Node: Arrays, Next: Built-in, Prev: Statements, Up: Top
-
-Actions: Using Arrays in `awk'
-******************************
-
-An "array" is a table of various values, called "elements". The
-elements of an array are distinguished by their "indices". Names of
-arrays in `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 `awk' program.
-
-* Menu:
-
-* Intro: Array Intro. Basic facts abou arrays in `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.
-
-* Scanning an Array:: A variation of the `for' statement. It loops
- through the indices of an array's existing elements.
-
-* Delete:: The `delete' statement removes an element from an array.
-
-* Multi-dimensional:: Emulating multi--dimensional arrays in `awk'.
-* Multi-scanning:: Scanning multi--dimensional arrays.
-
-
-
-File: gawk-info, Node: Array Intro, Next: Reference to Elements, Up: Arrays
-
-Introduction to Arrays
-======================
-
-The `awk' language has one--dimensional "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 `awk' program.
-
-Arrays in `awk' superficially resemble arrays in other programming
-languages; but there are fundamental differences. In `awk', you
-don't need to declare the size of an array before you start to use it.
-What's more, in `awk' any number or even a string may be used as an
-array index.
-
-In most other languages, you have to "declare" an array and specify
-how many elements or components it has. In such languages, the
-declaration causes a contiguous block of memory to be allocated for
-that many elements. An index in the array must be a positive
-integer; for example, the index 0 specifies the first element in the
-array, which is 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, `"foo"', `""' and 30:
-
- +--------+--------+-------+--------+
- | 8 | "foo" | "" | 30 | value
- +--------+--------+-------+--------+
- 0 1 2 3 index
-
-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.
-
-Arrays in `awk' are different: they are "associative". This means
-that each array is a collection of pairs: an index, and its
-corresponding array element value:
-
- Element 4 Value 30
- Element 2 Value "foo"
- Element 1 Value 8
- Element 3 Value ""
-
-We have shown the pairs in jumbled order because their order doesn't
-mean anything.
-
-One advantage of an associative array is that new pairs can be added
-at any time. For example, suppose we add to that array a tenth
-element whose value is `"number ten"'. The result is this:
-
- Element 10 Value "number ten"
- Element 4 Value 30
- Element 2 Value "foo"
- Element 1 Value 8
- Element 3 Value ""
-
-Now the array is "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.
-
-Another consequence of associative arrays is that the indices don't
-have to be positive integers. Any number, or even a string, can be
-an index. For example, here is an array which translates words from
-English into French:
-
- Element "dog" Value "chien"
- Element "cat" Value "chat"
- Element "one" Value "un"
- Element 1 Value "un"
-
-Here we decided to translate the number 1 in both spelled--out and
-numeral form--thus illustrating that a single array can have both
-numbers and strings as indices.
-
-When `awk' creates an array for you, e.g. with the `split' built--in
-function (*note String Functions::.), that array's indices start at
-the number one.
-
-
-
-File: gawk-info, Node: Reference to Elements, Next: Assigning Elements, Prev: Array Intro, Up: Arrays
-
-Referring to an Array Element
-=============================
-
-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:
-
- ARRAY[INDEX]
-
-Here ARRAY is the name of an array. The expression 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.
-
-For example, `foo[4.3]' is an expression for the element of array
-`foo' at index 4.3.
-
-If you refer to an array element that has no recorded value, the
-value of the reference is `""', the null string. This includes
-elements to which you have not assigned any value, and elements that
-have been deleted (*note 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
-`awk').
-
-You can find out if an element exists in an array at a certain index
-with the expression:
-
- INDEX in ARRAY
-
-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 `ARRAY[SUBSCRIPT]' exists,
-and 0 (false) if it does not exist.
-
-For example, to find out whether the array `frequencies' contains the
-subscript `"2"', you would ask:
-
- if ("2" in frequencies) print "Subscript \"2\" is present."
-
-Note that this is *not* a test of whether or not the array
-`frequencies' contains an element whose *value* is `"2"'. (There is
-no way to that except to scan all the elements.) Also, this *does
-not* create `frequencies["2"]', while the following (incorrect)
-alternative would:
-
- if (frequencies["2"] != "") print "Subscript \"2\" is present."
-
-
-
-File: gawk-info, Node: Assigning Elements, Next: Array Example, Prev: Reference to Elements, Up: Arrays
-
-Assigning Array Elements
-========================
-
-Array elements are lvalues: they can be assigned values just like
-`awk' variables:
-
- ARRAY[SUBSCRIPT] = VALUE
-
-Here ARRAY is the name of your array. The expression SUBSCRIPT is
-the index of the element of the array that you want to assign a
-value. The expression VALUE is the value you are assigning to that
-element of the array.
-
-
-
-File: gawk-info, Node: Array Example, Next: Scanning an Array, Prev: Assigning Elements, Up: Arrays
-
-Basic Example of an Array
-=========================
-
-The following program takes a list of lines, each beginning with a
-line 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 numbers, gaps, or lines that
-don't begin with a number.
-
- BEGIN {
- max=0
- }
-
- {
- if ($1 > max)
- max = $1
- arr[$1] = $0
- }
-
- END {
- for (x = 1; x <= max; x++)
- print arr[x]
- }
-
-The first rule just initializes the variable `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.)
-
-The second rule keeps track of the largest line number seen so far;
-it also stores each line into the array `arr', at an index that is
-the line's number.
-
-The third rule runs after all the input has been read, to print out
-all the lines.
-
-When this program is run with the following input:
-
- 5 I am the Five man
- 2 Who are you? The new number two!
- 4 . . . And four on the floor
- 1 Who is number one?
- 3 I three you.
-
- its output is this:
-
- 1 Who is number one?
- 2 Who are you? The new number two!
- 3 I three you.
- 4 . . . And four on the floor
- 5 I am the Five man
-
-
-
-File: gawk-info, Node: Scanning an Array, Next: Delete, Prev: Array Example, Up: Arrays
-
-Scanning All Elements of an Array
-=================================
-
-In programs that use arrays, often you need a loop that will execute
-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 find all the valid indices by counting from zero up to that
-value. This technique won't do the job in `awk', since any number or
-string may be an array index. So `awk' has a special kind of `for'
-statement for scanning an array:
-
- for (VAR in ARRAY)
- BODY
-
-This loop executes BODY once for each different value that your
-program has previously used as an index in ARRAY, with the variable
-VAR set to that index.
-
-Here is a program that uses this form of the `for' statement. The
-first rule scans the input records and notes which words appear (at
-least once) in the input, by storing a 1 into the array `used' with
-the word as index. The second rule scans the elements of `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. *Note Built-in::, for more information on the
-built--in function `length'.
-
- # Record a 1 for each word that is used at least once.
- {
- for (i = 0; i < NF; i++)
- used[$i] = 1
- }
-
- # Find number of distinct words more than 10 characters long.
- END {
- num_long_words = 0
- for (x in used)
- if (length(x) > 10) {
- ++num_long_words
- print x
- }
- print num_long_words, "words longer than 10 characters"
- }
-
-*Note Sample Program::, for a more detailed example of this type.
-
-The order in which elements of the array are accessed by this
-statement is determined by the internal arrangement of the array
-elements within `awk' and cannot be controlled or changed. This can
-lead to problems if new elements are added to ARRAY by statements in
-BODY; you cannot predict whether or not the `for' loop will reach
-them. Similarly, changing VAR inside the loop can produce strange
-results. It is best to avoid such things.
-
-
-
-File: gawk-info, Node: Delete, Next: Multi-dimensional, Prev: Scanning an Array, Up: Arrays
-
-The `delete' Statement
-======================
-
-You can remove an individual element of an array using the `delete'
-statement:
-
- delete ARRAY[INDEX]
-
-When an array element is deleted, it is as if you had never referred
-to it and had never given it any value. Any value the element
-formerly had can no longer be obtained.
-
-Here is an example of deleting elements in an array:
-
- awk '{ for (i in frequencies)
- delete frequencies[i]
- }'
-
-This example removes all the elements from the array `frequencies'.
-
-If you delete an element, the `for' statement to scan the array will
-not report that element, and the `in' operator to check for the
-presence of that element will return 0:
-
- delete foo[4]
- if (4 in foo)
- print "This will never be printed"
-
-
-
-File: gawk-info, Node: Multi-dimensional, Next: Multi-scanning, Prev: Delete, Up: Arrays
-
-Multi--dimensional arrays
-=========================
-
-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 languages, including `awk') to refer to an element of a
-two--dimensional array named `grid' is with `grid[x,y]'.
-
-Multi--dimensional arrays are supported in `awk' through
-concatenation of indices into one string. What happens is that `awk'
-converts the indices into strings (*note 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 variable `SUBSEP'.
-
-For example, suppose the value of `SUBSEP' is `","' and the
-expression `foo[5,12]="value"' is executed. The numbers 5 and 12
-will be concatenated with a comma between them, yielding `"5,12"';
-thus, the array element `foo["5,12"]' will be set to `"value"'.
-
-Once the element's value is stored, `awk' has no record of whether it
-was stored with a single index or a sequence of indices. The two
-expressions `foo[5,12]' and `foo[5 SUBSEP 12]' always have the same
-value.
-
-The default value of `SUBSEP' is not a comma; it is the string
-`"\034"', which contains a nonprinting character that is unlikely to
-appear in an `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 `SUBSEP' lead to
-combined strings that are ambiguous. Suppose that `SUBSEP' is a
-comma; then `foo["a,b", "c"]' and `foo["a", "b,c"]' will be
-indistinguishable because both are actually stored as `foo["a,b,c"]'.
-Because `SUBSEP' is `"\034"', such confusion can actually happen only
-when an index contains the character `"\034"', which is a rare event.
-
-You can test whether a particular index--sequence exists in a
-``multi--dimensional'' array with the same operator `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:
-
- (SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY
-
-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.
-
- awk 'BEGIN {
- max_nf = max_nr = 0
- }
-
- {
- if (max_nf < NF)
- max_nf = NF
- max_nr = NR
- for (x = 1; x <= NF; x++)
- vector[x, NR] = $x
- }
-
- END {
- for (x = 1; x <= max_nf; x++) {
- for (y = max_nr; y >= 1; --y)
- printf("%s ", vector[x, y])
- printf("\n")
- }
- }'
-
-When given the input:
-
- 1 2 3 4 5 6
- 2 3 4 5 6 1
- 3 4 5 6 1 2
- 4 5 6 1 2 3
-
-it produces:
-
- 4 3 2 1
- 5 4 3 2
- 6 5 4 3
- 1 6 5 4
- 2 1 6 5
- 3 2 1 6
-
-
-
-File: gawk-info, Node: Multi-scanning, Prev: Multi-dimensional, Up: Arrays
-
-Scanning Multi--dimensional Arrays
-==================================
-
-There is no special `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 *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 the scanning `for' statement (*note Scanning an Array::.)
-with the `split' built--in function (*note String Functions::.). It
-works like this:
-
- for (combined in ARRAY) {
- split (combined, separate, SUBSEP)
- ...
- }
-
-This finds each concatenated, combined index in the array, and splits
-it into the individual indices by breaking it apart where the value
-of `SUBSEP' appears. The split--out indices become the elements of
-the array `separate'.
-
-Thus, suppose you have previously stored in `ARRAY[1, "foo"]'; then
-an element with index `"1\034foo"' exists in ARRAY. (Recall that the
-default value of `SUBSEP' contains the character with code 034.)
-Sooner or later the `for' statement will find that index and do an
-iteration with `combined' set to `"1\034foo"'. Then the `split'
-function will be called as follows:
-
- split ("1\034foo", separate, "\034")
-
-The result of this is to set `separate[1]' to 1 and `separate[2]' to
-`"foo"'. Presto, the original sequence of separate indices has been
-recovered.
-
-
-
-File: gawk-info, Node: Built-in, Next: User-defined, Prev: Arrays, Up: Top
-
-Built--in functions
-*******************
-
-"Built--in" functions are functions always available for your `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 new
-functions yourself. *Note 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:
-
- i = 4
- j = myfunc(i++)
-
-the variable `i' will be set to 5 before `myfunc' is called with a
-value of 4 for its actual parameter.
-
-* Menu:
-
-* Numeric Functions:: Functions that work with numbers,
- including `int', `sin' and `rand'.
-
-* String Functions:: Functions for string manipulation,
- such as `split', `match', and `sprintf'.
-
-* I/O Functions:: Functions for files and shell commands
-
-
-
-File: gawk-info, Node: Numeric Functions, Next: String Functions, Up: Built-in
-
-Numeric Built--in Functions
-===========================
-
-The general syntax of the numeric built--in functions is the same for
-each. Here is an example of that syntax:
-
- 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)) }'
-
-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.
-
-Here is the full list of numeric built--in functions:
-
-`int(X)'
- This gives you the integer part of X, truncated toward 0. This
- produces the nearest integer to X, located between X and 0.
-
- For example, `int(3)' is 3, `int(3.9)' is 3, `int(-3.9)' is -3,
- and `int(-3)' is -3 as well.
-
-`sqrt(X)'
- This gives you the positive square root of X. It reports an
- error if X is negative.
-
-`exp(X)'
- This gives you the exponential of X, or reports an error if X is
- out of range. The range of values X can have depends on your
- machine's floating point representation.
-
-`log(X)'
- This gives you the natural logarithm of X, if X is positive;
- otherwise, it reports an error.
-
-`sin(X)'
- This gives you the sine of X, with X in radians.
-
-`cos(X)'
- This gives you the cosine of X, with X in radians.
-
-`atan2(Y, X)'
- This gives you the arctangent of Y/X, with both in radians.
-
-`rand()'
- This gives you a random number. The values of `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 you can use to obtain a random nonnegative integer less
- than N:
-
- function randint(n) {
- return int(n * rand())
- }
-
- The multiplication produces a random real number at least 0, and
- less than N. We then make it an integer (using `int') between 0
- and `N-1'.
-
- Here is an example where a similar function is used to produce
- random integers between 1 and N:
-
- 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.
- {
- printf("%d points\n", roll(6)+roll(6)+roll(6))
- }'
-
- *Note* that `rand()' starts generating numbers from the same
- point, or "seed", each time you run `awk'. This means that the
- same program will produce the same results each time you run it.
- The numbers are random within one `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 the seed to a value that will be different in each
- run. To do this, use `srand'.
-
-`srand(X)'
- The function `srand(X)' sets the starting point, or "seed", for
- generating random numbers to the value X.
-
- Each seed value leads to a particular sequence of ``random''
- numbers. Thus, if you set the seed to the same value a second
- time, you will get the same sequence of ``random'' numbers again.
-
- If you omit the argument X, as in `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 `srand()' is the previous seed. This makes
- it easy to keep track of the seeds for use in consistently
- reproducing sequences of random numbers.
-
-
-
-File: gawk-info, Node: String Functions, Next: I/O Functions, Prev: Numeric Functions, Up: Built-in
-
-Built--in Functions for String Manipulation
-===========================================
-
-`index(IN, FIND)'
- This searches the string IN for the first occurrence of the
- string FIND, and returns the position where that occurrence
- begins in the string IN. For example:
-
- awk 'BEGIN { print index("peanut", "an") }'
-
- prints `3'. If FIND is not found, `index' returns 0.
-
-`length(STRING)'
- This gives you the number of characters in STRING. If STRING is
- a number, the length of the digit string representing that
- number is returned. For example, `length("abcde")' is 5.
- Whereas, `length(15 * 35)' works out to 3. How? Well, 15 * 35
- = 525, and 525 is then converted to the string `"525"', which
- has three characters.
-
-`match(STRING, REGEXP)'
- The `match' function searches the string, STRING, for the
- longest, leftmost substring matched by the regular expression,
- REGEXP. It returns the character position, or "index", of where
- that substring begins (1, if it starts at the beginning of
- STRING). If no match if found, it returns 0.
-
- The `match' function sets the special variable `RSTART' to the
- index. It also sets the special variable `RLENGTH' to the
- length of the matched substring. If no match is found, `RSTART'
- is set to 0, and `RLENGTH' to -1.
-
- For example:
-
- awk '{
- if ($1 == "FIND")
- regex = $2
- else {
- where = match($0, regex)
- if (where)
- print "Match of", regex, "found at", where, "in", $0
- }
- }'
-
- This program looks for lines that match the regular expression
- stored in the variable `regex'. This regular expression can be
- changed. If the first word on a line is `FIND', `regex' is
- changed to be the second word on that line. Therefore, given:
-
- FIND fo*bar
- My program was a foobar
- 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.
-
- `awk' prints:
-
- 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.
-
-`split(STRING, ARRAY, FIELD_SEPARATOR)'
- This divides STRING up into pieces separated by FIELD_SEPARATOR,
- and stores the pieces in ARRAY. The first piece is stored in
- `ARRAY[1]', the second piece in `ARRAY[2]', and so forth. The
- string value of the third argument, FIELD_SEPARATOR, is used as
- a regexp to search for to find the places to split STRING. If
- the FIELD_SEPARATOR is omitted, the value of `FS' is used.
- `split' returns the number of elements created.
-
- The `split' function, then, splits strings into pieces in a
- manner similar to the way input lines are split into fields.
- For example:
-
- split("auto-da-fe", a, "-")
-
- splits the string `auto-da-fe' into three fields using `-' as
- the separator. It sets the contents of the array `a' as follows:
-
- a[1] = "auto"
- a[2] = "da"
- a[3] = "fe"
-
- The value returned by this call to `split' is 3.
-
-`sprintf(FORMAT, EXPRESSION1,...)'
- This returns (without printing) the string that `printf' would
- have printed out with the same arguments (*note Printf::.). For
- example:
-
- sprintf("pi = %.2f (approx.)", 22/7)
-
- returns the string `"pi = 3.14 (approx.)"'.
-
-`sub(REGEXP, REPLACEMENT_STRING, TARGET_VARIABLE)'
- The `sub' function alters the value of TARGET_VARIABLE. It
- searches this value, which should be a string, for the leftmost
- substring matched by the regular expression, REGEXP, extending
- this match as far as possible. Then the entire string is
- changed by replacing the matched text with REPLACEMENT_STRING.
- The modified string becomes the new value of TARGET_VARIABLE.
-
- This function is peculiar because TARGET_VARIABLE 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 `sub' can
- store a modified value there. If this argument is omitted, then
- the default is to use and alter `$0'.
-
- For example:
-
- str = "water, water, everywhere"
- sub(/at/, "ith", str)
-
- sets `str' to `"wither, water, everywhere"', by replacing the
- leftmost, longest occurrence of `at' with `ith'.
-
- The `sub' function returns the number of substitutions made
- (either one or zero).
-
- The special character, `&', in the replacement string,
- REPLACEMENT_STRING, stands for the precise substring that was
- matched by REGEXP. (If the regexp can match more than one
- string, then this precise substring may vary.) For example:
-
- awk '{ sub(/candidate/, "& and his wife"); print }'
-
- will change the first occurrence of ``candidate'' to ``candidate
- and his wife'' on each input line.
-
- The effect of this special character can be turned off by
- preceding it with a backslash (`\&'). To include a backslash in
- the replacement string, it too must be preceded with a (second)
- backslash.
-
- Note: if you use `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:
-
- sub(/USA/, "United States", "the USA and Canada")
-
- will indeed produce a string `"the United States and Canada"',
- but there will be no way to use that string!
-
-`gsub(REGEXP, REPLACEMENT_STRING, TARGET_VARIABLE)'
- This is similar to the `sub' function, except `gsub' replaces
- *all* of the longest, leftmost, *non--overlapping* matching
- substrings it can find. The ``g'' in `gsub' stands for
- "global", which means replace *everywhere*. For example:
-
- awk '{ gsub(/Britain/, "United Kingdom"); print }'
-
- replaces all occurrences of the string `Britain' with `United
- Kingdom' for all input records.
-
- The `gsub' function returns the number of substitutions made.
- If the variable to be searched and altered, TARGET_VARIABLE, is
- omitted, then the entire input record, `$0', is used.
-
- The characters `&' and `\' are special in `gsub' as they are in
- `sub' (see immediately above).
-
-`substr(STRING, START, LENGTH)'
- This returns a LENGTH--character--long substring of STRING,
- starting at character number START. The first character of a
- string is character number one. For example,
- `substr("washington", 5, 3)' returns `"ing"'.
-
- If LENGTH is not present, this function returns the whole suffix
- of STRING that begins at character number START. For example,
- `substr("washington", 5)' returns `"ington"'.
-
-
-
-File: gawk-info, Node: I/O Functions, Prev: String Functions, Up: Built-in
-
-Built--in Functions for I/O to Files and Commands
-=================================================
-
-`close(FILENAME)'
- Close the file FILENAME. The argument may alternatively be a
- shell command that was used for redirecting to or from a pipe;
- then the pipe is closed.
-
- *Note Close Input::, regarding closing input files and pipes.
- *Note Close Output::, regarding closing output files and pipes.
-
-`system(COMMAND)'
- The system function allows the user to execute operating system
- commands and then return to the `awk' program. The `system'
- function executes the command given by the string value of
- COMMAND. It returns, as its value, the status returned by the
- command that was executed. This is known as returning the "exit
- status".
-
- For example, if the following fragment of code is put in your
- `awk' program:
-
- END {
- system("mail -s 'awk run done' operator < /dev/null")
- }
-
- the system operator will be sent mail when the `awk' program
- finishes processing input and begins its end--of--input
- processing.
-
- Note that much the same result can be obtained by redirecting
- `print' or `printf' into a pipe. However, if your `awk' program
- is interactive, this function is useful for cranking up large
- self--contained programs, such as a shell or an editor.
-
-
-
-File: gawk-info, Node: User-defined, Next: Special, Prev: Built-in, Up: Top
-
-User--defined Functions
-***********************
-
-Complicated `awk' programs can often be simplified by defining your
-own functions. User--defined functions can be called just like
-built--in ones (*note Function Calls::.), but it is up to you to
-define them--to tell `awk' what they should do.
-
-* Menu:
-
-* Definition Syntax:: How to write definitions and what they mean.
-* Function Example:: An example function definition and what it does.
-* Function Caveats:: Things to watch out for.
-* Return Statement:: Specifying the value a function returns.
-
-
-
-File: gawk-info, Node: Definition Syntax, Next: Function Example, Up: User-defined
-
-Syntax of Function Definitions
-==============================
-
-The definition of a function named NAME looks like this:
-
- function NAME (PARAMETER-LIST) {
- BODY-OF-FUNCTION
- }
-
-A valid function name is like a valid variable name: a sequence of
-letters, digits and underscores, not starting with a digit.
-
-Such function definitions can appear anywhere between the rules of
-the `awk' program. The general format of an `awk' program, then, is
-now modified to include sequences of rules *and* user--defined
-function definitions.
-
-The function definition need not precede all the uses of the function.
-This is because `awk' reads the entire program before starting to
-execute any of it.
-
-The PARAMETER-LIST is a list of the function's "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.
-
-The local variable values hide or "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 `awk' program can be
-referenced or set normally in the function definition.
-
-The local variables last only as long as the function is executing.
-Once the function finishes, the shadowed variables come back.
-
-The BODY-OF-FUNCTION part of the definition is the most important
-part, because this is what says what the function should actually *do*.
-The local variables exist to give the body a way to talk about the
-arguments.
-
-Functions may be "recursive", i.e., they can call themselves, either
-directly, or indirectly (via calling a second function that calls the
-first again).
-
-The keyword `function' may also be written `func'.
-
-
-
-File: gawk-info, Node: Function Example, Next: Function Caveats, Prev: Definition Syntax, Up: User-defined
-
-Function Definition Example
-===========================
-
-Here is an example of a user--defined function, called `myprint',
-that takes a number and prints it in a specific format.
-
- function myprint(num)
- {
- printf "%6.3g\n", num
- }
-
-To illustrate, let's use the following `awk' rule to use, or "call",
-our `myprint' function:
-
- $3 > 0 { myprint($3) }'
-
-This program prints, in our special format, all the third fields that
-contain a positive number in our input. Therefore, when given:
-
- 1.2 3.4 5.6 7.8
- 9.10 11.12 13.14 15.16
- 17.18 19.20 21.22 23.24
-
-this program, using our function to format the results, will print:
-
- 5.6
- 13.1
- 21.2
-
-Here is a rather contrived example of a recursive function. It
-prints a string backwards:
-
- function rev (str, len) {
- if (len == 0) {
- printf "\n"
- return
- }
- printf "%c", substr(str, len, 1)
- rev(str, len - 1)
- }
-
-
-
-File: gawk-info, Node: Function Caveats, Next: Return Statement, Prev: Function Example, Up: User-defined
-
-Caveats of Function Calling
-===========================
-
-*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 `awk' can tell you are not trying to concatenate the value
-of a variable with the value of an expression inside the parentheses.
-
-When a function is called, it is given a *copy* of the values of its
-arguments. This is called "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:
-
- foo = "bar"
- z = myfunc(foo)
-
-then you should not think of the argument to `myfunc' as being ``the
-variable `foo'''. Instead, think of the argument as the string
-value, `"bar"'.
-
-If the function `myfunc' alters the values of its local variables,
-this has no effect on any other variables. In particular, if
-`myfunc' does this:
-
- function myfunc (win) {
- print win
- win = "zzz"
- print win
- }
-
-to change its first argument variable `win', this *does not* change
-the value of `foo' in the caller. The role of `foo' in calling
-`myfunc' ended when its value, `"bar"', was computed. If `win' also
-exists outside of `myfunc', this definition will not change it--that
-value is shadowed during the execution of `myfunc' and cannot be seen
-or changed from there.
-
-However, when arrays are the parameters to functions, they are *not*
-copied. Instead, the array itself is made available for direct
-manipulation by the function. This is usually called "passing by
-reference". Changes made to an array parameter inside the body of a
-function *are* visible outside that function. *This can be very
-dangerous if you don't watch what you are doing.* For example:
-
- function changeit (array, ind, nvalue) {
- array[ind] = nvalue
- }
-
- BEGIN {
- a[1] = 1 ; a[2] = 2 ; a[3] = 3
- changeit(a, 2, "two")
- printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3]
- }
-
-will print `a[1] = 1, a[2] = two, a[3] = 3', because the call to
-`changeit' stores `"two"' in the second element of `a'.
-
-
-
-File: gawk-info, Node: Return Statement, Prev: Function Caveats, Up: User-defined
-
-The `return' statement
-======================
-
-The body of a user--defined function can contain a `return' statement.
-This statement returns control to the rest of the `awk' program. It
-can also be used to return a value for use in the rest of the `awk'
-program. It looks like:
-
- `return EXPRESSION'
-
-The EXPRESSION part is optional. If it is omitted, then the returned
-value is undefined and, therefore, unpredictable.
-
-A `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
-for the largest number among the elements of an array:
-
- function maxelt (vec, i, ret) {
- for (i in vec) {
- if (ret == "" || vec[i] > ret)
- ret = vec[i]
- }
- return ret
- }
-
-You call `maxelt' with one argument, an array name. The local
-variables `i' and `ret' are not intended to be arguments; while there
-is nothing to stop you from passing two or three arguments to
-`maxelt', the results would be strange.
-
-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 `maxelt'.
-
-Here is a program that uses, or calls, our `maxelt' function. This
-program loads an array, calls `maxelt', and then reports the maximum
-number in that array:
-
- awk '
- function maxelt (vec, i, ret) {
- for (i in vec) {
- if (ret == "" || vec[i] > ret)
- ret = vec[i]
- }
- return ret
- }
-
- # Load all fields of each record into nums.
- {
- for(i = 1; i <= NF; i++)
- nums[NR, i] = $i
- }
-
- END {
- print maxelt(nums)
- }'
-
-Given the following input:
-
- 1 5 23 8 16
- 44 3 5 2 8 26
- 256 291 1396 2962 100
- -6 467 998 1101
- 99385 11 0 225
-
-our program tells us (predictably) that:
-
- 99385
-
-is the largest number in our array.
-
-
-
-File: gawk-info, Node: Special, Next: Sample Program, Prev: User-defined, Up: Top
-
-Special Variables
-*****************
-
-Most `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.
-
-A few variables have special meanings. Some of them `awk' examines
-automatically, so that they enable you to tell `awk' how to do
-certain things. Others are set automatically by `awk', so that they
-carry information from the internal workings of `awk' to your program.
-
-Most of these variables are also documented in the chapters where
-their areas of activity are described.
-
-* Menu:
-
-* User-modified:: Special variables that you change to control `awk'.
-
-* Auto-set:: Special variables where `awk' gives you information.
-
- \ No newline at end of file
diff --git a/gawk-info-5 b/gawk-info-5
deleted file mode 100644
index fd8d7eec..00000000
--- a/gawk-info-5
+++ /dev/null
@@ -1,960 +0,0 @@
-Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
-file gawk.texinfo.
-
-This file documents `awk', a program that you can use to select
-particular records in a file and perform operations upon them.
-
-Copyright (C) 1989 Free Software Foundation, Inc.
-
-Permission is granted to make and distribute verbatim copies of this
-manual provided the copyright notice and this permission notice are
-preserved on all copies.
-
-Permission is granted to copy and distribute modified versions of
-this manual under the conditions for verbatim copying, provided that
-the entire resulting derived work is distributed under the terms of a
-permission notice identical to this one.
-
-Permission is granted to copy and distribute translations of this
-manual into another language, under the above conditions for modified
-versions, except that this permission notice may be stated in a
-translation approved by the Foundation.
-
-
-
-File: gawk-info, Node: User-modified, Next: Auto-set, Up: Special
-
-Special Variables That Control `awk'
-====================================
-
-This is a list of the variables which you can change to control how
-`awk' does certain things.
-
-`FS'
- `FS' is the input field separator (*note Field Separators::.).
- The value is a regular expression that matches the separations
- between fields in an input record.
-
- The default value is `" "', a string consisting of a single
- space. As a special exception, this value actually means that
- any sequence of spaces and tabs is a single separator. It also
- causes spaces and tabs at the beginning or end of a line to be
- ignored.
-
- You can set the value of `FS' on the command line using the `-F'
- option:
-
- awk -F, 'PROGRAM' INPUT-FILES
-
-`OFMT'
- This string is used by `awk' to control conversion of numbers to
- strings (*note Conversion::.). It works by being passed, in
- effect, as the first argument to the `sprintf' function. Its
- default value is `"%.6g"'.
-
-`OFS'
- This is the output field separator (*note Output Separators::.).
- It is output between the fields output by a `print' statement.
- Its default value is `" "', a string consisting of a single space.
-
-`ORS'
- This is the output record separator (*note Output
- Separators::.). It is output at the end of every `print'
- statement. Its default value is the newline character, often
- represented in `awk' programs as `\n'.
-
-`RS'
- This is `awk''s record separator (*note 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.
-
-`SUBSEP'
- `SUBSEP' is a subscript separator (*note Multi-dimensional::.).
- It has the default value of `"\034"', and is used to separate
- the parts of the name of a multi--dimensional array. Thus, if
- you access `foo[12,3]', it really accesses `foo["12\0343"]'.
-
-
-
-File: gawk-info, Node: Auto-set, Prev: User-modified, Up: Special
-
-Special Variables That Convey Information to You
-================================================
-
-This is a list of the variables that are set automatically by `awk'
-on certain occasions so as to provide information for your program.
-
-`ARGC'
-`ARGV'
- The command--line arguments available to `awk' are stored in an
- array called `ARGV'. `ARGC' is the number of command--line
- arguments present. `ARGV' is indexed from zero to `ARGC' - 1.
- For example:
-
- awk '{ print ARGV[$1] }' inventory-shipped BBS-list
-
- In this example, `ARGV[0]' contains `"awk"', `ARGV[1]' contains
- `"inventory-shipped"', and `ARGV[2]' contains `"BBS-list"'.
- `ARGC' is 3, one more than the index of the last element in
- `ARGV' since the elements are numbered from zero.
-
- Notice that the `awk' program is not treated as an argument.
- The `-f' `FILENAME' option, and the `-F' option, are also not
- treated as arguments for this purpose.
-
- Variable assignments on the command line *are* treated as
- arguments, and do show up in the `ARGV' array.
-
- Your program can alter `ARGC' the elements of `ARGV'. Each time
- `awk' reaches the end of an input file, it uses the next element
- of `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 `-' to represent the standard input. By
- storing additional elements and incrementing `ARGC' you can
- cause additional files to be read.
-
- If you decrease the value of `ARGC', that eliminates input files
- from the end of the list. By recording the old value of `ARGC'
- elsewhere, your program can treat the eliminated arguments as
- something other than file names.
-
- To eliminate a file from the middle of the list, store the null
- string (`""') into `ARGV' in place of the file's name. As a
- special feature, `awk' ignores file names that have been
- replaced with the null string.
-
-`ENVIRON'
- This is an array that contains the values of the environment.
- The array indices are the environment variable names; the values
- are the values of the particular environment variables. For
- example, `ENVIRON["HOME"]' might be `/u/close'. Changing this
- array does not affect the environment passed on to any programs
- that `awk' may spawn via redirection or the `system' function.
- (This may not work under operating systems other than MS-DOS,
- Unix, or GNU.)
-
-`FILENAME'
- This is the name of the file that `awk' is currently reading.
- If `awk' is reading from the standard input (in other words,
- there are no files listed on the command line), `FILENAME' is
- set to `"-"'. `FILENAME' is changed each time a new file is
- read (*note Reading Files::.).
-
-`FNR'
- `FNR' is the current record number in the current file. `FNR'
- is incremented each time a new record is read (*note Getline::.).
- It is reinitialized to 0 each time a new input file is started.
-
-`NF'
- `NF' is the number of fields in the current input record. `NF'
- is set each time a new record is read, when a new field is
- created, or when $0 changes (*note Fields::.).
-
-`NR'
- This is the number of input records `awk' has processed since
- the beginning of the program's execution. (*note Records::.).
- `NR' is set each time a new record is read.
-
-`RLENGTH'
- `RLENGTH' is the length of the string matched by the `match'
- function (*note String Functions::.). `RLENGTH' is set by
- invoking the `match' function. Its value is the length of the
- matched string, or -1 if no match was found.
-
-`RSTART'
- `RSTART' is the start of the string matched by the `match'
- function (*note String Functions::.). `RSTART' is set by
- invoking the `match' function. Its value is the position of the
- string where the matched string starts, or 0 if no match was
- found.
-
-
-
-File: gawk-info, Node: Sample Program, Next: Notes, Prev: Special, Up: Top
-
-Sample Program
-**************
-
-The following example is a complete `awk' program, which prints the
-number of occurrences of each word in its input. It illustrates the
-associative nature of `awk' arrays by using strings as subscripts.
-It also demonstrates the `for X in ARRAY' construction. Finally, it
-shows how `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.
-
- awk '
- # Print list of word frequencies
- {
- for (i = 1; i <= NF; i++)
- freq[$i]++
- }
-
- END {
- for (word in freq)
- printf "%s\t%d\n", word, freq[word]
- }'
-
-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 `awk''s field--accessing
-mechanism (*note Fields::.) to pick out the individual words from the
-line, and the special variable `NF' (*note Special::.) to know how
-many fields are available.
-
-For each input word, an element of the array `freq' is incremented to
-reflect that the word has been seen an additional time.
-
-The second rule, because it has the pattern `END', is not executed
-until the input has been exhausted. It prints out the contents of
-the `freq' table that has been built up inside the first action.
-
-Note that this program has several problems that would prevent it
-from being useful by itself on real text files:
-
- * Words are detected using the `awk' convention that fields are
- separated by whitespace and that other characters in the input
- (except newlines) don't have any special meaning to `awk'. This
- means that punctuation characters count as part of words.
-
- * The `awk' language considers upper and lower case characters to
- be distinct. Therefore, `foo' and `Foo' will not be 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.
-
- * The output does not come out in any useful order. You're more
- likely to be interested in which words occur most frequently, or
- having an alphabetized table of how frequently each word occurs.
-
-The way to solve these problems is to use other operating system
-utilities to process the input and output of the `awk' script.
-Suppose the script shown above is saved in the file `frequency.awk'.
-Then the shell command:
-
- tr A-Z a-z < file1 | tr -cd 'a-z\012' \
- | awk -f frequency.awk \
- | sort +1 -nr
-
-produces a table of the words appearing in `file1' in order of
-decreasing frequency.
-
-The first `tr' command in this pipeline translates all the upper case
-characters in `file1' to lower case. The second `tr' command deletes
-all the characters in the input except lower case characters and
-newlines. The second argument to the second `tr' is quoted to
-protect the backslash in it from being interpreted by the shell. The
-`awk' program reads this suitably massaged data and produces a word
-frequency table, which is not ordered.
-
-The `awk' script's output is now sorted by the `sort' command and
-printed on the terminal. The options given to `sort' in this example
-specify to sort by the second field of each input line (skipping one
-field), that the sort keys should be treated as numeric quantities
-(otherwise `15' would come before `5'), and that the sorting should
-be done in descending (reverse) order.
-
-See the general operating system documentation for more information
-on how to use the `tr' and `sort' commands.
-
-
-
-File: gawk-info, Node: Notes, Next: Glossary, Prev: Sample Program, Up: Top
-
-Implementation Notes
-********************
-
-This appendix contains information mainly of interest to implementors
-and maintainers of `gawk'. Everything in it applies specifically to
-`gawk', and not to other implementations.
-
-* Menu:
-
-* Extensions:: Things`gawk' does that Unix `awk' does not.
-
-* Future Extensions:: Things likely to appear in a future release.
-
-* Improvements:: Suggestions for future improvements.
-
-* Manual Improvements:: Suggestions for improvements to this manual.
-
-
-
-File: gawk-info, Node: Extensions, Next: Future Extensions, Up: Notes
-
-GNU Extensions to the AWK Language
-==================================
-
-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 `awk', too.
-
-All of these features can be turned off either by compiling `gawk'
-with `-DSTRICT', or by invoking `gawk' as `awk'.
-
-The `AWKPATH' environment variable
- When opening a file supplied via the `-f' option, if the
- filename does not contain a `/', `gawk' will perform a "path
- search" for the file, similar to that performed by the shell.
- `gawk' gets its search path from the `AWKPATH' environment
- variable. If that variable does not exist, it uses the default
- path `".:/usr/lib/awk:/usr/local/lib/awk"'.
-
-Case Independent Matching
- Two new operators have been introduced, `~~', and `!~~'. These
- perform regular expression match and no-match operations that
- are case independent. In other words, `A' and `a' would both
- match `/a/'.
-
-The `-i' option
- This option causes the `~' and `!~' operators to behave like the
- `~~' and `!~~' operators described above.
-
-The `-v' option
- This option prints version information for this particular copy
- of `gawk'. This is so you can determine if your copy of `gawk'
- is up to date with respect to whatever the Free Software
- Foundation is currently distributing. It may disappear in a
- future version of `gawk'.
-
-
-
-File: gawk-info, Node: Future Extensions, Next: Improvements, Prev: Extensions, Up: Notes
-
-Extensions Likely To Appear In A Future Release
-===============================================
-
-Here are some more extensions that indicate the directions we are
-currently considering for `gawk'. Like the previous section, this
-section is also subject to change. None of these are implemented yet.
-
-The `IGNORECASE' special variable
- If `IGNORECASE' is non--zero, then *all* regular expression
- matching will be done in a case--independent fashion. The `-i'
- option and the `~~' and `!~~' operators will go away, as this
- mechanism generalizes those facilities.
-
-More Escape Sequences
- The ANSI C `\a', and `\x' escape sequences will be recognized.
- Unix `awk' does not recognize `\v', although `gawk' does.
-
-`RS' as a regexp
- The meaning of `RS' will be generalized along the lines of `FS'.
-
-Transliteration Functions
- We are planning on adding `toupper' and `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.
-
-Access To System File Descriptors
- `gawk' will recognize the special file names `/dev/stdin',
- `/dev/stdout', `/dev/stderr', and `/dev/fd/N' internally. These
- will allow access to inherited file descriptors from within an
- `awk' program.
-
-
-
-File: gawk-info, Node: Improvements, Next: Manual Improvements, Prev: Future Extensions, Up: Notes
-
-Suggestions for Future Improvements
-===================================
-
-Here are some projects that would--be `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 project.
-
- 1. State machine regexp matcher: At present, `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 `egrep'.
-
- 2. Compilation of `awk' programs: `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.
-
- It should be possible for `gawk' to convert the script's parse
- tree into a C program which the user would then compile, using
- the normal C compiler and a special `gawk' library to provide
- all the needed functions (regexps, fields, associative arrays,
- type coercion, and so on).
-
- An easier possibility might be for an intermediate phase of
- `awk' to convert the parse tree into a linear byte code form
- like the one used 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 `gawk' does now.
-
-
-
-File: gawk-info, Node: Manual Improvements, Prev: Improvements, Up: Notes
-
-Suggestions For Future Improvements of This Manual
-==================================================
-
- 1. 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.
-
- 2. A summary page has not been included, as the ``man'', or help,
- page that comes with the `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.
-
- 3. A function and variable index has not been included as we are
- not sure what to put in it.
-
- 4. A section summarizing the differences between V7 `awk' and
- System V Release 4 `awk' would be useful for long--time `awk'
- hackers.
-
-
-
-File: gawk-info, Node: Glossary, Next: Index, Prev: Notes, Up: Top
-
-Glossary
-********
-
-Action
- A series of `awk' statements attached to a rule. If the rule's
- pattern matches an input record, the `awk' language executes the
- rule's action. Actions are always enclosed in curly braces.
-
-Amazing `awk' assembler
- Henry Spencer at the University of Toronto wrote a retargetable
- assembler completely as `awk' scripts. It is thousands of lines
- long, including machine descriptions for several 8--bit
- microcomputers. It is distributed with `gawk' and is a good
- example of a program that would have been better written in
- another language.
-
-Assignment
- An `awk' expression that changes the value of some `awk'
- variable or data object. An object that you can assign to is
- called an "lvalue".
-
-Built-in function
- The `awk' language provides built--in functions that perform
- various numerical and string computations. Examples are `sqrt'
- (for the square root of a number) and `substr' (for a substring
- of a string).
-
-C
- The system programming language that most of GNU is written in.
- The `awk' programming language has C--like syntax, and this
- manual points out similarities between `awk' and C when
- appropriate.
-
-Compound statement
- A series of `awk' statements, enclosed in curly braces.
- Compound statements may be nested.
-
-Concatenation
- Concatenating two strings means sticking them together, one
- after another, giving a new string. For example, the string
- `foo' concatenated with the string `bar' gives the string
- `foobar'.
-
-Conditional expression
- A relation that is either true or false, such as `(a < b)'.
- Conditional expressions are used in `if' and `while' statements,
- and in patterns to select which input records to process.
-
-Curly braces
- The characters `{' and `}'. Curly braces are used in `awk' for
- delimiting actions, compound statements, and function bodies.
-
-Data objects
- These are numbers and strings of characters. Numbers are
- converted into strings and vice versa, as needed.
-
-Escape Sequences
- A special sequence of characters used for describing
- non--printable characters, such as `\n' for newline, or `\033'
- for the ASCII ESC (escape) character.
-
-Field
- When `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 `FS'). Such
- pieces are called fields.
-
-Format
- Format strings are used to control the appearance of output in
- the `printf' statement. Also, data conversions from numbers to
- strings are controlled by the format string contained in the
- special variable `OFMT'.
-
-Function
- A specialized group of statements often used to encapsulate
- general or program--specific tasks. `awk' has a number of
- built--in functions, and also allows you to define your own.
-
-`gawk'
- The GNU implementation of `awk'.
-
-`awk' language
- The language in which `awk' programs are written.
-
-`awk' program
- An `awk' program consists of a series of "patterns" and
- "actions", collectively known as "rules". For each input record
- given to the program, the program's rules are all processed in
- turn. `awk' programs may also contain function definitions.
-
-`awk' script
- Another name for an `awk' program.
-
-Input record
- A single chunk of data read in by `awk'. Usually, an `awk'
- input record consists of one line of text.
-
-Keyword
- In the `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: `if', `else', `while', `do...while', `for',
- `for...in', `break', `continue', `delete', `next', `function',
- `func', and `exit'.
-
-Lvalue
- An expression that can appear on the left side of an assignment
- operator. In most languages, lvalues can be variables or array
- elements. In `awk', a field designator can also be used as an
- lvalue.
-
-Number
- A numeric valued data object. The `gawk' implementation uses
- double precision floating point to represent numbers.
-
-Pattern
- Patterns tell `awk' which input records are interesting to which
- rules.
-
- A pattern is an arbitrary conditional expression against which
- input is tested. If the condition is satisfied, the pattern is
- said to "match" the input record. A typical pattern might
- compare the input record against a regular expression.
-
-Range (of input lines)
- A sequence of consecutive lines from the input file. A pattern
- can specify ranges of input lines for `awk' to process, or it
- can specify single lines.
-
-Recursion
- When a function calls itself, either directly or indirectly. If
- this isn't clear, refer to the entry for ``recursion''.
-
-Redirection
- 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 `print' and `printf'
- statements to a file or a system command, using the `>', `>>',
- and `|' operators. You can redirect input to the `getline'
- statement using the `<' and `|' operators.
-
-Regular Expression
- See ``regexp''.
-
-Regexp
- Short for "regular expression". A regexp is a pattern that
- denotes a set of strings, possibly an infinite set. For
- example, the regexp `R.*xp' matches any string starting with the
- letter `R' and ending with the letters `xp'. In `awk', regexps
- are used in patterns and in conditional expressions.
-
-Rule
- A segment of an `awk' program, that specifies how to process
- single input records. A rule consists of a "pattern" and an
- "action". `awk' reads an input record; then, for each rule, if
- the input record satisfies the rule's pattern, `awk' executes
- the rule's action. Otherwise, the rule does nothing for that
- input record.
-
-Special Variable
- The variables `ARGC', `ARGV', `ENVIRON', `FILENAME', `FNR',
- `FS', `NF', `NR', `OFMT', `OFS', `ORS', `RLENGTH', `RSTART',
- `RS', `SUBSEP', have special meaning to `awk'. Changing some of
- them affects `awk''s running environment.
-
-Stream Editor
- A program that reads records from an input stream and processes
- them one or more at a time. This is in contrast with batch
- programs, which may expect to read their input files in entirety
- before starting to do anything, and with interactive programs,
- which require input from the user.
-
-String
- A datum consisting of a sequence of characters, such as `I am a
- string'. Constant strings are written with double--quotes in
- the `awk' language, and may contain "escape sequences".
-
-Whitespace
- A sequence of blank or tab characters occurring inside an input
- record or a string.
-
-
-
-File: gawk-info, Node: Index, Prev: Glossary, Up: Top
-
-Index
-*****
-
-* Menu:
-
-* #!: Executable Scripts.
-* -f option: Long.
-* `$NF', last field in record: Fields.
-* `$' (field operator): Fields.
-* `>>': Redirection.
-* `>': Redirection.
-* `BEGIN', special pattern: BEGIN/END.
-* `END', special pattern: BEGIN/END.
-* `awk' language: This Manual.
-* `awk' program: This Manual.
-* `break' statement: Break.
-* `close' statement for input: Close Input.
-* `close' statement for output: Close Output.
-* `continue' statement: Continue.
-* `delete' statement: Delete.
-* `exit' statement: Exit.
-* `for (x in ...)': Scanning an Array.
-* `for' statement: For.
-* `if' statement: If.
-* `next' statement: Next.
-* `print $0': Very Simple.
-* `printf' statement, format of: Basic Printf.
-* `printf', format-control characters: Format-Control.
-* `printf', modifiers: Modifiers.
-* `print' statement: Print.
-* `return' statement: Return Statement.
-* `while' statement: While.
-* `|': Redirection.
-* `BBS-list' file: The Files.
-* `inventory-shipped' file: The Files.
-* Accessing fields: Fields.
-* Acronym: History.
-* Action, curly braces: Actions.
-* Action, curly braces: Getting Started.
-* Action, default: Very Simple.
-* Action, definition of: Getting Started.
-* Action, general: Actions.
-* Action, separating statements: Actions.
-* Applications of `awk': When.
-* Arguments in function call: Function Calls.
-* Arguments, Command Line: Command Line.
-* Arithmetic operators: Arithmetic Ops.
-* Array assignment: Assigning Elements.
-* Array reference: Reference to Elements.
-* Arrays: Array Intro.
-* Arrays, definition of: Array Intro.
-* Arrays, deleting an element: Delete.
-* Arrays, determining presence of elements: Reference to Elements.
-* Arrays, multi-dimensional subscripts: Multi-dimensional.
-* Arrays, special `for' statement: Scanning an Array.
-* Assignment operators: Assignment Ops.
-* Associative arrays: Array Intro.
-* Backslash Continuation: Statements/Lines.
-* Basic function of `gawk': Getting Started.
-* Body of a loop: While.
-* Boolean expressions: Boolean Ops.
-* Boolean operators: Boolean Ops.
-* Boolean patterns: Boolean.
-* Built-in functions, list of: Built-in.
-* Built-in variables: Variables.
-* Calling a function: Function Calls.
-* Case sensitivity and gawk: Read Terminal.
-* Changing contents of a field: Changing Fields.
-* Changing the record separator: Records.
-* Closing files and pipes: Close Output.
-* Command Line: Command Line.
-* Command line formats: Running gawk.
-* Command line, setting `FS' on: Field Separators.
-* Comments: Comments.
-* Comparison expressions: Comparison Ops.
-* Comparison expressions as patterns: Comparison Patterns.
-* Compound statements: Actions.
-* Computed Regular Expressions: Regexp Usage.
-* Concatenation: Concatenation.
-* Conditional Patterns: Conditional Patterns.
-* Conditional expression: Conditional Exp.
-* Constants, types of: Constants.
-* Continuing statements on the next line: Statements/Lines.
-* Conversion of strings and numbers: Conversion.
-* Curly braces: Actions.
-* Curly braces: Getting Started.
-* Default action: Very Simple.
-* Default pattern: Very Simple.
-* Deleting elements of arrays: Delete.
-* Differences between `gawk' and `awk': Arithmetic Ops.
-* Differences between `gawk' and `awk': Constants.
-* Documenting `awk' programs: Comments.
-* Dynamic Regular Expressions: Regexp Usage.
-* Element assignment: Assigning Elements.
-* Element of array: Reference to Elements.
-* Emacs Lisp: When.
-* Empty pattern: Empty.
-* Escape sequence notation: Constants.
-* Examining fields: Fields.
-* Executable Scripts: Executable Scripts.
-* Expression, conditional: Conditional Exp.
-* Expressions: Actions.
-* Expressions, boolean: Boolean Ops.
-* Expressions, comparison: Comparison Ops.
-* Field separator, `FS': Field Separators.
-* Field separator, choice of: Field Separators.
-* Field separator, setting on command line: Field Separators.
-* Field, changing contents of: Changing Fields.
-* Fields: Fields.
-* Fields, negative-numbered: Non-Constant Fields.
-* Fields, semantics of: Field Separators.
-* Fields, separating: Field Separators.
-* Format specifier: Format-Control.
-* Format string: Basic Printf.
-* Formatted output: Printf.
-* Function call: Function Calls.
-* Function definitions: Actions.
-* Functions, user-defined: User-defined.
-* General input: Reading Files.
-* History of `awk': History.
-* How gawk works: Two Rules.
-* Increment operators: Increment Ops.
-* Input file, sample: The Files.
-* Input, `getline' function: Getline.
-* Input, general: Reading Files.
-* Input, multiple line records: Multiple.
-* Input, standard: Read Terminal.
-* Input, standard: Reading Files.
-* Interaction of `awk' with other programs: I/O Functions.
-* Invocation of `gawk': Command Line.
-* Language, `awk': This Manual.
-* Loop: While.
-* Loops, breaking out of: Break.
-* Lvalue: Assignment Ops.
-* Manual, using this: This Manual.
-* Metacharacters: Regexp Operators.
-* Mod function, semantics of: Arithmetic Ops.
-* Modifiers (in format specifiers): Modifiers.
-* Multiple line records: Multiple.
-* Multiple passes over data: Command Line.
-* Multiple statements on one line: Statements/Lines.
-* Negative-numbered fields: Non-Constant Fields.
-* Number of fields, `NF': Fields.
-* Number of records, `FNR': Records.
-* Number of records, `NR': Records.
-* Numerical constant: Constants.
-* Numerical value: Constants.
-* One-liners: One-liners.
-* Operator, Ternary: Conditional Patterns.
-* Operators, `$': Fields.
-* Operators, arithmetic: Arithmetic Ops.
-* Operators, assignment: Assignment Ops.
-* Operators, boolean: Boolean Ops.
-* Operators, increment: Increment Ops.
-* Operators, regular expression matching: Regexp Usage.
-* Operators, relational: Comparison Ops.
-* Operators, relational: Comparison Patterns.
-* Operators, string: Concatenation.
-* Operators, string-matching: Regexp Usage.
-* Options, Command Line: Command Line.
-* Output: Printing.
-* Output field separator, `OFS': Output Separators.
-* Output record separator, `ORS': Output Separators.
-* Output redirection: Redirection.
-* Output, formatted: Printf.
-* Output, piping: Redirection.
-* Passes, Multiple: Command Line.
-* Pattern, case sensitive: Read Terminal.
-* Pattern, comparison expressions: Comparison Patterns.
-* Pattern, default: Very Simple.
-* Pattern, definition of: Getting Started.
-* Pattern, empty: Empty.
-* Pattern, regular expressions: Regexp.
-* Patterns, `BEGIN': BEGIN/END.
-* Patterns, `END': BEGIN/END.
-* Patterns, Conditional: Conditional Patterns.
-* Patterns, boolean: Boolean.
-* Patterns, definition of: Patterns.
-* Patterns, types of: Patterns.
-* Pipes for output: Redirection.
-* Printing, general: Printing.
-* Program, `awk': This Manual.
-* Program, Self contained: Executable Scripts.
-* Program, definition of: Getting Started.
-* Programs, documenting: Comments.
-* Range pattern: Ranges.
-* Reading files, `getline' function: Getline.
-* Reading files, general: Reading Files.
-* Reading files, multiple line records: Multiple.
-* Record separator, `RS': Records.
-* Records, multiple line: Multiple.
-* Redirection of output: Redirection.
-* Reference to array: Reference to Elements.
-* Regexp: Regexp.
-* Regular Expressions, Computed: Regexp Usage.
-* Regular Expressions, Dynamic: Regexp Usage.
-* Regular expression matching operators: Regexp Usage.
-* Regular expression, metacharacters: Regexp Operators.
-* Regular expressions as patterns: Regexp.
-* Regular expressions, field separators and: Field Separators.
-* Relational operators: Comparison Patterns.
-* Relational operators: Comparison Ops.
-* Removing elements of arrays: Delete.
-* Rule, definition of: Getting Started.
-* Running gawk programs: Running gawk.
-* Sample input file: The Files.
-* Scanning an array: Scanning an Array.
-* Script, definition of: Getting Started.
-* Scripts, Executable: Executable Scripts.
-* Scripts, Shell: Executable Scripts.
-* Self contained Programs: Executable Scripts.
-* Separator character, choice of: Field Separators.
-* Shell Scripts: Executable Scripts.
-* Single quotes, why they are needed: One-shot.
-* Special variables, user modifiable: User-modified.
-* Standard input: Read Terminal.
-* Standard input: Reading Files.
-* Statements: Statements.
-* Statements: Actions.
-* String constants: Constants.
-* String operators: Concatenation.
-* String value: Constants.
-* String-matching operators: Regexp Usage.
-* Subscripts, multi-dimensional in arrays: Multi-dimensional.
-* Ternary Operator: Conditional Patterns.
-* Use of comments: Comments.
-* User-defined functions: User-defined.
-* User-defined variables: Variables.
-* Uses of `awk': Preface.
-* Using this manual: This Manual.
-* Variables, built-in: Variables.
-* Variables, user-defined: Variables.
-* What is `awk': Preface.
-* When to use `awk': When.
-* file, `awk' program: Long.
-* patterns, range: Ranges.
-* program file: Long.
-* regexp search operators: Regexp Usage.
-* running long programs: Long.
-
-
- 
-Tag Table:
-Node: Top918
-Node: Preface2804
-Node: History4267
-Node: License5644
-Node: This Manual18989
-Node: The Files20330
-Node: Getting Started22914
-Node: Very Simple24249
-Node: Two Rules26030
-Node: More Complex28066
-Node: Running gawk30908
-Node: One-shot31827
-Node: Read Terminal32945
-Node: Long33862
-Node: Executable Scripts34991
-Node: Command Line36534
-Node: Comments40168
-Node: Statements/Lines41067
-Node: When43498
-Node: Reading Files45420
-Node: Records47119
-Node: Fields49902
-Node: Non-Constant Fields52789
-Node: Changing Fields54591
-Node: Field Separators57302
-Node: Multiple62004
-Node: Assignment Options64393
-Node: Getline65608
-Node: Close Input74958
-Node: Printing76023
-Node: Print76748
-Node: Print Examples78712
-Node: Output Separators80751
-Node: Redirection82417
-Node: Close Output85886
-Node: Printf88132
-Node: Basic Printf88908
-Node: Format-Control90261
-Node: Modifiers91806
-Node: Printf Examples93108
-Node: One-liners95707
-Node: Patterns97642
-Node: Empty100130
-Node: Regexp100402
-Node: Regexp Usage101173
-Node: Regexp Operators102947
-Node: Comparison Patterns107890
-Node: Ranges109336
-Node: BEGIN/END110722
-Node: Boolean113151
-Node: Conditional Patterns115605
-Node: Actions116105
-Node: Expressions117435
-Node: Constants119124
-Node: Variables121097
-Node: Arithmetic Ops122454
-Node: Concatenation123840
-Node: Comparison Ops124569
-Node: Boolean Ops125973
-Node: Assignment Ops128266
-Node: Increment Ops131817
-Node: Conversion134112
-Node: Conditional Exp136066
-Node: Function Calls137384
-Node: Statements139939
-Node: If141253
-Node: While142627
-Node: Do144232
-Node: For145265
-Node: Break148306
-Node: Continue149848
-Node: Next151476
-Node: Exit152985
-Node: Arrays154514
-Node: Array Intro155624
-Node: Reference to Elements159227
-Node: Assigning Elements161115
-Node: Array Example161615
-Node: Scanning an Array163336
-Node: Delete165642
-Node: Multi-dimensional166529
-Node: Multi-scanning169746
-Node: Built-in171303
-Node: Numeric Functions172806
-Node: String Functions176601
-Node: I/O Functions183717
-Node: User-defined185189
-Node: Definition Syntax185834
-Node: Function Example187928
-Node: Function Caveats189034
-Node: Return Statement191386
-Node: Special193612
-Node: User-modified194478
-Node: Auto-set196511
-Node: Sample Program200558
-Node: Notes204316
-Node: Extensions204909
-Node: Future Extensions206490
-Node: Improvements207922
-Node: Manual Improvements210034
-Node: Glossary210928
-Node: Index217934
diff --git a/gawk.1 b/gawk.1
index 3d2068b8..5472d20a 100644
--- a/gawk.1
+++ b/gawk.1
@@ -1,4 +1,4 @@
-.TH GAWK 1 "Free Software Foundation"
+.TH GAWK 1 "August 24 1989" "Free Software Foundation"
.SH NAME
gawk \- pattern scanning and processing language
.SH SYNOPSIS
@@ -8,21 +8,27 @@ gawk \- pattern scanning and processing language
.B \-d
] [
.B \-D
-] [
-.B \-v
-] [
-.B \-V
]
..
[
+.B \-a
+] [
+.B \-e
+] [
+.B \-c
+] [
+.B \-C
+] [
+.B \-V
+] [
.BI \-F\^ fs
+] [
+.B \-v
+.IR var = val
]
.B \-f
.I program-file
[
-.B \-f
-.I program-file
-\&.\^.\^. ] [
.B \-\^\-
] file .\^.\^.
.br
@@ -32,15 +38,24 @@ gawk \- pattern scanning and processing language
.B \-d
] [
.B \-D
-] [
-.B \-v
-] [
-.B \-V
]
..
[
+.B \-a
+] [
+.B \-e
+] [
+.B \-c
+] [
+.B \-C
+] [
+.B \-V
+] [
.BI \-F\^ fs
] [
+.B \-v
+.IR var = val
+] [
.B \-\^\-
]
.I program-text
@@ -53,7 +68,8 @@ It conforms to the definition and description of the language in
by Aho, Kernighan, and Weinberger,
with the additional features defined in the System V Release 4 version
of \s-1UNIX\s+1
-.IR awk .
+.IR awk ,
+and some GNU-specific extensions.
.PP
The command line consists of options to
.I gawk
@@ -66,9 +82,9 @@ and
.B ARGV
pre-defined AWK variables.
.PP
-The options that
-.I gawk
-accepts are:
+.I Gawk
+accepts the following options, which should be available on any implementation
+of the AWK language.
.TP
.BI \-F fs
Use
@@ -78,10 +94,23 @@ for the input field separator (the value of the
predefined
variable).
.TP
+\fB\-v\fI var\fR\^=\^\fIval\fR
+Assign the value
+.IR val ,
+to the variable
+.IR var ,
+before execution of the program begins.
+Such variable values are available to the
+.B BEGIN
+block of an AWK program.
+.TP
.BI \-f " program-file"
Read the AWK program source from the file
.IR program-file ,
instead of from the first command line argument.
+Multiple
+.B \-f
+options may be used.
.TP
.B \-\^\-
Signal the end of options. This is useful to allow further arguments to the
@@ -89,10 +118,52 @@ AWK program itself to start with a ``\-''.
This is mainly for consistency with the argument parsing convention used
by most other System V programs.
.PP
+The following options are specific to the GNU implementation.
+.TP
+.B \-a
+Use AWK style regular expressions as described in the book.
+This is the current default, but may not be when the POSIX P1003.2
+standard is finalized.
+It is orthogonal to
+.BR \-c .
+.TP
+.B \-e
+Use
+.IR egrep (1)
+style regular expressions as described in POSIX standard.
+This may become the default when the POSIX P1003.2
+standard is finalized.
+It is orthogonal to
+.BR \-c .
+.TP
+.B \-c
+Run in
+.I compatibility
+mode. In compatibility mode,
+.I gawk
+behaves identically to \s-1UNIX\s+1
+.IR awk ;
+none of the GNU-specific extensions are recognized.
+.TP
+.B \-C
+Print the short version of the GNU copyright information message on
+the error output.
+This option may disappear in a future version of
+.IR gawk .
+.TP
+.B \-V
+Print version information for this particular copy of
+.I gawk
+on the error output.
+This is useful mainly for knowing if the current copy of
+.I gawk
+on your system
+is up to date with respect to whatever the Free Software Foundation
+is distributing.
+This option may disappear in a future version of
+.IR gawk .
+.PP
Any other options are flagged as illegal, but are otherwise ignored.
-(However, see the
-.B "GNU EXTENSIONS"
-section, below.)
.PP
An AWK program consists of a sequence of pattern-action statements
and optional function definitions.
@@ -137,6 +208,9 @@ option contains a ``/'' character, no path search is performed.
.PP
.I Gawk
compiles the program into an internal form,
+executes the code in the
+.B BEGIN
+block(s) (if any),
and then proceeds to read
each file named in the
.B ARGV
@@ -167,10 +241,11 @@ is executed.
.SH VARIABLES AND FIELDS
AWK variables are dynamic; they come into existence when they are
first used. Their values are either floating-point numbers or strings,
-depending upon how they are used. AWK also has single dimension
+depending upon how they are used. AWK also has one dimension
arrays; multiply dimensioned arrays may be simulated.
There are several pre-defined variables that AWK sets as a program
runs; these will be described as needed and summarized below.
+.SS Fields
.PP
As each input line is read,
.I gawk
@@ -258,6 +333,8 @@ Changing this array does not affect the environment seen by programs which
spawns via redirection or the
.B system
function.
+(This may change in a future version of
+.IR gawk .)
.TP \l'\fBIGNORECASE\fR'
.B FILENAME
the name of the current input file.
@@ -284,6 +361,7 @@ and
.BR !~ ,
and the
.BR gsub() ,
+.BR index() ,
.BR match() ,
.BR split() ,
and
@@ -363,7 +441,7 @@ arrays. For example:
.ft B
i = "A" ;\^ j = "B" ;\^ k = "C"
.br
-x[i,j,k] = "hello, world\en"
+x[i, j, k] = "hello, world\en"
.ft R
.RE
.PP
@@ -596,6 +674,8 @@ matches zero or one
grouping: matches
.IR r .
.RE
+The escape sequences that are valid in string constants (see below)
+are also legal in regular expressions.
.SS Actions
Action statements are enclosed in braces,
.B {
@@ -605,6 +685,7 @@ 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.
+.SS Operators
.PP
The operators in AWK, in order of increasing precedence, are
.PP
@@ -664,6 +745,7 @@ increment and decrement, both prefix and postfix.
.B $
field reference.
.RE
+.SS Control Statements
.PP
The control statements are
as follows:
@@ -682,6 +764,7 @@ as follows:
\fB{ \fIstatements \fB}
.fi
.RE
+.SS "I/O Statements"
.PP
The input/output statements are as follows:
.PP
@@ -767,6 +850,7 @@ pipes into
.BR getline .
.BR Getline
will return 0 on end of file, and \-1 on an error.
+.SS The \fIprintf\fP Statement
.PP
The AWK versions of the
.B printf
@@ -787,6 +871,10 @@ character of that string is printed.
.B %d
A decimal number (the integer part).
.TP
+.B %i
+Just like
+.BR %d .
+.TP
.B %e
A floating point number of the form
.BR [\-]d.ddddddE[+\^\-]dd .
@@ -811,6 +899,14 @@ A character string.
.B %x
An unsigned hexadecimal number (an integer).
.TP
+.B %X
+Like
+.BR %x ,
+but using
+.B ABCDEF
+instead of
+.BR abcdef .
+.TP
.B %%
A single
.B %
@@ -845,6 +941,7 @@ routines are not supported.
However, they may be simulated by using
the AWK concatenation operation to build up
a format specification dynamically.
+.SS Special File Names
.PP
When doing I/O redirection from either
.B print
@@ -892,6 +989,7 @@ print "You blew it!" | "cat 1>&2"
.RE
.PP
These file names may also be used on the command line to name data files.
+.SS Numeric Functions
.PP
AWK has the following pre-defined arithmetic functions:
.PP
@@ -932,6 +1030,7 @@ is provided, the time of day will be used.
The return value is the previous seed for the random
number generator.
.RE
+.SS String Functions
.PP
AWK has the following pre-defined string functions:
.PP
@@ -1029,6 +1128,7 @@ with all the lower-case characters in
translated to their corresponding upper-case counterparts.
Non-alphabetic characters are left unchanged.
.RE
+.SS String Constants
.PP
String constants in AWK are sequences of characters enclosed
between double quotes (\fB"\fR). Within strings, certain
@@ -1152,10 +1252,16 @@ Concatenate and line number (a variation on a theme):
.ft B
{ print NR, $0 }
.ft R
+.fi
.SH SEE ALSO
+.IR egrep (1)
+.PP
.IR "The AWK Programming Language" ,
Alfred V. Aho, Brian W. Kernighan, Peter J. Weinberger,
Addison-Wesley, 1988. ISBN 0-201-07981-X.
+.PP
+.IR "The GAWK Manual" ,
+published by the Free Software Foundation, 1989.
.SH SYSTEM V RELEASE 4 COMPATIBILITY
A primary goal for
.I gawk
@@ -1169,6 +1275,24 @@ but are part of
.I awk
in System V Release 4.
.PP
+The
+.B \-v
+option for assigning variables before program execution starts is new.
+The book indicates that command line variable assignment happens when
+.I awk
+would otherwise open the argument as a file, which is after the
+.B BEGIN
+block is executed. However, in earlier implementations, when such an
+assignment appeared before any file names, the assignment would happen
+.I before
+the
+.B BEGIN
+block was run. Applications came to depend on this ``feature.''
+When
+.I awk
+was changed to match its documentation, this option was added to
+accomodate applications that depended upon the old behaviour.
+.PP
When processing arguments,
.I gawk
uses the special option ``\fB\-\^\-\fP'' to signal the end of
@@ -1185,11 +1309,22 @@ in
.I gawk
also returns its current seed.
.PP
+Other new features are:
The use of multiple
.B \-f
-options is a new feature, as is the
+options; the
.B ENVIRON
-array.
+array; the
+.BR \ea ,
+and
+.BR \ev ,
+.B \ex
+escape sequences; the
+.B tolower
+and
+.B toupper
+built-in functions; and the ANSI C conversion specifications in
+.BR printf .
.SH GNU EXTENSIONS
.I Gawk
has some extensions to System V
@@ -1201,8 +1336,9 @@ with
.BR \-DSTRICT ,
or by invoking
.I gawk
-with the name
-.IR awk .
+with the
+.B \-c
+option.
If the underlying operating system supports the
.B /dev/fd
directory and corresponding files, then
@@ -1219,25 +1355,10 @@ System V
.RS
.TP \l'\(bu'
\(bu
-The
-.BR \ea ,
-.BR \ev ,
-or
-.B \ex
-escape sequences are not recognized.
-.TP \l'\(bu'
-\(bu
The special file names available for I/O redirection are not recognized.
.TP \l'\(bu'
\(bu
The
-.B tolower
-and
-.B toupper
-built-in string functions are not available.
-.TP \l'\(bu'
-\(bu
-The
.B IGNORECASE
variable and its side-effects are not available.
.TP \l'\(bu'
@@ -1247,6 +1368,16 @@ No path search is performed for files named via the
option. Therefore the
.B AWKPATH
environment variable is not special.
+.TP \l'\(bu'
+\(bu
+The
+.BR \-a ,
+.BR \-e ,
+.BR \-c ,
+.BR \-C ,
+and
+.B \-V
+command line options.
.RE
.PP
The AWK book does not define the return value of the
@@ -1262,8 +1393,9 @@ when closing a file or pipe, respectively.
.PP
When
.I gawk
-is invoked as
-.IR awk ,
+is invoked with the
+.B \-c
+option,
if the
.I fs
argument to the
@@ -1272,6 +1404,7 @@ option is ``t'', then
.B FS
will be set to the tab character.
Since this is a rather ugly special case, it is not the default behavior.
+.ig
.PP
The rest of the features described in this section may change at some time in
the future, or may go away entirely.
@@ -1279,7 +1412,6 @@ You should not write programs that depend upon them.
.PP
.I Gawk
accepts the following additional options:
-.ig
.TP
.B \-D
Turn on general debugging and turn on
@@ -1301,24 +1433,14 @@ This option should only be of interest to the
maintainers, and may not even be compiled into
.IR gawk .
..
-.TP
-.B \-v
-Print version information for this particular copy of
-.I gawk
-on the error output.
-This is useful mainly for knowing if the current copy of
-.I gawk
-on your system
-is up to date with respect to whatever the Free Software Foundation
-is distributing.
-.TP
-.B \-V
-Print the GNU copyright information message on the error output.
.SH BUGS
The
.B \-F
option is not necessary given the command line variable assignment feature;
it remains only for backwards compatibility.
+.PP
+There are now too many options.
+Fortunately, most of them are rarely needed.
.SH AUTHORS
The original version of \s-1UNIX\s+1
.I awk
diff --git a/gawk.aux b/gawk.aux
deleted file mode 100644
index 9c137c3b..00000000
--- a/gawk.aux
+++ /dev/null
@@ -1,202 +0,0 @@
-'xrdef {Preface-pg}{1}
-'xrdef {Preface-snt}{}
-'xrdef {History-pg}{1}
-'xrdef {History-snt}{}
-'xrdef {License-pg}{3}
-'xrdef {License-snt}{}
-'xrdef {This Manual-pg}{9}
-'xrdef {This Manual-snt}{chapter'tie1}
-'xrdef {The Files-pg}{9}
-'xrdef {The Files-snt}{section'tie1.1}
-'xrdef {Getting Started-pg}{11}
-'xrdef {Getting Started-snt}{chapter'tie2}
-'xrdef {Very Simple-pg}{11}
-'xrdef {Very Simple-snt}{section'tie2.1}
-'xrdef {Two Rules-pg}{12}
-'xrdef {Two Rules-snt}{section'tie2.2}
-'xrdef {More Complex-pg}{13}
-'xrdef {More Complex-snt}{section'tie2.3}
-'xrdef {Running gawk-pg}{14}
-'xrdef {Running gawk-snt}{section'tie2.4}
-'xrdef {One-shot-pg}{15}
-'xrdef {One-shot-snt}{section'tie2.4.1}
-'xrdef {Read Terminal-pg}{15}
-'xrdef {Read Terminal-snt}{section'tie2.4.2}
-'xrdef {Long-pg}{16}
-'xrdef {Long-snt}{section'tie2.4.3}
-'xrdef {Executable Scripts-pg}{17}
-'xrdef {Executable Scripts-snt}{section'tie2.4.4}
-'xrdef {Command Line-pg}{18}
-'xrdef {Command Line-snt}{section'tie2.4.5}
-'xrdef {Comments-pg}{19}
-'xrdef {Comments-snt}{section'tie2.5}
-'xrdef {Statements/Lines-pg}{20}
-'xrdef {Statements/Lines-snt}{section'tie2.6}
-'xrdef {When-pg}{21}
-'xrdef {When-snt}{section'tie2.7}
-'xrdef {Reading Files-pg}{23}
-'xrdef {Reading Files-snt}{chapter'tie3}
-'xrdef {Records-pg}{23}
-'xrdef {Records-snt}{section'tie3.1}
-'xrdef {Fields-pg}{24}
-'xrdef {Fields-snt}{section'tie3.2}
-'xrdef {Non-Constant Fields-pg}{26}
-'xrdef {Non-Constant Fields-snt}{section'tie3.3}
-'xrdef {Changing Fields-pg}{27}
-'xrdef {Changing Fields-snt}{section'tie3.4}
-'xrdef {Field Separators-pg}{28}
-'xrdef {Field Separators-snt}{section'tie3.5}
-'xrdef {Multiple-pg}{31}
-'xrdef {Multiple-snt}{section'tie3.6}
-'xrdef {Assignment Options-pg}{32}
-'xrdef {Assignment Options-snt}{section'tie3.7}
-'xrdef {Getline-pg}{32}
-'xrdef {Getline-snt}{section'tie3.8}
-'xrdef {Close Input-pg}{36}
-'xrdef {Close Input-snt}{section'tie3.8.1}
-'xrdef {Printing-pg}{39}
-'xrdef {Printing-snt}{chapter'tie4}
-'xrdef {Print-pg}{39}
-'xrdef {Print-snt}{section'tie4.1}
-'xrdef {Print Examples-pg}{40}
-'xrdef {Print Examples-snt}{section'tie4.2}
-'xrdef {Output Separators-pg}{41}
-'xrdef {Output Separators-snt}{section'tie4.3}
-'xrdef {Redirection-pg}{42}
-'xrdef {Redirection-snt}{section'tie4.4}
-'xrdef {Close Output-pg}{43}
-'xrdef {Close Output-snt}{section'tie4.4.1}
-'xrdef {Printf-pg}{44}
-'xrdef {Printf-snt}{section'tie4.5}
-'xrdef {Basic Printf-pg}{45}
-'xrdef {Basic Printf-snt}{section'tie4.5.1}
-'xrdef {Format-Control-pg}{45}
-'xrdef {Format-Control-snt}{section'tie4.5.2}
-'xrdef {Modifiers-pg}{46}
-'xrdef {Modifiers-snt}{section'tie4.5.3}
-'xrdef {Printf Examples-pg}{46}
-'xrdef {Printf Examples-snt}{section'tie4.5.4}
-'xrdef {One-liners-pg}{49}
-'xrdef {One-liners-snt}{chapter'tie5}
-'xrdef {Patterns-pg}{51}
-'xrdef {Patterns-snt}{chapter'tie6}
-'xrdef {Empty-pg}{51}
-'xrdef {Empty-snt}{section'tie6.1}
-'xrdef {Regexp-pg}{52}
-'xrdef {Regexp-snt}{section'tie6.2}
-'xrdef {Regexp Usage-pg}{52}
-'xrdef {Regexp Usage-snt}{section'tie6.2.1}
-'xrdef {Regexp Operators-pg}{53}
-'xrdef {Regexp Operators-snt}{section'tie6.2.2}
-'xrdef {Comparison Patterns-pg}{55}
-'xrdef {Comparison Patterns-snt}{section'tie6.3}
-'xrdef {Ranges-pg}{56}
-'xrdef {Ranges-snt}{section'tie6.4}
-'xrdef {BEGIN/END-pg}{57}
-'xrdef {BEGIN/END-snt}{section'tie6.5}
-'xrdef {Boolean-pg}{58}
-'xrdef {Boolean-snt}{section'tie6.6}
-'xrdef {Conditional Patterns-pg}{59}
-'xrdef {Conditional Patterns-snt}{section'tie6.7}
-'xrdef {Actions-pg}{61}
-'xrdef {Actions-snt}{chapter'tie7}
-'xrdef {Expressions-pg}{63}
-'xrdef {Expressions-snt}{chapter'tie8}
-'xrdef {Constants-pg}{63}
-'xrdef {Constants-snt}{section'tie8.1}
-'xrdef {Variables-pg}{64}
-'xrdef {Variables-snt}{section'tie8.2}
-'xrdef {Arithmetic Ops-pg}{65}
-'xrdef {Arithmetic Ops-snt}{section'tie8.3}
-'xrdef {Concatenation-pg}{65}
-'xrdef {Concatenation-snt}{section'tie8.4}
-'xrdef {Comparison Ops-pg}{66}
-'xrdef {Comparison Ops-snt}{section'tie8.5}
-'xrdef {Boolean Ops-pg}{67}
-'xrdef {Boolean Ops-snt}{section'tie8.6}
-'xrdef {Assignment Ops-pg}{68}
-'xrdef {Assignment Ops-snt}{section'tie8.7}
-'xrdef {Increment Ops-pg}{70}
-'xrdef {Increment Ops-snt}{section'tie8.8}
-'xrdef {Conversion-pg}{71}
-'xrdef {Conversion-snt}{section'tie8.9}
-'xrdef {Conditional Exp-pg}{72}
-'xrdef {Conditional Exp-snt}{section'tie8.10}
-'xrdef {Function Calls-pg}{73}
-'xrdef {Function Calls-snt}{section'tie8.11}
-'xrdef {Statements-pg}{75}
-'xrdef {Statements-snt}{chapter'tie9}
-'xrdef {If-pg}{75}
-'xrdef {If-snt}{section'tie9.1}
-'xrdef {While-pg}{76}
-'xrdef {While-snt}{section'tie9.2}
-'xrdef {Do-pg}{77}
-'xrdef {Do-snt}{section'tie9.3}
-'xrdef {For-pg}{77}
-'xrdef {For-snt}{section'tie9.4}
-'xrdef {Break-pg}{79}
-'xrdef {Break-snt}{section'tie9.5}
-'xrdef {Continue-pg}{80}
-'xrdef {Continue-snt}{section'tie9.6}
-'xrdef {Next-pg}{81}
-'xrdef {Next-snt}{section'tie9.7}
-'xrdef {Exit-pg}{82}
-'xrdef {Exit-snt}{section'tie9.8}
-'xrdef {Arrays-pg}{83}
-'xrdef {Arrays-snt}{chapter'tie10}
-'xrdef {Array Intro-pg}{83}
-'xrdef {Array Intro-snt}{section'tie10.1}
-'xrdef {Reference to Elements-pg}{85}
-'xrdef {Reference to Elements-snt}{section'tie10.2}
-'xrdef {Assigning Elements-pg}{86}
-'xrdef {Assigning Elements-snt}{section'tie10.3}
-'xrdef {Array Example-pg}{86}
-'xrdef {Array Example-snt}{section'tie10.4}
-'xrdef {Scanning an Array-pg}{87}
-'xrdef {Scanning an Array-snt}{section'tie10.5}
-'xrdef {Delete-pg}{88}
-'xrdef {Delete-snt}{section'tie10.6}
-'xrdef {Multi-dimensional-pg}{89}
-'xrdef {Multi-dimensional-snt}{section'tie10.7}
-'xrdef {Multi-scanning-pg}{91}
-'xrdef {Multi-scanning-snt}{section'tie10.8}
-'xrdef {Built-in-pg}{93}
-'xrdef {Built-in-snt}{chapter'tie11}
-'xrdef {Numeric Functions-pg}{93}
-'xrdef {Numeric Functions-snt}{section'tie11.1}
-'xrdef {String Functions-pg}{95}
-'xrdef {String Functions-snt}{section'tie11.2}
-'xrdef {I/O Functions-pg}{98}
-'xrdef {I/O Functions-snt}{section'tie11.3}
-'xrdef {User-defined-pg}{99}
-'xrdef {User-defined-snt}{chapter'tie12}
-'xrdef {Definition Syntax-pg}{99}
-'xrdef {Definition Syntax-snt}{section'tie12.1}
-'xrdef {Function Example-pg}{100}
-'xrdef {Function Example-snt}{section'tie12.2}
-'xrdef {Function Caveats-pg}{101}
-'xrdef {Function Caveats-snt}{section'tie12.3}
-'xrdef {Return Statement-pg}{102}
-'xrdef {Return Statement-snt}{section'tie12.4}
-'xrdef {Special-pg}{105}
-'xrdef {Special-snt}{chapter'tie13}
-'xrdef {User-modified-pg}{105}
-'xrdef {User-modified-snt}{section'tie13.1}
-'xrdef {Auto-set-pg}{106}
-'xrdef {Auto-set-snt}{section'tie13.2}
-'xrdef {Sample Program-pg}{109}
-'xrdef {Sample Program-snt}{}
-'xrdef {Notes-pg}{111}
-'xrdef {Notes-snt}{}
-'xrdef {Extensions-pg}{111}
-'xrdef {Extensions-snt}{}
-'xrdef {Future Extensions-pg}{111}
-'xrdef {Future Extensions-snt}{}
-'xrdef {Improvements-pg}{112}
-'xrdef {Improvements-snt}{}
-'xrdef {Manual Improvements-pg}{113}
-'xrdef {Manual Improvements-snt}{}
-'xrdef {Glossary-pg}{115}
-'xrdef {Glossary-snt}{}
-'xrdef {Index-pg}{119}
-'xrdef {Index-snt}{}
diff --git a/gawk.cp b/gawk.cp
deleted file mode 100644
index 7ff13135..00000000
--- a/gawk.cp
+++ /dev/null
@@ -1,234 +0,0 @@
-\entry {What is awk}{1}{What is {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {Uses of awk}{1}{Uses of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {Acronym}{1}{Acronym}
-\entry {History of awk}{1}{History of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {Manual, using this}{9}{Manual, using this}
-\entry {Using this manual}{9}{Using this manual}
-\entry {Language, awk}{9}{Language, {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {Program, awk}{9}{Program, {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {awk language}{9}{{\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} language}
-\entry {awk program}{9}{{\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} program}
-\entry {Input file, sample}{9}{Input file, sample}
-\entry {Sample input file}{9}{Sample input file}
-\entry {`{\fam \ttfam \tentt \rawbackslash \frenchspacing BBS-list}'\hbox {} file}{9}{`{\fam \ttfam \tentt \rawbackslash \frenchspacing BBS-list}'\hbox {} file}
-\entry {`{\fam \ttfam \tentt \rawbackslash \frenchspacing inventory-shipped}'\hbox {} file}{10}{`{\fam \ttfam \tentt \rawbackslash \frenchspacing inventory-shipped}'\hbox {} file}
-\entry {Script, definition of}{11}{Script, definition of}
-\entry {Rule, definition of}{11}{Rule, definition of}
-\entry {Pattern, definition of}{11}{Pattern, definition of}
-\entry {Action, definition of}{11}{Action, definition of}
-\entry {Program, definition of}{11}{Program, definition of}
-\entry {Basic function of gawk}{11}{Basic function of {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {}}
-\entry {Action, curly braces}{11}{Action, curly braces}
-\entry {Curly braces}{11}{Curly braces}
-\entry {print $0}{11}{{\fam \ttfam \tentt \rawbackslash \frenchspacing print $0}\hbox {}}
-\entry {Action, default}{11}{Action, default}
-\entry {Pattern, default}{11}{Pattern, default}
-\entry {Default action}{11}{Default action}
-\entry {Default pattern}{11}{Default pattern}
-\entry {How gawk works}{12}{How gawk works}
-\entry {Command line formats}{14}{Command line formats}
-\entry {Running gawk programs}{14}{Running gawk programs}
-\entry {Single quotes, why they are needed}{15}{Single quotes, why they are needed}
-\entry {Standard input}{15}{Standard input}
-\entry {Input, standard}{15}{Input, standard}
-\entry {Case sensitivity and gawk}{16}{Case sensitivity and gawk}
-\entry {Pattern, case sensitive}{16}{Pattern, case sensitive}
-\entry {running long programs}{16}{running long programs}
-\entry {-f option}{16}{-f option}
-\entry {program file}{16}{program file}
-\entry {file, awk program}{16}{file, {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} program}
-\entry {Executable Scripts}{17}{Executable Scripts}
-\entry {Scripts, Executable}{17}{Scripts, Executable}
-\entry {Self contained Programs}{17}{Self contained Programs}
-\entry {Program, Self contained}{17}{Program, Self contained}
-\entry {#!}{17}{#!}
-\entry {Shell Scripts}{17}{Shell Scripts}
-\entry {Scripts, Shell}{17}{Scripts, Shell}
-\entry {Command Line}{18}{Command Line}
-\entry {Invocation of gawk}{18}{Invocation of {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {}}
-\entry {Arguments, Command Line}{18}{Arguments, Command Line}
-\entry {Options, Command Line}{18}{Options, Command Line}
-\entry {Multiple passes over data}{19}{Multiple passes over data}
-\entry {Passes, Multiple}{19}{Passes, Multiple}
-\entry {Comments}{19}{Comments}
-\entry {Use of comments}{19}{Use of comments}
-\entry {Documenting awk programs}{19}{Documenting {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} programs}
-\entry {Programs, documenting}{19}{Programs, documenting}
-\entry {Backslash Continuation}{20}{Backslash Continuation}
-\entry {Continuing statements on the next line}{20}{Continuing statements on the next line}
-\entry {Multiple statements on one line}{21}{Multiple statements on one line}
-\entry {When to use awk}{21}{When to use {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {Applications of awk}{21}{Applications of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {Emacs Lisp}{21}{Emacs Lisp}
-\entry {Reading files, general}{23}{Reading files, general}
-\entry {Input, general}{23}{Input, general}
-\entry {Standard input}{23}{Standard input}
-\entry {Input, standard}{23}{Input, standard}
-\entry {General input}{23}{General input}
-\entry {Record separator, RS}{23}{Record separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing RS}\hbox {}}
-\entry {Changing the record separator}{23}{Changing the record separator}
-\entry {Number of records, NR}{24}{Number of records, {\fam \ttfam \tentt \rawbackslash \frenchspacing NR}\hbox {}}
-\entry {Number of records, FNR}{24}{Number of records, {\fam \ttfam \tentt \rawbackslash \frenchspacing FNR}\hbox {}}
-\entry {Examining fields}{24}{Examining fields}
-\entry {Fields}{24}{Fields}
-\entry {Accessing fields}{24}{Accessing fields}
-\entry {$ (field operator)}{24}{{\fam \ttfam \tentt \rawbackslash \frenchspacing $}\hbox {} (field operator)}
-\entry {Operators, $}{24}{Operators, {\fam \ttfam \tentt \rawbackslash \frenchspacing $}\hbox {}}
-\entry {$NF, last field in record}{25}{{\fam \ttfam \tentt \rawbackslash \frenchspacing $NF}\hbox {}, last field in record}
-\entry {Number of fields, NF}{25}{Number of fields, {\fam \ttfam \tentt \rawbackslash \frenchspacing NF}\hbox {}}
-\entry {Fields, negative-numbered}{26}{Fields, negative-numbered}
-\entry {Negative-numbered fields}{26}{Negative-numbered fields}
-\entry {Field, changing contents of}{27}{Field, changing contents of}
-\entry {Changing contents of a field}{27}{Changing contents of a field}
-\entry {Fields, semantics of}{28}{Fields, semantics of}
-\entry {Fields, separating}{28}{Fields, separating}
-\entry {Field separator, FS}{28}{Field separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing FS}\hbox {}}
-\entry {Separator character, choice of}{29}{Separator character, choice of}
-\entry {Field separator, choice of}{29}{Field separator, choice of}
-\entry {Regular expressions, field separators and}{29}{Regular expressions, field separators and}
-\entry {Field separator, setting on command line}{29}{Field separator, setting on command line}
-\entry {Command line, setting FS on}{29}{Command line, setting {\fam \ttfam \tentt \rawbackslash \frenchspacing FS}\hbox {} on}
-\entry {Multiple line records}{31}{Multiple line records}
-\entry {Input, multiple line records}{31}{Input, multiple line records}
-\entry {Reading files, multiple line records}{31}{Reading files, multiple line records}
-\entry {Records, multiple line}{31}{Records, multiple line}
-\entry {Input, getline function}{32}{Input, {\fam \ttfam \tentt \rawbackslash \frenchspacing getline}\hbox {} function}
-\entry {Reading files, getline function}{32}{Reading files, {\fam \ttfam \tentt \rawbackslash \frenchspacing getline}\hbox {} function}
-\entry {close statement for input}{36}{{\fam \ttfam \tentt \rawbackslash \frenchspacing close}\hbox {} statement for input}
-\entry {Printing, general}{39}{Printing, general}
-\entry {Output}{39}{Output}
-\entry {print statement}{39}{{\fam \ttfam \tentt \rawbackslash \frenchspacing print}\hbox {} statement}
-\entry {Output field separator, OFS}{41}{Output field separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing OFS}\hbox {}}
-\entry {Output record separator, ORS}{41}{Output record separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing ORS}\hbox {}}
-\entry {Output redirection}{42}{Output redirection}
-\entry {Redirection of output}{42}{Redirection of output}
-\entry {{\fam \ttfam \tentt \gtr }}{42}{{\fam \ttfam \tentt \rawbackslash \frenchspacing {\fam \ttfam \tentt \gtr }}\hbox {}}
-\entry {{\fam \ttfam \tentt \gtr }{\fam \ttfam \tentt \gtr }}{42}{{\fam \ttfam \tentt \rawbackslash \frenchspacing {\fam \ttfam \tentt \gtr }{\fam \ttfam \tentt \gtr }}\hbox {}}
-\entry {{\fam \ttfam \tentt \char '174}}{42}{{\fam \ttfam \tentt \rawbackslash \frenchspacing {\fam \ttfam \tentt \char '174}}\hbox {}}
-\entry {Pipes for output}{42}{Pipes for output}
-\entry {Output, piping}{42}{Output, piping}
-\entry {close statement for output}{43}{{\fam \ttfam \tentt \rawbackslash \frenchspacing close}\hbox {} statement for output}
-\entry {Closing files and pipes}{43}{Closing files and pipes}
-\entry {Formatted output}{44}{Formatted output}
-\entry {Output, formatted}{44}{Output, formatted}
-\entry {printf statement, format of}{45}{{\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {} statement, format of}
-\entry {Format string}{45}{Format string}
-\entry {printf, format-control characters}{45}{{\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {}, format-control characters}
-\entry {Format specifier}{45}{Format specifier}
-\entry {printf, modifiers}{46}{{\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {}, modifiers}
-\entry {Modifiers (in format specifiers)}{46}{Modifiers (in format specifiers)}
-\entry {One-liners}{49}{One-liners}
-\entry {Patterns, definition of}{51}{Patterns, definition of}
-\entry {Patterns, types of}{51}{Patterns, types of}
-\entry {Empty pattern}{51}{Empty pattern}
-\entry {Pattern, empty}{51}{Pattern, empty}
-\entry {Pattern, regular expressions}{52}{Pattern, regular expressions}
-\entry {Regexp}{52}{Regexp}
-\entry {Regular expressions as patterns}{52}{Regular expressions as patterns}
-\entry {Regular expression matching operators}{52}{Regular expression matching operators}
-\entry {String-matching operators}{52}{String-matching operators}
-\entry {Operators, string-matching}{52}{Operators, string-matching}
-\entry {Operators, regular expression matching}{52}{Operators, regular expression matching}
-\entry {regexp search operators}{52}{regexp search operators}
-\entry {Computed Regular Expressions}{52}{Computed Regular Expressions}
-\entry {Regular Expressions, Computed}{52}{Regular Expressions, Computed}
-\entry {Dynamic Regular Expressions}{52}{Dynamic Regular Expressions}
-\entry {Regular Expressions, Dynamic}{52}{Regular Expressions, Dynamic}
-\entry {Metacharacters}{53}{Metacharacters}
-\entry {Regular expression, metacharacters}{53}{Regular expression, metacharacters}
-\entry {Comparison expressions as patterns}{55}{Comparison expressions as patterns}
-\entry {Pattern, comparison expressions}{55}{Pattern, comparison expressions}
-\entry {Relational operators}{55}{Relational operators}
-\entry {Operators, relational}{55}{Operators, relational}
-\entry {Range pattern}{56}{Range pattern}
-\entry {patterns, range}{56}{patterns, range}
-\entry {BEGIN, special pattern}{57}{{\fam \ttfam \tentt \rawbackslash \frenchspacing BEGIN}\hbox {}, special pattern}
-\entry {Patterns, BEGIN}{57}{Patterns, {\fam \ttfam \tentt \rawbackslash \frenchspacing BEGIN}\hbox {}}
-\entry {END, special pattern}{57}{{\fam \ttfam \tentt \rawbackslash \frenchspacing END}\hbox {}, special pattern}
-\entry {Patterns, END}{57}{Patterns, {\fam \ttfam \tentt \rawbackslash \frenchspacing END}\hbox {}}
-\entry {Patterns, boolean}{58}{Patterns, boolean}
-\entry {Boolean patterns}{58}{Boolean patterns}
-\entry {Conditional Patterns}{59}{Conditional Patterns}
-\entry {Patterns, Conditional}{59}{Patterns, Conditional}
-\entry {Ternary Operator}{59}{Ternary Operator}
-\entry {Operator, Ternary}{59}{Operator, Ternary}
-\entry {Action, general}{61}{Action, general}
-\entry {Curly braces}{61}{Curly braces}
-\entry {Action, curly braces}{61}{Action, curly braces}
-\entry {Action, separating statements}{61}{Action, separating statements}
-\entry {Expressions}{61}{Expressions}
-\entry {Statements}{61}{Statements}
-\entry {Compound statements}{61}{Compound statements}
-\entry {Function definitions}{61}{Function definitions}
-\entry {Constants, types of}{63}{Constants, types of}
-\entry {String constants}{63}{String constants}
-\entry {String value}{63}{String value}
-\entry {Numerical constant}{63}{Numerical constant}
-\entry {Numerical value}{63}{Numerical value}
-\entry {Differences between gawk and awk}{63}{Differences between {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {} and {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {Escape sequence notation}{63}{Escape sequence notation}
-\entry {Variables, user-defined}{64}{Variables, user-defined}
-\entry {User-defined variables}{64}{User-defined variables}
-\entry {Built-in variables}{64}{Built-in variables}
-\entry {Variables, built-in}{64}{Variables, built-in}
-\entry {Arithmetic operators}{65}{Arithmetic operators}
-\entry {Operators, arithmetic}{65}{Operators, arithmetic}
-\entry {Mod function, semantics of}{65}{Mod function, semantics of}
-\entry {Differences between gawk and awk}{65}{Differences between {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {} and {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}
-\entry {String operators}{65}{String operators}
-\entry {Operators, string}{65}{Operators, string}
-\entry {Concatenation}{65}{Concatenation}
-\entry {Comparison expressions}{66}{Comparison expressions}
-\entry {Expressions, comparison}{66}{Expressions, comparison}
-\entry {Relational operators}{66}{Relational operators}
-\entry {Operators, relational}{66}{Operators, relational}
-\entry {Expressions, boolean}{67}{Expressions, boolean}
-\entry {Boolean expressions}{67}{Boolean expressions}
-\entry {Operators, boolean}{67}{Operators, boolean}
-\entry {Boolean operators}{67}{Boolean operators}
-\entry {Assignment operators}{68}{Assignment operators}
-\entry {Operators, assignment}{68}{Operators, assignment}
-\entry {Lvalue}{68}{Lvalue}
-\entry {Increment operators}{70}{Increment operators}
-\entry {Operators, increment}{70}{Operators, increment}
-\entry {Conversion of strings and numbers}{71}{Conversion of strings and numbers}
-\entry {Conditional expression}{72}{Conditional expression}
-\entry {Expression, conditional}{72}{Expression, conditional}
-\entry {Function call}{73}{Function call}
-\entry {Calling a function}{73}{Calling a function}
-\entry {Arguments in function call}{73}{Arguments in function call}
-\entry {Statements}{75}{Statements}
-\entry {if statement}{75}{{\fam \ttfam \tentt \rawbackslash \frenchspacing if}\hbox {} statement}
-\entry {while statement}{76}{{\fam \ttfam \tentt \rawbackslash \frenchspacing while}\hbox {} statement}
-\entry {Loop}{76}{Loop}
-\entry {Body of a loop}{76}{Body of a loop}
-\entry {for statement}{77}{{\fam \ttfam \tentt \rawbackslash \frenchspacing for}\hbox {} statement}
-\entry {break statement}{79}{{\fam \ttfam \tentt \rawbackslash \frenchspacing break}\hbox {} statement}
-\entry {Loops, breaking out of}{79}{Loops, breaking out of}
-\entry {continue statement}{80}{{\fam \ttfam \tentt \rawbackslash \frenchspacing continue}\hbox {} statement}
-\entry {next statement}{81}{{\fam \ttfam \tentt \rawbackslash \frenchspacing next}\hbox {} statement}
-\entry {exit statement}{82}{{\fam \ttfam \tentt \rawbackslash \frenchspacing exit}\hbox {} statement}
-\entry {Arrays}{83}{Arrays}
-\entry {Arrays, definition of}{83}{Arrays, definition of}
-\entry {Associative arrays}{83}{Associative arrays}
-\entry {Array reference}{85}{Array reference}
-\entry {Element of array}{85}{Element of array}
-\entry {Reference to array}{85}{Reference to array}
-\entry {Arrays, determining presence of elements}{85}{Arrays, determining presence of elements}
-\entry {Array assignment}{86}{Array assignment}
-\entry {Element assignment}{86}{Element assignment}
-\entry {for (x in \dots {})}{87}{{\fam \ttfam \tentt \rawbackslash \frenchspacing for (x in \dots {})}\hbox {}}
-\entry {Arrays, special for statement}{87}{Arrays, special {\fam \ttfam \tentt \rawbackslash \frenchspacing for}\hbox {} statement}
-\entry {Scanning an array}{87}{Scanning an array}
-\entry {delete statement}{88}{{\fam \ttfam \tentt \rawbackslash \frenchspacing delete}\hbox {} statement}
-\entry {Deleting elements of arrays}{88}{Deleting elements of arrays}
-\entry {Removing elements of arrays}{88}{Removing elements of arrays}
-\entry {Arrays, deleting an element}{88}{Arrays, deleting an element}
-\entry {Subscripts, multi-dimensional in arrays}{89}{Subscripts, multi-dimensional in arrays}
-\entry {Arrays, multi-dimensional subscripts}{89}{Arrays, multi-dimensional subscripts}
-\entry {Built-in functions, list of}{93}{Built-in functions, list of}
-\entry {Interaction of awk with other programs}{98}{Interaction of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} with other programs}
-\entry {User-defined functions}{99}{User-defined functions}
-\entry {Functions, user-defined}{99}{Functions, user-defined}
-\entry {return statement}{102}{{\fam \ttfam \tentt \rawbackslash \frenchspacing return}\hbox {} statement}
-\entry {Special variables, user modifiable}{105}{Special variables, user modifiable}
diff --git a/gawk.cps b/gawk.cps
deleted file mode 100644
index 9c5c7c44..00000000
--- a/gawk.cps
+++ /dev/null
@@ -1,253 +0,0 @@
-\initial {#}
-\entry {#!}{17}
-\initial {$}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing $}\hbox {} (field operator)}{25}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing $NF}\hbox {}, last field in record}{25}
-\initial {-}
-\entry {-f option}{16}
-\initial {`}
-\entry {`{\fam \ttfam \tentt \rawbackslash \frenchspacing BBS-list}'\hbox {} file}{9}
-\entry {`{\fam \ttfam \tentt \rawbackslash \frenchspacing inventory-shipped}'\hbox {} file}{10}
-\initial {{\fam \ttfam \tentt \char '174}}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing {\fam \ttfam \tentt \char '174}}\hbox {}}{42}
-\initial {{\fam \ttfam \tentt \gtr }}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing {\fam \ttfam \tentt \gtr }}\hbox {}}{42}
-\initial {{\fam \ttfam \tentt \gtr }}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing {\fam \ttfam \tentt \gtr }{\fam \ttfam \tentt \gtr }}\hbox {}}{42}
-\initial {A}
-\entry {Accessing fields}{24}
-\entry {Acronym}{1}
-\entry {Action, curly braces}{11, 61}
-\entry {Action, default}{12}
-\entry {Action, definition of}{11}
-\entry {Action, general}{61}
-\entry {Action, separating statements}{61}
-\entry {Applications of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{21}
-\entry {Arguments in function call}{73}
-\entry {Arguments, Command Line}{18}
-\entry {Arithmetic operators}{65}
-\entry {Array assignment}{86}
-\entry {Array reference}{85}
-\entry {Arrays}{83}
-\entry {Arrays, definition of}{83}
-\entry {Arrays, deleting an element}{88}
-\entry {Arrays, determining presence of elements}{85}
-\entry {Arrays, multi-dimensional subscripts}{89}
-\entry {Arrays, special {\fam \ttfam \tentt \rawbackslash \frenchspacing for}\hbox {} statement}{87}
-\entry {Assignment operators}{68}
-\entry {Associative arrays}{83}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} language}{9}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} program}{9}
-\initial {B}
-\entry {Backslash Continuation}{20}
-\entry {Basic function of {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {}}{11}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing BEGIN}\hbox {}, special pattern}{57}
-\entry {Body of a loop}{76}
-\entry {Boolean expressions}{67}
-\entry {Boolean operators}{67}
-\entry {Boolean patterns}{58}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing break}\hbox {} statement}{79}
-\entry {Built-in functions, list of}{93}
-\entry {Built-in variables}{64}
-\initial {C}
-\entry {Calling a function}{73}
-\entry {Case sensitivity and gawk}{16}
-\entry {Changing contents of a field}{27}
-\entry {Changing the record separator}{23}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing close}\hbox {} statement for input}{36}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing close}\hbox {} statement for output}{43}
-\entry {Closing files and pipes}{43}
-\entry {Command Line}{18}
-\entry {Command line formats}{14}
-\entry {Command line, setting {\fam \ttfam \tentt \rawbackslash \frenchspacing FS}\hbox {} on}{29}
-\entry {Comments}{19}
-\entry {Comparison expressions}{66}
-\entry {Comparison expressions as patterns}{55}
-\entry {Compound statements}{61}
-\entry {Computed Regular Expressions}{52}
-\entry {Concatenation}{65}
-\entry {Conditional expression}{72}
-\entry {Conditional Patterns}{59}
-\entry {Constants, types of}{63}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing continue}\hbox {} statement}{80}
-\entry {Continuing statements on the next line}{20}
-\entry {Conversion of strings and numbers}{71}
-\entry {Curly braces}{11, 61}
-\initial {D}
-\entry {Default action}{12}
-\entry {Default pattern}{12}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing delete}\hbox {} statement}{88}
-\entry {Deleting elements of arrays}{88}
-\entry {Differences between {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {} and {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{63, 65}
-\entry {Documenting {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} programs}{19}
-\entry {Dynamic Regular Expressions}{52}
-\initial {E}
-\entry {Element assignment}{86}
-\entry {Element of array}{85}
-\entry {Emacs Lisp}{21}
-\entry {Empty pattern}{51}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing END}\hbox {}, special pattern}{57}
-\entry {Escape sequence notation}{63}
-\entry {Examining fields}{24}
-\entry {Executable Scripts}{17}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing exit}\hbox {} statement}{82}
-\entry {Expression, conditional}{72}
-\entry {Expressions}{61}
-\entry {Expressions, boolean}{67}
-\entry {Expressions, comparison}{66}
-\initial {F}
-\entry {Field separator, choice of}{29}
-\entry {Field separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing FS}\hbox {}}{28}
-\entry {Field separator, setting on command line}{29}
-\entry {Field, changing contents of}{27}
-\entry {Fields}{24}
-\entry {Fields, negative-numbered}{26}
-\entry {Fields, semantics of}{28}
-\entry {Fields, separating}{28}
-\entry {file, {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} program}{16}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing for (x in \dots {})}\hbox {}}{87}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing for}\hbox {} statement}{77}
-\entry {Format specifier}{45}
-\entry {Format string}{45}
-\entry {Formatted output}{44}
-\entry {Function call}{73}
-\entry {Function definitions}{61}
-\entry {Functions, user-defined}{99}
-\initial {G}
-\entry {General input}{23}
-\initial {H}
-\entry {History of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{1}
-\entry {How gawk works}{12}
-\initial {I}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing if}\hbox {} statement}{75}
-\entry {Increment operators}{70}
-\entry {Input file, sample}{9}
-\entry {Input, general}{23}
-\entry {Input, {\fam \ttfam \tentt \rawbackslash \frenchspacing getline}\hbox {} function}{32}
-\entry {Input, multiple line records}{31}
-\entry {Input, standard}{15, 23}
-\entry {Interaction of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} with other programs}{98}
-\entry {Invocation of {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {}}{18}
-\initial {L}
-\entry {Language, {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{9}
-\entry {Loop}{76}
-\entry {Loops, breaking out of}{79}
-\entry {Lvalue}{68}
-\initial {M}
-\entry {Manual, using this}{9}
-\entry {Metacharacters}{53}
-\entry {Mod function, semantics of}{65}
-\entry {Modifiers (in format specifiers)}{46}
-\entry {Multiple line records}{31}
-\entry {Multiple passes over data}{19}
-\entry {Multiple statements on one line}{21}
-\initial {N}
-\entry {Negative-numbered fields}{26}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing next}\hbox {} statement}{81}
-\entry {Number of fields, {\fam \ttfam \tentt \rawbackslash \frenchspacing NF}\hbox {}}{25}
-\entry {Number of records, {\fam \ttfam \tentt \rawbackslash \frenchspacing FNR}\hbox {}}{24}
-\entry {Number of records, {\fam \ttfam \tentt \rawbackslash \frenchspacing NR}\hbox {}}{24}
-\entry {Numerical constant}{63}
-\entry {Numerical value}{63}
-\initial {O}
-\entry {One-liners}{49}
-\entry {Operator, Ternary}{59}
-\entry {Operators, {\fam \ttfam \tentt \rawbackslash \frenchspacing $}\hbox {}}{25}
-\entry {Operators, arithmetic}{65}
-\entry {Operators, assignment}{68}
-\entry {Operators, boolean}{67}
-\entry {Operators, increment}{70}
-\entry {Operators, regular expression matching}{52}
-\entry {Operators, relational}{55, 66}
-\entry {Operators, string}{65}
-\entry {Operators, string-matching}{52}
-\entry {Options, Command Line}{18}
-\entry {Output}{39}
-\entry {Output field separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing OFS}\hbox {}}{41}
-\entry {Output record separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing ORS}\hbox {}}{41}
-\entry {Output redirection}{42}
-\entry {Output, formatted}{44}
-\entry {Output, piping}{42}
-\initial {P}
-\entry {Passes, Multiple}{19}
-\entry {Pattern, case sensitive}{16}
-\entry {Pattern, comparison expressions}{55}
-\entry {Pattern, default}{12}
-\entry {Pattern, definition of}{11}
-\entry {Pattern, empty}{51}
-\entry {Pattern, regular expressions}{52}
-\entry {Patterns, {\fam \ttfam \tentt \rawbackslash \frenchspacing BEGIN}\hbox {}}{57}
-\entry {Patterns, boolean}{58}
-\entry {Patterns, Conditional}{59}
-\entry {Patterns, definition of}{51}
-\entry {Patterns, {\fam \ttfam \tentt \rawbackslash \frenchspacing END}\hbox {}}{57}
-\entry {patterns, range}{56}
-\entry {Patterns, types of}{51}
-\entry {Pipes for output}{42}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing print $0}\hbox {}}{11}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing print}\hbox {} statement}{39}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {} statement, format of}{45}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {}, format-control characters}{45}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {}, modifiers}{46}
-\entry {Printing, general}{39}
-\entry {program file}{16}
-\entry {Program, {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{9}
-\entry {Program, definition of}{11}
-\entry {Program, Self contained}{17}
-\entry {Programs, documenting}{19}
-\initial {R}
-\entry {Range pattern}{56}
-\entry {Reading files, general}{23}
-\entry {Reading files, {\fam \ttfam \tentt \rawbackslash \frenchspacing getline}\hbox {} function}{32}
-\entry {Reading files, multiple line records}{31}
-\entry {Record separator, {\fam \ttfam \tentt \rawbackslash \frenchspacing RS}\hbox {}}{23}
-\entry {Records, multiple line}{31}
-\entry {Redirection of output}{42}
-\entry {Reference to array}{85}
-\entry {Regexp}{52}
-\entry {regexp search operators}{52}
-\entry {Regular expression matching operators}{52}
-\entry {Regular expression, metacharacters}{53}
-\entry {Regular expressions as patterns}{52}
-\entry {Regular Expressions, Computed}{52}
-\entry {Regular Expressions, Dynamic}{52}
-\entry {Regular expressions, field separators and}{29}
-\entry {Relational operators}{55, 66}
-\entry {Removing elements of arrays}{88}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing return}\hbox {} statement}{102}
-\entry {Rule, definition of}{11}
-\entry {Running gawk programs}{14}
-\entry {running long programs}{16}
-\initial {S}
-\entry {Sample input file}{9}
-\entry {Scanning an array}{87}
-\entry {Script, definition of}{11}
-\entry {Scripts, Executable}{17}
-\entry {Scripts, Shell}{17}
-\entry {Self contained Programs}{17}
-\entry {Separator character, choice of}{29}
-\entry {Shell Scripts}{17}
-\entry {Single quotes, why they are needed}{15}
-\entry {Special variables, user modifiable}{105}
-\entry {Standard input}{15, 23}
-\entry {Statements}{61, 75}
-\entry {String constants}{63}
-\entry {String operators}{65}
-\entry {String value}{63}
-\entry {String-matching operators}{52}
-\entry {Subscripts, multi-dimensional in arrays}{89}
-\initial {T}
-\entry {Ternary Operator}{59}
-\initial {U}
-\entry {Use of comments}{19}
-\entry {User-defined functions}{99}
-\entry {User-defined variables}{64}
-\entry {Uses of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{1}
-\entry {Using this manual}{9}
-\initial {V}
-\entry {Variables, built-in}{64}
-\entry {Variables, user-defined}{64}
-\initial {W}
-\entry {What is {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{1}
-\entry {When to use {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{21}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing while}\hbox {} statement}{76}
diff --git a/gawk.dvi b/gawk.dvi
deleted file mode 100644
index 8c863aa4..00000000
--- a/gawk.dvi
+++ /dev/null
Binary files differ
diff --git a/gawk.fn b/gawk.fn
deleted file mode 100644
index d45d54e7..00000000
--- a/gawk.fn
+++ /dev/null
@@ -1,10 +0,0 @@
-\entry {getline}{32}{{\fam \ttfam \tentt \rawbackslash \frenchspacing getline}\hbox {}}
-\entry {match}{95}{{\fam \ttfam \tentt \rawbackslash \frenchspacing match}\hbox {}}
-\entry {length}{95}{{\fam \ttfam \tentt \rawbackslash \frenchspacing length}\hbox {}}
-\entry {match}{95}{{\fam \ttfam \tentt \rawbackslash \frenchspacing match}\hbox {}}
-\entry {split}{96}{{\fam \ttfam \tentt \rawbackslash \frenchspacing split}\hbox {}}
-\entry {sprintf}{96}{{\fam \ttfam \tentt \rawbackslash \frenchspacing sprintf}\hbox {}}
-\entry {sub}{96}{{\fam \ttfam \tentt \rawbackslash \frenchspacing sub}\hbox {}}
-\entry {gsub}{97}{{\fam \ttfam \tentt \rawbackslash \frenchspacing gsub}\hbox {}}
-\entry {substr}{97}{{\fam \ttfam \tentt \rawbackslash \frenchspacing substr}\hbox {}}
-\entry {system}{98}{{\fam \ttfam \tentt \rawbackslash \frenchspacing system}\hbox {}}
diff --git a/gawk.fns b/gawk.fns
deleted file mode 100644
index bfd931c1..00000000
--- a/gawk.fns
+++ /dev/null
@@ -1,13 +0,0 @@
-\initial {G}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing getline}\hbox {}}{32}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing gsub}\hbox {}}{97}
-\initial {L}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing length}\hbox {}}{95}
-\initial {M}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing match}\hbox {}}{95}
-\initial {S}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing split}\hbox {}}{96}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing sprintf}\hbox {}}{96}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing sub}\hbox {}}{96}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing substr}\hbox {}}{97}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing system}\hbox {}}{98}
diff --git a/gawk.ky b/gawk.ky
deleted file mode 100644
index e69de29b..00000000
--- a/gawk.ky
+++ /dev/null
diff --git a/gawk.kys b/gawk.kys
deleted file mode 100644
index e69de29b..00000000
--- a/gawk.kys
+++ /dev/null
diff --git a/gawk.pg b/gawk.pg
deleted file mode 100644
index e69de29b..00000000
--- a/gawk.pg
+++ /dev/null
diff --git a/gawk.pgs b/gawk.pgs
deleted file mode 100644
index e69de29b..00000000
--- a/gawk.pgs
+++ /dev/null
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
diff --git a/gawk.toc b/gawk.toc
deleted file mode 100644
index b07c6d3b..00000000
--- a/gawk.toc
+++ /dev/null
@@ -1,104 +0,0 @@
-\unnumbchapentry {Preface}{1}
-\unnumbsecentry{History of {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} and {\fam \ttfam \tentt \rawbackslash \frenchspacing gawk}\hbox {}}{1}
-\unnumbchapentry {GNU GENERAL PUBLIC LICENSE}{3}
-\unnumbsecentry{Preamble}{3}
-\unnumbsecentry{TERMS AND CONDITIONS}{4}
-\unnumbsecentry{Appendix: How to Apply These Terms to Your New Programs}{7}
-\chapentry {Using This Manual}{1}{9}
-\secentry {Input Files for the Examples}{1}{1}{9}
-\chapentry {Getting Started With {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{2}{11}
-\secentry {A Very Simple Example}{2}{1}{11}
-\secentry {An Example with Two Rules}{2}{2}{12}
-\secentry {A More Complex Example}{2}{3}{13}
-\secentry {How to Run {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} Programs}{2}{4}{14}
-\subsecentry {One--shot Throw--away {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} Programs}{2}{4}{1}{15}
-\subsecentry {Running {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} without Input Files}{2}{4}{2}{15}
-\subsecentry {Running Long Programs}{2}{4}{3}{16}
-\subsecentry {Executable {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} Programs}{2}{4}{4}{17}
-\subsecentry {Details of the {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} Command Line}{2}{4}{5}{18}
-\secentry {Comments in {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} Programs}{2}{5}{19}
-\secentry {{\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {} Statements versus Lines}{2}{6}{20}
-\secentry {When to Use {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{2}{7}{21}
-\chapentry {Reading Files (Input)}{3}{23}
-\secentry {How Input is Split into Records}{3}{1}{23}
-\secentry {Examining Fields}{3}{2}{24}
-\secentry {Non-constant Field Numbers}{3}{3}{26}
-\secentry {Changing the Contents of a Field}{3}{4}{27}
-\secentry {Specifying How Fields Are Separated}{3}{5}{28}
-\secentry {Multiple--Line Records}{3}{6}{31}
-\secentry {Assigning Variables on the Command Line}{3}{7}{32}
-\secentry {Explicit Input with {\fam \ttfam \tentt \rawbackslash \frenchspacing getline}\hbox {}}{3}{8}{32}
-\subsecentry {Closing Input Files}{3}{8}{1}{36}
-\chapentry {Printing Output}{4}{39}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing print}\hbox {} Statement}{4}{1}{39}
-\secentry {Examples of {\fam \ttfam \tentt \rawbackslash \frenchspacing print}\hbox {} Statements}{4}{2}{40}
-\secentry {Output Separators}{4}{3}{41}
-\secentry {Redirecting Output of {\fam \ttfam \tentt \rawbackslash \frenchspacing print}\hbox {} and {\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {}}{4}{4}{42}
-\subsecentry {Closing Output Files and Pipes}{4}{4}{1}{43}
-\secentry {Using {\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {} Statements For Fancier Printing}{4}{5}{44}
-\subsecentry {Introduction to the {\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {} Statement}{4}{5}{1}{45}
-\subsecentry {Format--Control Characters}{4}{5}{2}{45}
-\subsecentry {Modifiers for {\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {} Formats}{4}{5}{3}{46}
-\subsecentry {Examples of Using {\fam \ttfam \tentt \rawbackslash \frenchspacing printf}\hbox {}}{4}{5}{4}{46}
-\chapentry {Useful ``One-liners''}{5}{49}
-\chapentry {Patterns}{6}{51}
-\secentry {The Empty Pattern}{6}{1}{51}
-\secentry {Regular Expressions as Patterns}{6}{2}{52}
-\subsecentry {How to use Regular Expressions}{6}{2}{1}{52}
-\subsecentry {Regular Expression Operators}{6}{2}{2}{53}
-\secentry {Comparison Expressions as Patterns}{6}{3}{55}
-\secentry {Specifying Record Ranges With Patterns}{6}{4}{56}
-\secentry {{\fam \ttfam \tentt \rawbackslash \frenchspacing BEGIN}\hbox {} and {\fam \ttfam \tentt \rawbackslash \frenchspacing END}\hbox {} Special Patterns}{6}{5}{57}
-\secentry {Boolean Operators and Patterns}{6}{6}{58}
-\secentry {Conditional Patterns}{6}{7}{59}
-\chapentry {Actions: The Basics}{7}{61}
-\chapentry {Actions: Expressions}{8}{63}
-\secentry {Constant Expressions}{8}{1}{63}
-\secentry {Variables}{8}{2}{64}
-\secentry {Arithmetic Operators}{8}{3}{65}
-\secentry {String Concatenation}{8}{4}{65}
-\secentry {Comparison Expressions}{8}{5}{66}
-\secentry {Boolean Operators}{8}{6}{67}
-\secentry {Assignment Operators}{8}{7}{68}
-\secentry {Increment Operators}{8}{8}{70}
-\secentry {Conversion of Strings and Numbers}{8}{9}{71}
-\secentry {Conditional Expressions}{8}{10}{72}
-\secentry {Function Calls}{8}{11}{73}
-\chapentry {Actions: Statements}{9}{75}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing if}\hbox {} Statement}{9}{1}{75}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing while}\hbox {} Statement}{9}{2}{76}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing do}\hbox {}--{\fam \ttfam \tentt \rawbackslash \frenchspacing while}\hbox {} Statement}{9}{3}{77}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing for}\hbox {} Statement}{9}{4}{77}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing break}\hbox {} Statement}{9}{5}{79}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing continue}\hbox {} Statement}{9}{6}{80}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing next}\hbox {} Statement}{9}{7}{81}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing exit}\hbox {} Statement}{9}{8}{82}
-\chapentry {Actions: Using Arrays in {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{10}{83}
-\secentry {Introduction to Arrays}{10}{1}{83}
-\secentry {Referring to an Array Element}{10}{2}{85}
-\secentry {Assigning Array Elements}{10}{3}{86}
-\secentry {Basic Example of an Array}{10}{4}{86}
-\secentry {Scanning All Elements of an Array}{10}{5}{87}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing delete}\hbox {} Statement}{10}{6}{88}
-\secentry {Multi--dimensional arrays}{10}{7}{89}
-\secentry {Scanning Multi--dimensional Arrays}{10}{8}{91}
-\chapentry {Built--in functions}{11}{93}
-\secentry {Numeric Built--in Functions}{11}{1}{93}
-\secentry {Built--in Functions for String Manipulation}{11}{2}{95}
-\secentry {Built--in Functions for I/O to Files and Commands}{11}{3}{98}
-\chapentry {User--defined Functions}{12}{99}
-\secentry {Syntax of Function Definitions}{12}{1}{99}
-\secentry {Function Definition Example}{12}{2}{100}
-\secentry {Caveats of Function Calling}{12}{3}{101}
-\secentry {The {\fam \ttfam \tentt \rawbackslash \frenchspacing return}\hbox {} statement}{12}{4}{102}
-\chapentry {Special Variables}{13}{105}
-\secentry {Special Variables That Control {\fam \ttfam \tentt \rawbackslash \frenchspacing awk}\hbox {}}{13}{1}{105}
-\secentry {Special Variables That Convey Information to You}{13}{2}{106}
-\chapentry {Sample Program}{Appendix \char 65}{109}
-\chapentry {Implementation Notes}{Appendix \char 66}{111}
-\secentry {GNU Extensions to the AWK Language}{\char 66}{1}{111}
-\secentry {Extensions Likely To Appear In A Future Release}{\char 66}{2}{111}
-\secentry {Suggestions for Future Improvements}{\char 66}{3}{112}
-\secentry {Suggestions For Future Improvements of This Manual}{\char 66}{4}{113}
-\chapentry {Glossary}{Appendix \char 67}{115}
-\unnumbchapentry {Index}{119}
diff --git a/gawk.tp b/gawk.tp
deleted file mode 100644
index e69de29b..00000000
--- a/gawk.tp
+++ /dev/null
diff --git a/gawk.tps b/gawk.tps
deleted file mode 100644
index e69de29b..00000000
--- a/gawk.tps
+++ /dev/null
diff --git a/gawk.vr b/gawk.vr
deleted file mode 100644
index 9b2ba722..00000000
--- a/gawk.vr
+++ /dev/null
@@ -1,17 +0,0 @@
-\entry {ARGV}{19}{{\fam \ttfam \tentt \rawbackslash \frenchspacing ARGV}\hbox {}}
-\entry {OFS}{19}{{\fam \ttfam \tentt \rawbackslash \frenchspacing OFS}\hbox {}}
-\entry {ORS}{19}{{\fam \ttfam \tentt \rawbackslash \frenchspacing ORS}\hbox {}}
-\entry {RS}{19}{{\fam \ttfam \tentt \rawbackslash \frenchspacing RS}\hbox {}}
-\entry {FILENAME}{23}{{\fam \ttfam \tentt \rawbackslash \frenchspacing FILENAME}\hbox {}}
-\entry {RS}{23}{{\fam \ttfam \tentt \rawbackslash \frenchspacing RS}\hbox {}}
-\entry {NR}{24}{{\fam \ttfam \tentt \rawbackslash \frenchspacing NR}\hbox {}}
-\entry {FNR}{24}{{\fam \ttfam \tentt \rawbackslash \frenchspacing FNR}\hbox {}}
-\entry {NF}{25}{{\fam \ttfam \tentt \rawbackslash \frenchspacing NF}\hbox {}}
-\entry {FS}{28}{{\fam \ttfam \tentt \rawbackslash \frenchspacing FS}\hbox {}}
-\entry {OFS}{41}{{\fam \ttfam \tentt \rawbackslash \frenchspacing OFS}\hbox {}}
-\entry {ORS}{41}{{\fam \ttfam \tentt \rawbackslash \frenchspacing ORS}\hbox {}}
-\entry {OFMT}{71}{{\fam \ttfam \tentt \rawbackslash \frenchspacing OFMT}\hbox {}}
-\entry {SUBSEP}{89}{{\fam \ttfam \tentt \rawbackslash \frenchspacing SUBSEP}\hbox {}}
-\entry {RSTART}{95}{{\fam \ttfam \tentt \rawbackslash \frenchspacing RSTART}\hbox {}}
-\entry {RLENGTH}{95}{{\fam \ttfam \tentt \rawbackslash \frenchspacing RLENGTH}\hbox {}}
-\entry {ENVIRON}{106}{{\fam \ttfam \tentt \rawbackslash \frenchspacing ENVIRON}\hbox {}}
diff --git a/gawk.vrs b/gawk.vrs
deleted file mode 100644
index 0ee09c6d..00000000
--- a/gawk.vrs
+++ /dev/null
@@ -1,21 +0,0 @@
-\initial {A}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing ARGV}\hbox {}}{19}
-\initial {E}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing ENVIRON}\hbox {}}{106}
-\initial {F}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing FILENAME}\hbox {}}{23}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing FNR}\hbox {}}{24}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing FS}\hbox {}}{28}
-\initial {N}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing NF}\hbox {}}{25}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing NR}\hbox {}}{24}
-\initial {O}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing OFMT}\hbox {}}{71}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing OFS}\hbox {}}{19, 41}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing ORS}\hbox {}}{19, 41}
-\initial {R}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing RLENGTH}\hbox {}}{95}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing RS}\hbox {}}{19, 23}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing RSTART}\hbox {}}{95}
-\initial {S}
-\entry {{\fam \ttfam \tentt \rawbackslash \frenchspacing SUBSEP}\hbox {}}{89}
diff --git a/gnu.getopt.c b/gnu.getopt.c
deleted file mode 100644
index 93002de9..00000000
--- a/gnu.getopt.c
+++ /dev/null
@@ -1,417 +0,0 @@
-/* Getopt for GNU.
- Copyright (C) 1987, 1989 Free Software Foundation, Inc.
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 1, or (at your option)
- any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
-
-
-
-/* This version of `getopt' appears to the caller like standard Unix `getopt'
- but it behaves differently for the user, since it allows the user
- to intersperse the options with the other arguments.
-
- As `getopt' works, it permutes the elements of `argv' so that,
- when it is done, all the options precede everything else. Thus
- all application programs are extended to handle flexible argument order.
-
- Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
- Then the behavior is completely standard.
-
- GNU application programs can use a third alternative mode in which
- they can distinguish the relative order of options and other arguments. */
-
-#include <stdio.h>
-
-#ifdef sparc
-#include <alloca.h>
-#endif
-#if defined(USG) || defined(MSDOS)
-extern char *alloca();
-extern char *strchr();
-#define index strchr
-#define bcopy(s, d, l) memcpy((d), (s), (l))
-#endif
-
-/* For communication from `getopt' to the caller.
- When `getopt' finds an option that takes an argument,
- the argument value is returned here.
- Also, when `ordering' is RETURN_IN_ORDER,
- each non-option ARGV-element is returned here. */
-
-char *optarg = 0;
-
-/* Index in ARGV of the next element to be scanned.
- This is used for communication to and from the caller
- and for communication between successive calls to `getopt'.
-
- On entry to `getopt', zero means this is the first call; initialize.
-
- When `getopt' returns EOF, this is the index of the first of the
- non-option elements that the caller should itself scan.
-
- Otherwise, `optind' communicates from one call to the next
- how much of ARGV has been scanned so far. */
-
-int optind = 0;
-
-/* The next char to be scanned in the option-element
- in which the last option character we returned was found.
- This allows us to pick up the scan where we left off.
-
- If this is zero, or a null string, it means resume the scan
- by advancing to the next ARGV-element. */
-
-static char *nextchar;
-
-/* Callers store zero here to inhibit the error message
- for unrecognized options. */
-
-int opterr = 1;
-
-/* Describe how to deal with options that follow non-option ARGV-elements.
-
- UNSPECIFIED means the caller did not specify anything;
- the default is then REQUIRE_ORDER if the environment variable
- _OPTIONS_FIRST is defined, PERMUTE otherwise.
-
- REQUIRE_ORDER means don't recognize them as options.
- Stop option processing when the first non-option is seen.
- This is what Unix does.
-
- PERMUTE is the default. We permute the contents of `argv' as we scan,
- so that eventually all the options are at the end. This allows options
- to be given in any order, even with programs that were not written to
- expect this.
-
- RETURN_IN_ORDER is an option available to programs that were written
- to expect options and other ARGV-elements in any order and that care about
- the ordering of the two. We describe each non-option ARGV-element
- as if it were the argument of an option with character code zero.
- Using `-' as the first character of the list of option characters
- requests this mode of operation.
-
- The special argument `--' forces an end of option-scanning regardless
- of the value of `ordering'. In the case of RETURN_IN_ORDER, only
- `--' can cause `getopt' to return EOF with `optind' != ARGC. */
-
-static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
-
-/* Handle permutation of arguments. */
-
-/* Describe the part of ARGV that contains non-options that have
- been skipped. `first_nonopt' is the index in ARGV of the first of them;
- `last_nonopt' is the index after the last of them. */
-
-static int first_nonopt;
-static int last_nonopt;
-
-/* Exchange two adjacent subsequences of ARGV.
- One subsequence is elements [first_nonopt,last_nonopt)
- which contains all the non-options that have been skipped so far.
- The other is elements [last_nonopt,optind), which contains all
- the options processed since those non-options were skipped.
-
- `first_nonopt' and `last_nonopt' are relocated so that they describe
- the new indices of the non-options in ARGV after they are moved. */
-
-static void
-exchange (argv)
- char **argv;
-{
- int nonopts_size
- = (last_nonopt - first_nonopt) * sizeof (char *);
- char **temp = (char **) alloca (nonopts_size);
-
- /* Interchange the two blocks of data in argv. */
-
- bcopy (&argv[first_nonopt], temp, nonopts_size);
- bcopy (&argv[last_nonopt], &argv[first_nonopt],
- (optind - last_nonopt) * sizeof (char *));
- bcopy (temp, &argv[first_nonopt + optind - last_nonopt],
- nonopts_size);
-
- /* Update records for the slots the non-options now occupy. */
-
- first_nonopt += (optind - last_nonopt);
- last_nonopt = optind;
-}
-
-/* Scan elements of ARGV (whose length is ARGC) for option characters
- given in OPTSTRING.
-
- If an element of ARGV starts with '-', and is not exactly "-" or "--",
- then it is an option element. The characters of this element
- (aside from the initial '-') are option characters. If `getopt'
- is called repeatedly, it returns successively each of theoption characters
- from each of the option elements.
-
- If `getopt' finds another option character, it returns that character,
- updating `optind' and `nextchar' so that the next call to `getopt' can
- resume the scan with the following option character or ARGV-element.
-
- If there are no more option characters, `getopt' returns `EOF'.
- Then `optind' is the index in ARGV of the first ARGV-element
- that is not an option. (The ARGV-elements have been permuted
- so that those that are not options now come last.)
-
- OPTSTRING is a string containing the legitimate option characters.
- A colon in OPTSTRING means that the previous character is an option
- that wants an argument. The argument is taken from the rest of the
- current ARGV-element, or from the following ARGV-element,
- and returned in `optarg'.
-
- If an option character is seen that is not listed in OPTSTRING,
- return '?' after printing an error message. If you set `opterr' to
- zero, the error message is suppressed but we still return '?'.
-
- If a char in OPTSTRING is followed by a colon, that means it wants an arg,
- so the following text in the same ARGV-element, or the text of the following
- ARGV-element, is returned in `optarg. Two colons mean an option that
- wants an optional arg; if there is text in the current ARGV-element,
- it is returned in `optarg'.
-
- If OPTSTRING starts with `-', it requests a different method of handling the
- non-option ARGV-elements. See the comments about RETURN_IN_ORDER, above. */
-
-int
-getopt (argc, argv, optstring)
- int argc;
- char **argv;
- char *optstring;
-{
- /* Initialize the internal data when the first call is made.
- Start processing options with ARGV-element 1 (since ARGV-element 0
- is the program name); the sequence of previously skipped
- non-option ARGV-elements is empty. */
-
- if (optind == 0)
- {
- first_nonopt = last_nonopt = optind = 1;
-
- nextchar = 0;
-
- /* Determine how to handle the ordering of options and nonoptions. */
-
- if (optstring[0] == '-')
- ordering = RETURN_IN_ORDER;
- else if (getenv ("_POSIX_OPTION_ORDER") != 0)
- ordering = REQUIRE_ORDER;
- else
- ordering = PERMUTE;
- }
-
- if (nextchar == 0 || *nextchar == 0)
- {
- if (ordering == PERMUTE)
- {
- /* If we have just processed some options following some non-options,
- exchange them so that the options come first. */
-
- if (first_nonopt != last_nonopt && last_nonopt != optind)
- exchange (argv);
- else if (last_nonopt != optind)
- first_nonopt = optind;
-
- /* Now skip any additional non-options
- and extend the range of non-options previously skipped. */
-
- while (optind < argc
- && (argv[optind][0] != '-'
- || argv[optind][1] == 0))
- optind++;
- last_nonopt = optind;
- }
-
- /* Special ARGV-element `--' means premature end of options.
- Skip it like a null option,
- then exchange with previous non-options as if it were an option,
- then skip everything else like a non-option. */
-
- if (optind != argc && !strcmp (argv[optind], "--"))
- {
- optind++;
-
- if (first_nonopt != last_nonopt && last_nonopt != optind)
- exchange (argv);
- else if (first_nonopt == last_nonopt)
- first_nonopt = optind;
- last_nonopt = argc;
-
- optind = argc;
- }
-
- /* If we have done all the ARGV-elements, stop the scan
- and back over any non-options that we skipped and permuted. */
-
- if (optind == argc)
- {
- /* Set the next-arg-index to point at the non-options
- that we previously skipped, so the caller will digest them. */
- if (first_nonopt != last_nonopt)
- optind = first_nonopt;
- return EOF;
- }
-
- /* If we have come to a non-option and did not permute it,
- either stop the scan or describe it to the caller and pass it by. */
-
- if (argv[optind][0] != '-' || argv[optind][1] == 0)
- {
- if (ordering == REQUIRE_ORDER)
- return EOF;
- optarg = argv[optind++];
- return 0;
- }
-
- /* We have found another option-ARGV-element.
- Start decoding its characters. */
-
- nextchar = argv[optind] + 1;
- }
-
- /* Look at and handle the next option-character. */
-
- {
- char c = *nextchar++;
- char *temp = (char *) index (optstring, c);
-
- /* Increment `optind' when we start to process its last character. */
- if (*nextchar == 0)
- optind++;
-
- if (temp == 0 || c == ':')
- {
- if (opterr != 0)
- {
- if (c < 040 || c >= 0177)
- fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
- argv[0], c);
- else
- fprintf (stderr, "%s: unrecognized option `-%c'\n",
- argv[0], c);
- }
- return '?';
- }
- if (temp[1] == ':')
- {
- if (temp[2] == ':')
- {
- /* This is an option that accepts an argument optionally. */
- if (*nextchar != 0)
- {
- optarg = nextchar;
- optind++;
- }
- else
- optarg = 0;
- nextchar = 0;
- }
- else
- {
- /* This is an option that requires an argument. */
- if (*nextchar != 0)
- {
- optarg = nextchar;
- /* If we end this ARGV-element by taking the rest as an arg,
- we must advance to the next element now. */
- optind++;
- }
- else if (optind == argc)
- {
- if (opterr != 0)
- fprintf (stderr, "%s: no argument for `-%c' option\n",
- argv[0], c);
- c = '?';
- }
- else
- /* We already incremented `optind' once;
- increment it again when taking next ARGV-elt as argument. */
- optarg = argv[optind++];
- nextchar = 0;
- }
- }
- return c;
- }
-}
-
-#ifdef TEST
-
-/* Compile with -DTEST to make an executable for use in testing
- the above definition of `getopt'. */
-
-int
-main (argc, argv)
- int argc;
- char **argv;
-{
- char c;
- int digit_optind = 0;
-
- while (1)
- {
- int this_option_optind = optind;
- if ((c = getopt (argc, argv, "abc:d:0123456789")) == EOF)
- break;
-
- switch (c)
- {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- if (digit_optind != 0 && digit_optind != this_option_optind)
- printf ("digits occur in two different argv-elements.\n");
- digit_optind = this_option_optind;
- printf ("option %c\n", c);
- break;
-
- case 'a':
- printf ("option a\n");
- break;
-
- case 'b':
- printf ("option b\n");
- break;
-
- case 'c':
- printf ("option c with value `%s'\n", optarg);
- break;
-
- case '?':
- break;
-
- default:
- printf ("?? getopt returned character code 0%o ??\n", c);
- }
- }
-
- if (optind < argc)
- {
- printf ("non-option ARGV-elements: ");
- while (optind < argc)
- printf ("%s ", argv[optind++]);
- printf ("\n");
- }
-
- return 0;
-}
-
-#endif /* TEST */
-
diff --git a/io.c b/io.c
new file mode 100644
index 00000000..ac5f35fa
--- /dev/null
+++ b/io.c
@@ -0,0 +1,765 @@
+/*
+ * io.c - routines for dealing with input and output and records
+ */
+
+/*
+ * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
+ *
+ * This file is part of GAWK, the GNU implementation of the
+ * AWK Progamming Language.
+ *
+ * GAWK is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 1, or (at your option)
+ * any later version.
+ *
+ * GAWK is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with GAWK; see the file COPYING. If not, write to
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#include "awk.h"
+#ifndef O_RDONLY
+#include <fcntl.h>
+#endif
+#if defined(MSDOS)
+#include "popen.h"
+#endif
+#include <signal.h>
+
+extern FILE *popen();
+
+static void do_file();
+static IOBUF *nextfile();
+static int get_a_record();
+static int iop_close();
+static IOBUF *iop_alloc();
+static void close_one();
+static int close_redir();
+static IOBUF *gawk_popen();
+static int gawk_pclose();
+
+static struct redirect *red_head = NULL;
+static int getline_redirect = 0; /* "getline <file" being executed */
+
+extern char *line_buf;
+extern int output_is_tty;
+extern NODE *ARGC_node;
+extern NODE *ARGV_node;
+extern NODE **fields_arr;
+
+int field_num;
+
+static IOBUF *
+nextfile()
+{
+ static int i = 1;
+ static int files = 0;
+ static IOBUF *curfile = NULL;
+ char *arg;
+ char *cp;
+ int fd = -1;
+
+ if (curfile != NULL && curfile->cnt != EOF)
+ return curfile;
+ for (; i < (int) (ARGC_node->lnode->numbr); i++) {
+ arg = (*assoc_lookup(ARGV_node, tmp_number((AWKNUM) i)))->stptr;
+ if (*arg == '\0')
+ continue;
+ cp = strchr(arg, '=');
+ if (cp != NULL) {
+ *cp++ = '\0';
+ variable(arg)->var_value = make_string(cp, strlen(cp));
+ *--cp = '='; /* restore original text of ARGV */
+ } else {
+ files++;
+ if (STREQ(arg, "-"))
+ fd = 0;
+ else
+ fd = devopen(arg, "r");
+ if (fd == -1)
+ fatal("cannot open file `%s' for reading (%s)",
+ arg, strerror(errno));
+ /* NOTREACHED */
+ /* This is a kludge. */
+ deref = FILENAME_node->var_value;
+ do_deref();
+ FILENAME_node->var_value =
+ make_string(arg, strlen(arg));
+ FNR_node->var_value->numbr = 0.0;
+ i++;
+ break;
+ }
+ }
+ if (files == 0) {
+ files++;
+ /* no args. -- use stdin */
+ /* FILENAME is init'ed to "-" */
+ /* FNR is init'ed to 0 */
+ fd = 0;
+ }
+ if (fd == -1)
+ return NULL;
+ return curfile = iop_alloc(fd);
+}
+
+static IOBUF *
+iop_alloc(fd)
+int fd;
+{
+ IOBUF *iop;
+ struct stat stb;
+
+ /*
+ * System V doesn't have the file system block size in the
+ * stat structure. So we have to make some sort of reasonable
+ * guess. We use stdio's BUFSIZ, since that is what it was
+ * meant for in the first place.
+ */
+#ifdef BLKSIZE_MISSING
+#define DEFBLKSIZE BUFSIZ
+#else
+#define DEFBLKSIZE (stb.st_blksize ? stb.st_blksize : BUFSIZ)
+#endif
+
+ if (fd == -1)
+ return NULL;
+ emalloc(iop, IOBUF *, sizeof(IOBUF), "nextfile");
+ iop->flag = 0;
+ if (isatty(fd)) {
+ iop->flag |= IOP_IS_TTY;
+ iop->size = BUFSIZ;
+ } else if (fstat(fd, &stb) == -1)
+ fatal("can't stat fd %d (%s)", fd, strerror(errno));
+ else if (lseek(fd, 0L, 0) == -1)
+ iop->size = DEFBLKSIZE;
+ else
+ iop->size = (stb.st_size < DEFBLKSIZE ?
+ stb.st_size+1 : DEFBLKSIZE);
+ errno = 0;
+ iop->fd = fd;
+ emalloc(iop->buf, char *, iop->size, "nextfile");
+ iop->off = iop->buf;
+ iop->cnt = 0;
+ iop->secsiz = iop->size < BUFSIZ ? iop->size : BUFSIZ;
+ emalloc(iop->secbuf, char *, iop->secsiz, "nextfile");
+ return iop;
+}
+
+void
+do_input()
+{
+ IOBUF *iop;
+ extern int exiting;
+
+ while ((iop = nextfile()) != NULL) {
+ do_file(iop);
+ if (exiting)
+ break;
+ }
+}
+
+static int
+iop_close(iop)
+IOBUF *iop;
+{
+ int ret;
+
+ ret = close(iop->fd);
+ if (ret == -1)
+ warning("close of fd %d failed (%s)", iop->fd, strerror(errno));
+ free(iop->buf);
+ free(iop->secbuf);
+ free((char *)iop);
+ return ret == -1 ? 1 : 0;
+}
+
+/*
+ * This reads in a record from the input file
+ */
+static int
+inrec(iop)
+IOBUF *iop;
+{
+ int cnt;
+ int retval = 0;
+
+ cnt = get_a_record(&line_buf, iop);
+ if (cnt == EOF) {
+ cnt = 0;
+ retval = 1;
+ } else {
+ if (!getline_redirect) {
+ assign_number(&NR_node->var_value,
+ NR_node->var_value->numbr + 1.0);
+ assign_number(&FNR_node->var_value,
+ FNR_node->var_value->numbr + 1.0);
+ }
+ }
+ set_record(line_buf, cnt);
+
+ return retval;
+}
+
+static void
+do_file(iop)
+IOBUF *iop;
+{
+ /* This is where it spends all its time. The infamous MAIN LOOP */
+ if (inrec(iop) == 0)
+ while (interpret(expression_value) && inrec(iop) == 0)
+ ;
+ (void) iop_close(iop);
+}
+
+int
+get_rs()
+{
+ register NODE *tmp;
+
+ tmp = force_string(RS_node->var_value);
+ if (tmp->stlen == 0)
+ return 0;
+ return *(tmp->stptr);
+}
+
+/* Redirection for printf and print commands */
+struct redirect *
+redirect(tree, errflg)
+NODE *tree;
+int *errflg;
+{
+ register NODE *tmp;
+ register struct redirect *rp;
+ register char *str;
+ int tflag = 0;
+ int outflag = 0;
+ char *direction = "to";
+ char *mode;
+ int fd;
+
+ switch (tree->type) {
+ case Node_redirect_append:
+ tflag = RED_APPEND;
+ case Node_redirect_output:
+ outflag = (RED_FILE|RED_WRITE);
+ tflag |= outflag;
+ break;
+ case Node_redirect_pipe:
+ tflag = (RED_PIPE|RED_WRITE);
+ break;
+ case Node_redirect_pipein:
+ tflag = (RED_PIPE|RED_READ);
+ break;
+ case Node_redirect_input:
+ tflag = (RED_FILE|RED_READ);
+ break;
+ default:
+ fatal ("invalid tree type %d in redirect()", tree->type);
+ break;
+ }
+ tmp = force_string(tree_eval(tree->subnode));
+ str = tmp->stptr;
+ for (rp = red_head; rp != NULL; rp = rp->next)
+ if (STREQ(rp->value, str)
+ && ((rp->flag & ~RED_NOBUF) == tflag
+ || (outflag
+ && (rp->flag & (RED_FILE|RED_WRITE)) == outflag)))
+ break;
+ if (rp == NULL) {
+ emalloc(rp, struct redirect *, sizeof(struct redirect),
+ "redirect");
+ emalloc(str, char *, tmp->stlen+1, "redirect");
+ memcpy(str, tmp->stptr, tmp->stlen+1);
+ rp->value = str;
+ rp->flag = tflag;
+ rp->offset = 0;
+ rp->fp = NULL;
+ rp->iop = NULL;
+ /* maintain list in most-recently-used first order */
+ if (red_head)
+ red_head->prev = rp;
+ rp->prev = NULL;
+ rp->next = red_head;
+ red_head = rp;
+ }
+ while (rp->fp == NULL && rp->iop == NULL) {
+ mode = NULL;
+ errno = 0;
+ switch (tree->type) {
+ case Node_redirect_output:
+ mode = "w";
+ break;
+ case Node_redirect_append:
+ mode = "a";
+ break;
+ case Node_redirect_pipe:
+ if ((rp->fp = popen(str, "w")) == NULL)
+ fatal("can't open pipe (\"%s\") for output (%s)",
+ str, strerror(errno));
+ rp->flag |= RED_NOBUF;
+ break;
+ case Node_redirect_pipein:
+ direction = "from";
+ if (gawk_popen(str, rp) == NULL)
+ fatal("can't open pipe (\"%s\") for input (%s)",
+ str, strerror(errno));
+ break;
+ case Node_redirect_input:
+ direction = "from";
+ rp->iop = iop_alloc(devopen(str, "r"));
+ break;
+ default:
+ cant_happen();
+ }
+ if (mode != NULL) {
+ fd = devopen(str, mode);
+ if (fd != -1) {
+ rp->fp = fdopen(fd, mode);
+ if (isatty(fd))
+ rp->flag |= RED_NOBUF;
+ }
+ }
+ if (rp->fp == NULL && rp->iop == NULL) {
+ /* too many files open -- close one and try again */
+ if (errno == ENFILE || errno == EMFILE)
+ close_one();
+ else {
+ /*
+ * Some other reason for failure.
+ *
+ * On redirection of input from a file,
+ * just return an error, so e.g. getline
+ * can return -1. For output to file,
+ * complain. The shell will complain on
+ * a bad command to a pipe.
+ */
+ *errflg = 1;
+ if (tree->type == Node_redirect_output
+ || tree->type == Node_redirect_append)
+ fatal("can't redirect %s `%s' (%s)",
+ direction, str, strerror(errno));
+ else
+ return NULL;
+ }
+ }
+ }
+ if (rp->offset != 0) /* this file was previously open */
+ if (fseek(rp->fp, rp->offset, 0) == -1)
+ fatal("can't seek to %ld on `%s' (%s)",
+ rp->offset, str, strerror(errno));
+ free_temp(tmp);
+ return rp;
+}
+
+static void
+close_one()
+{
+ register struct redirect *rp;
+ register struct redirect *rplast = NULL;
+
+ /* go to end of list first, to pick up least recently used entry */
+ for (rp = red_head; rp != NULL; rp = rp->next)
+ rplast = rp;
+ /* now work back up through the list */
+ for (rp = rplast; rp != NULL; rp = rp->prev)
+ if (rp->fp && (rp->flag & RED_FILE)) {
+ rp->offset = ftell(rp->fp);
+ if (fclose(rp->fp))
+ warning("close of \"%s\" failed (%s).",
+ rp->value, strerror(errno));
+ rp->fp = NULL;
+ break;
+ }
+ if (rp == NULL)
+ /* surely this is the only reason ??? */
+ fatal("too many pipes or input files open");
+}
+
+NODE *
+do_close(tree)
+NODE *tree;
+{
+ NODE *tmp;
+ register struct redirect *rp;
+
+ tmp = force_string(tree_eval(tree->subnode));
+ for (rp = red_head; rp != NULL; rp = rp->next) {
+ if (STREQ(rp->value, tmp->stptr))
+ break;
+ }
+ free_temp(tmp);
+ if (rp == NULL) /* no match */
+ return tmp_number((AWKNUM) 0.0);
+ return tmp_number((AWKNUM)close_redir(rp));
+}
+
+static int
+close_redir(rp)
+register struct redirect *rp;
+{
+ int status = 0;
+
+ if ((rp->flag & (RED_PIPE|RED_WRITE)) == (RED_PIPE|RED_WRITE))
+ status = pclose(rp->fp);
+ else if (rp->fp)
+ status = fclose(rp->fp);
+ else if (rp->iop) {
+ if (rp->flag & RED_PIPE)
+ status = gawk_pclose(rp);
+ else
+ status = iop_close(rp->iop);
+
+ }
+ /* SVR4 awk checks and warns about status of close */
+ if (status)
+ warning("failure status (%d) on %s close of \"%s\" (%s).",
+ status,
+ (rp->flag & RED_PIPE) ? "pipe" :
+ "file", rp->value, strerror(errno));
+ if (rp->next)
+ rp->next->prev = rp->prev;
+ if (rp->prev)
+ rp->prev->next = rp->next;
+ else
+ red_head = rp->next;
+ free(rp->value);
+ free((char *)rp);
+ return status;
+}
+
+int
+flush_io ()
+{
+ register struct redirect *rp;
+ int status = 0;
+
+ errno = 0;
+ if (fflush(stdout)) {
+ warning("error writing standard output (%s).", strerror(errno));
+ status++;
+ }
+ errno = 0;
+ if (fflush(stderr)) {
+ warning("error writing standard error (%s).", strerror(errno));
+ status++;
+ }
+ for (rp = red_head; rp != NULL; rp = rp->next)
+ /* flush both files and pipes, what the heck */
+ if ((rp->flag & RED_WRITE) && rp->fp != NULL)
+ if (fflush(rp->fp)) {
+ warning("%s flush of \"%s\" failed (%s).",
+ (rp->flag & RED_PIPE) ? "pipe" :
+ "file", rp->value, strerror(errno));
+ status++;
+ }
+ return status;
+}
+
+int
+close_io ()
+{
+ register struct redirect *rp;
+ int status = 0;
+
+ for (rp = red_head; rp != NULL; rp = rp->next)
+ if (close_redir(rp))
+ status++;
+ return status;
+}
+
+/* devopen --- handle /dev/std{in,out,err}, /dev/fd/N, regular files */
+int
+devopen (name, mode)
+char *name, *mode;
+{
+ int openfd = -1;
+ FILE *fdopen ();
+ char *cp;
+ int flag = 0;
+
+ switch(mode[0]) {
+ case 'r':
+ flag = O_RDONLY;
+ break;
+
+ case 'w':
+ flag = O_WRONLY|O_CREAT|O_TRUNC;
+ break;
+
+ case 'a':
+ flag = O_WRONLY|O_APPEND|O_CREAT;
+ break;
+ default:
+ cant_happen();
+ }
+
+#if defined(STRICT) || defined(NO_DEV_FD)
+ return (open (name, flag, 0666));
+#else
+ if (strict)
+ return (open (name, flag, 0666));
+
+ if (!STREQN (name, "/dev/", 5))
+ return (open (name, flag, 0666));
+ else
+ cp = name + 5;
+
+ /* XXX - first three tests ignore mode */
+ if (STREQ(cp, "stdin"))
+ return (0);
+ else if (STREQ(cp, "stdout"))
+ return (1);
+ else if (STREQ(cp, "stderr"))
+ return (2);
+ else if (STREQN(cp, "fd/", 3)) {
+ cp += 3;
+ if (sscanf (cp, "%d", & openfd) == 1 && openfd >= 0)
+ /* got something */
+ return openfd;
+ else
+ return -1;
+ } else
+ return (open (name, flag, 0666));
+#endif
+}
+
+static IOBUF *
+gawk_popen(cmd, rp)
+char *cmd;
+struct redirect *rp;
+{
+ int p[2];
+ register int pid;
+
+ rp->pid = -1;
+ rp->iop = NULL;
+ if (pipe(p) < 0)
+ return NULL;
+ if((pid = fork()) == 0) {
+ close(p[0]);
+ dup2(p[1], 1);
+ close(p[1]);
+ execl("/bin/sh", "sh", "-c", cmd, 0);
+ _exit(127);
+ }
+ if(pid == -1)
+ return NULL;
+ rp->pid = pid;
+ close(p[1]);
+ return (rp->iop = iop_alloc(p[0]));
+}
+
+static int
+gawk_pclose(rp)
+struct redirect *rp;
+{
+ void (*hstat)(), (*istat)(), (*qstat)();
+ int pid;
+ int status;
+ struct redirect *redp;
+ extern int errno;
+
+ iop_close(rp->iop);
+ if (rp->pid == -1)
+ return rp->status;
+ hstat = signal(SIGHUP, SIG_IGN);
+ istat = signal(SIGINT, SIG_IGN);
+ qstat = signal(SIGQUIT, SIG_IGN);
+ for (;;) {
+ pid = wait(&status);
+ if (pid == -1 && errno == ECHILD)
+ break;
+ else if (pid == rp->pid) {
+ rp->pid = -1;
+ rp->status = status;
+ break;
+ } else {
+ for (redp = red_head; redp != NULL; redp = redp->next)
+ if (pid == redp->pid) {
+ redp->pid = -1;
+ redp->status = status;
+ break;
+ }
+ }
+ }
+ signal(SIGHUP, hstat);
+ signal(SIGINT, istat);
+ signal(SIGQUIT, qstat);
+ return(rp->status);
+}
+
+#define DO_END_OF_BUF len = bp - iop->off;\
+ used = last - start;\
+ while (len + used > iop->secsiz) {\
+ iop->secsiz *= 2;\
+ erealloc(iop->secbuf,char *,iop->secsiz,"get");\
+ }\
+ last = iop->secbuf + used;\
+ start = iop->secbuf;\
+ memcpy(last, iop->off, len);\
+ last += len;\
+ iop->cnt = read(iop->fd, iop->buf, iop->size);\
+ if (iop->cnt < 0)\
+ return iop->cnt;\
+ end_data = iop->buf + iop->cnt;\
+ iop->off = bp = iop->buf;
+
+#define DO_END_OF_DATA iop->cnt = read(iop->fd, end_data, end_buf - end_data);\
+ if (iop->cnt < 0)\
+ return iop->cnt;\
+ end_data += iop->cnt;\
+ if (iop->cnt == 0)\
+ break;\
+ iop->cnt = end_data - iop->buf;
+
+static int
+get_a_record(res, iop)
+char **res;
+IOBUF *iop;
+{
+ register char *end_data;
+ register char *end_buf;
+ char *start;
+ register char *bp;
+ register char *last;
+ int len, used;
+ register char rs = get_rs();
+
+ if (iop->cnt < 0)
+ return iop->cnt;
+ if ((iop->flag & IOP_IS_TTY) && output_is_tty)
+ fflush(stdout);
+ end_data = iop->buf + iop->cnt;
+ if (iop->off >= end_data) {
+ iop->cnt = read(iop->fd, iop->buf, iop->size);
+ if (iop->cnt <= 0)
+ return iop->cnt = EOF;
+ end_data = iop->buf + iop->cnt;
+ iop->off = iop->buf;
+ }
+ last = start = bp = iop->off;
+ end_buf = iop->buf + iop->size;
+ if (rs == 0) {
+ while (!(*bp == '\n' && bp != iop->buf && bp[-1] == '\n')) {
+ if (++bp == end_buf) {
+ DO_END_OF_BUF
+ }
+ if (bp == end_data) {
+ DO_END_OF_DATA
+ }
+ }
+ if (*bp == '\n' && bp != iop->off && bp[-1] == '\n') {
+ int tmp = 0;
+
+ /* allow for more than two newlines */
+ while (*bp == '\n') {
+ tmp++;
+ if (++bp == end_buf) {
+ DO_END_OF_BUF
+ }
+ if (bp == end_data) {
+ DO_END_OF_DATA
+ }
+ }
+ iop->off = bp;
+ bp -= 1 + tmp;
+ } else if (bp != iop->buf && bp[-1] != '\n') {
+ warning("record not terminated");
+ iop->off = bp + 2;
+ } else {
+ bp--;
+ iop->off = bp + 2;
+ }
+ } else {
+ while (*bp++ != rs) {
+ if (bp == end_buf) {
+ DO_END_OF_BUF
+ }
+ if (bp == end_data) {
+ DO_END_OF_DATA
+ }
+ }
+ if (*--bp != rs) {
+ warning("record not terminated");
+ bp++;
+ }
+ iop->off = bp + 1;
+ }
+ if (start == iop->secbuf) {
+ len = bp - iop->buf;
+ if (len > 0) {
+ used = last - start;
+ while (len + used > iop->secsiz) {
+ iop->secsiz *= 2;
+ erealloc(iop->secbuf,char *,iop->secsiz,"get2");
+ }
+ last = iop->secbuf + used;
+ start = iop->secbuf;
+ memcpy(last, iop->buf, len);
+ last += len;
+ }
+ } else
+ last = bp;
+ *last = '\0';
+ *res = start;
+ return last - start;
+}
+
+NODE *
+do_getline(tree)
+NODE *tree;
+{
+ struct redirect *rp;
+ IOBUF *iop;
+ int cnt;
+ NODE **lhs;
+ int redir_error = 0;
+
+ if (tree->rnode == NULL) { /* no redirection */
+ iop = nextfile();
+ if (iop == NULL) /* end of input */
+ return tmp_number((AWKNUM) 0.0);
+ } else {
+ rp = redirect(tree->rnode, &redir_error);
+ if (rp == NULL && redir_error) /* failed redirect */
+ return tmp_number((AWKNUM) -1.0);
+ iop = rp->iop;
+ getline_redirect++;
+ }
+ if (tree->lnode == NULL) { /* no optional var. -- read in $0 */
+ if (inrec(iop) != 0) {
+ getline_redirect = 0;
+ return tmp_number((AWKNUM) 0.0);
+ }
+ } else { /* read in a named variable */
+ char *s = NULL;
+
+ lhs = get_lhs(tree->lnode, 1);
+ cnt = get_a_record(&s, iop);
+ if (!getline_redirect) {
+ assign_number(&NR_node->var_value,
+ NR_node->var_value->numbr + 1.0);
+ assign_number(&FNR_node->var_value,
+ FNR_node->var_value->numbr + 1.0);
+ }
+ if (cnt == EOF) {
+ getline_redirect = 0;
+ free(s);
+ return tmp_number((AWKNUM) 0.0);
+ }
+ *lhs = make_string(s, strlen(s));
+ do_deref();
+ /* we may have to regenerate $0 here! */
+ if (field_num == 0)
+ set_record(fields_arr[0]->stptr, fields_arr[0]->stlen);
+ field_num = -1;
+ }
+ getline_redirect = 0;
+ return tmp_number((AWKNUM) 1.0);
+}
diff --git a/main.c b/main.c
new file mode 100644
index 00000000..dbafe917
--- /dev/null
+++ b/main.c
@@ -0,0 +1,548 @@
+/*
+ * main.c -- Expression tree constructors and main program for gawk.
+ */
+
+/*
+ * Copyright (C) 1986, 1988, 1989 the Free Software Foundation, Inc.
+ *
+ * This file is part of GAWK, the GNU implementation of the
+ * AWK Progamming Language.
+ *
+ * GAWK is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 1, or (at your option)
+ * any later version.
+ *
+ * GAWK is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with GAWK; see the file COPYING. If not, write to
+ * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#include "awk.h"
+#include "patchlevel.h"
+#include <signal.h>
+
+extern int yyparse();
+extern void do_input();
+extern int close_io();
+extern void init_fields();
+extern int getopt();
+extern int re_set_syntax();
+extern NODE *node();
+
+static void usage();
+static void set_fs();
+static void init_vars();
+static void init_args();
+static NODE *spc_var();
+static void pre_assign();
+static void copyleft();
+
+/* These nodes store all the special variables AWK uses */
+NODE *FS_node, *NF_node, *RS_node, *NR_node;
+NODE *FILENAME_node, *OFS_node, *ORS_node, *OFMT_node;
+NODE *FNR_node, *RLENGTH_node, *RSTART_node, *SUBSEP_node;
+NODE *ENVIRON_node, *IGNORECASE_node;
+NODE *ARGC_node, *ARGV_node;
+
+/*
+ * The parse tree and field nodes are stored here. Parse_end is a dummy item
+ * used to free up unneeded fields without freeing the program being run
+ */
+int errcount = 0; /* error counter, used by yyerror() */
+
+/* The global null string */
+NODE *Nnull_string;
+
+/* The name the program was invoked under, for error messages */
+char *myname;
+
+/* A block of AWK code to be run before running the program */
+NODE *begin_block = 0;
+
+/* A block of AWK code to be run after the last input file */
+NODE *end_block = 0;
+
+int exiting = 0; /* Was an "exit" statement executed? */
+int exit_val = 0; /* optional exit value */
+
+#ifdef DEBUG
+/* non-zero means in debugging is enabled. Probably not very useful */
+int debugging = 0;
+extern int yydebug;
+#endif
+
+int tempsource = 0; /* source is in a temp file */
+char **sourcefile = NULL; /* source file name(s) */
+int numfiles = -1; /* how many source files */
+
+int strict = 0; /* turn off gnu extensions */
+
+int output_is_tty = 0; /* control flushing of output */
+
+NODE *expression_value;
+
+/*
+ * for strict to work, legal options must be first
+ *
+ * Unfortunately, -a and -e are orthogonal to -c.
+ */
+#define EXTENSIONS 8 /* where to clear */
+#ifdef DEBUG
+char awk_opts[] = "F:f:v:caeCVdD";
+#else
+char awk_opts[] = "F:f:v:caeCV";
+#endif
+
+int
+main(argc, argv)
+int argc;
+char **argv;
+{
+#ifdef DEBUG
+ /* Print out the parse tree. For debugging */
+ register int dotree = 0;
+#endif
+ extern char *version_string;
+ FILE *fp;
+ int c;
+ extern int opterr, optind;
+ extern char *optarg;
+ extern char *strrchr();
+ extern char *tmpnam();
+ extern int catchsig();
+ int i;
+ int nostalgia;
+#ifdef somtime_in_the_future
+ int regex_mode = RE_SYNTAX_POSIX_EGREP;
+#else
+ int regex_mode = RE_SYNTAX_AWK;
+#endif
+
+ (void) signal(SIGFPE, catchsig);
+ (void) signal(SIGSEGV, catchsig);
+
+ myname = strrchr(argv[0], '/');
+ if (myname == NULL)
+ myname = argv[0];
+ else
+ myname++;
+ if (argc < 2)
+ usage();
+
+ /* initialize the null string */
+ Nnull_string = make_string("", 0);
+ Nnull_string->numbr = 0.0;
+ Nnull_string->type = Node_val;
+ Nnull_string->flags = (PERM|STR|NUM|NUMERIC);
+
+ /* Set up the special variables */
+
+ /*
+ * Note that this must be done BEFORE arg parsing else -F
+ * breaks horribly
+ */
+ init_vars();
+
+ /* worst case */
+ emalloc(sourcefile, char **, argc * sizeof(char *), "main");
+
+
+#ifdef STRICT /* strict new awk compatibility */
+ strict = 1;
+ awk_opts[EXTENSIONS] = '\0';
+#endif
+
+#ifndef STRICT
+ /* undocumented feature, inspired by nostalgia, and a T-shirt */
+ nostalgia = 0;
+ for (i = 1; i < argc && argv[i][0] == '-'; i++) {
+ if (argv[i][1] == '-') /* -- */
+ break;
+ else if (argv[i][1] == 'c') { /* compatibility mode */
+ nostalgia = 0;
+ break;
+ } else if (STREQ(&argv[i][1], "nostalgia"))
+ nostalgia = 1;
+ /* keep looping, in case -c after -nostalgia */
+ }
+ if (nostalgia) {
+ fprintf (stderr, "awk: bailing out near line 1\n");
+ abort();
+ }
+#endif
+
+ while ((c = getopt (argc, argv, awk_opts)) != EOF) {
+ switch (c) {
+#ifdef DEBUG
+ case 'd':
+ debugging++;
+ dotree++;
+ break;
+
+ case 'D':
+ debugging++;
+ yydebug = 2;
+ break;
+#endif
+
+#ifndef STRICT
+ case 'c':
+ strict = 1;
+ break;
+#endif
+
+ case 'F':
+ set_fs(optarg);
+ break;
+
+ case 'f':
+ /*
+ * a la MKS awk, allow multiple -f options.
+ * this makes function libraries real easy.
+ * most of the magic is in the scanner.
+ */
+ sourcefile[++numfiles] = optarg;
+ break;
+
+ case 'v':
+ pre_assign(optarg);
+ break;
+
+ case 'V':
+ fprintf(stderr, "%s, patchlevel %d\n",
+ version_string, PATCHLEVEL);
+ break;
+
+ case 'C':
+ copyleft();
+ break;
+
+ case 'a': /* use old fashioned awk regexps */
+ regex_mode = RE_SYNTAX_AWK;
+ break;
+
+ case 'e': /* use egrep style regexps, per Posix */
+ regex_mode = RE_SYNTAX_POSIX_EGREP;
+ break;
+
+ case '?':
+ default:
+ /* getopt will print a message for us */
+ /* S5R4 awk ignores bad options and keeps going */
+ break;
+ }
+ }
+
+ /* Tell the regex routines how they should work. . . */
+ (void) re_set_syntax(regex_mode);
+
+#ifdef DEBUG
+ setbuf(stdout, (char *) NULL); /* make debugging easier */
+#endif
+ if (isatty(fileno(stdout)))
+ output_is_tty = 1;
+ /* No -f option, use next arg */
+ /* write to temp file and save sourcefile name */
+ if (numfiles == -1) {
+ int i;
+
+ if (optind > argc - 1) /* no args left */
+ usage();
+ numfiles++;
+ i = strlen (argv[optind]);
+ if (i == 0) { /* sanity check */
+ fprintf(stderr, "%s: empty program text\n", myname);
+ usage();
+ /* NOTREACHED */
+ }
+ sourcefile[0] = tmpnam((char *) NULL);
+ if ((fp = fopen (sourcefile[0], "w")) == NULL)
+ fatal("could not save source prog in temp file (%s)",
+ strerror(errno));
+ if (fwrite (argv[optind], 1, i, fp) == 0)
+ fatal(
+ "could not write source program to temp file (%s)",
+ strerror(errno));
+ if (argv[optind][i-1] != '\n')
+ putc ('\n', fp);
+ (void) fclose (fp);
+ tempsource++;
+ optind++;
+ }
+ init_args(optind, argc, myname, argv);
+
+ /* Read in the program */
+ if (yyparse() || errcount)
+ exit(1);
+
+#ifdef DEBUG
+ if (dotree)
+ print_parse_tree(expression_value);
+#endif
+ /* Set up the field variables */
+ init_fields();
+
+ if (begin_block)
+ (void) interpret(begin_block);
+ if (!exiting && (expression_value || end_block))
+ do_input();
+ if (end_block)
+ (void) interpret(end_block);
+ if (close_io() != 0 && exit_val == 0)
+ exit_val = 1;
+ exit(exit_val);
+}
+
+static void
+usage()
+{
+ char *opt1 = " -f progfile [--]";
+ char *opt2 = " [--] 'program'";
+#ifdef STRICT
+ char *regops = " [-ae] [-F fs] [-v var=val]"
+#else
+ char *regops = " [-aecCV] [-F fs] [-v var=val]";
+#endif
+
+ fprintf(stderr, "usage: %s%s%s file ...\n %s%s%s file ...\n",
+ myname, regops, opt1, myname, regops, opt2);
+ exit(11);
+}
+
+/* Generate compiled regular expressions */
+struct re_pattern_buffer *
+make_regexp(s, ignorecase)
+NODE *s;
+int ignorecase;
+{
+ struct re_pattern_buffer *rp;
+ char *err;
+
+ emalloc(rp, struct re_pattern_buffer *, sizeof(*rp), "make_regexp");
+ memset((char *) rp, 0, sizeof(*rp));
+ emalloc(rp->buffer, char *, 16, "make_regexp");
+ rp->allocated = 16;
+ emalloc(rp->fastmap, char *, 256, "make_regexp");
+
+ if (! strict && ignorecase)
+ rp->translate = casetable;
+ else
+ rp->translate = NULL;
+ if ((err = re_compile_pattern(s->stptr, s->stlen, rp)) != NULL)
+ fatal("%s: /%s/", err, s->stptr);
+ free_temp(s);
+ return rp;
+}
+
+struct re_pattern_buffer *
+mk_re_parse(s, ignorecase)
+char *s;
+int ignorecase;
+{
+ char *src;
+ register char *dest;
+ register int c;
+ int in_brack = 0;
+
+ for (dest = src = s; *src != '\0';) {
+ if (*src == '\\') {
+ c = *++src;
+ switch (c) {
+ case '/':
+ case 'a':
+ case 'b':
+ case 'f':
+ case 'n':
+ case 'r':
+ case 't':
+ case 'v':
+ case 'x':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ c = parse_escape(&src);
+ if (c < 0)
+ cant_happen();
+ *dest++ = c;
+ break;
+ default:
+ *dest++ = '\\';
+ *dest++ = c;
+ src++;
+ break;
+ }
+ } else if (*src == '/' && ! in_brack)
+ break;
+ else {
+ if (*src == '[')
+ in_brack = 1;
+ else if (*src == ']')
+ in_brack = 0;
+
+ *dest++ = *src++;
+ }
+ }
+ return make_regexp(tmp_string(s, dest-s), ignorecase);
+}
+
+static void
+copyleft ()
+{
+ extern char *version_string;
+ char *cp;
+ static char blurb[] =
+"Copyright (C) 1989, Free Software Foundation.\n\
+GNU Awk comes with ABSOLUTELY NO WARRANTY. This is free software, and\n\
+you are welcome to distribute it under the terms of the GNU General\n\
+Public License, which covers both the warranty information and the\n\
+terms for redistribution.\n\n\
+You should have received a copy of the GNU General Public License along\n\
+with this program; if not, write to the Free Software Foundation, Inc.,\n\
+675 Mass Ave, Cambridge, MA 02139, USA.\n";
+
+ fprintf (stderr, "%s, patchlevel %d\n", version_string, PATCHLEVEL);
+ fputs(blurb, stderr);
+ fflush(stderr);
+}
+
+static void
+set_fs(str)
+char *str;
+{
+ register NODE **tmp;
+
+ tmp = get_lhs(FS_node, 0);
+ /*
+ * Only if in full compatibility mode check for the stupid special
+ * case so -F\t works as documented in awk even though the shell
+ * hands us -Ft. Bleah!
+ */
+ if (strict && str[0] == 't' && str[1] == '\0')
+ str[0] = '\t';
+ *tmp = make_string(str, 1);
+ do_deref();
+}
+
+static void
+init_args(argc0, argc, argv0, argv)
+int argc0, argc;
+char *argv0;
+char **argv;
+{
+ int i, j;
+ NODE **aptr;
+
+ ARGV_node = spc_var("ARGV", Nnull_string);
+ aptr = assoc_lookup(ARGV_node, tmp_number(0.0));
+ *aptr = make_string(argv0, strlen(argv0));
+ for (i = argc0, j = 1; i < argc; i++) {
+ aptr = assoc_lookup(ARGV_node, tmp_number((AWKNUM) j));
+ *aptr = make_string(argv[i], strlen(argv[i]));
+ j++;
+ }
+ ARGC_node = spc_var("ARGC", make_number((AWKNUM) j));
+}
+
+/*
+ * Set all the special variables to their initial values.
+ */
+static void
+init_vars()
+{
+ extern char **environ;
+ char *var, *val;
+ NODE **aptr;
+ int i;
+
+ FS_node = spc_var("FS", make_string(" ", 1));
+ NF_node = spc_var("NF", make_number(-1.0));
+ RS_node = spc_var("RS", make_string("\n", 1));
+ NR_node = spc_var("NR", make_number(0.0));
+ FNR_node = spc_var("FNR", make_number(0.0));
+ FILENAME_node = spc_var("FILENAME", make_string("-", 1));
+ OFS_node = spc_var("OFS", make_string(" ", 1));
+ ORS_node = spc_var("ORS", make_string("\n", 1));
+ OFMT_node = spc_var("OFMT", make_string("%.6g", 4));
+ RLENGTH_node = spc_var("RLENGTH", make_number(0.0));
+ RSTART_node = spc_var("RSTART", make_number(0.0));
+ SUBSEP_node = spc_var("SUBSEP", make_string("\034", 1));
+ IGNORECASE_node = spc_var("IGNORECASE", make_number(0.0));
+
+ ENVIRON_node = spc_var("ENVIRON", Nnull_string);
+ for (i = 0; environ[i]; i++) {
+ static char nullstr[] = "";
+
+ var = environ[i];
+ val = strchr(var, '=');
+ if (val)
+ *val++ = '\0';
+ else
+ val = nullstr;
+ aptr = assoc_lookup(ENVIRON_node, tmp_string(var, strlen (var)));
+ *aptr = make_string(val, strlen (val));
+
+ /* restore '=' so that system() gets a valid environment */
+ if (val != nullstr)
+ *--val = '=';
+ }
+}
+
+/* Create a special variable */
+static NODE *
+spc_var(name, value)
+char *name;
+NODE *value;
+{
+ register NODE *r;
+
+ if ((r = lookup(variables, name)) == NULL)
+ r = install(variables, name, node(value, Node_var, (NODE *) NULL));
+ return r;
+}
+
+static void
+pre_assign(v)
+char *v;
+{
+ char *cp;
+
+ cp = strchr(v, '=');
+ if (cp != NULL) {
+ *cp++ = '\0';
+ variable(v)->var_value = make_string(cp, strlen(cp));
+ } else {
+ fprintf (stderr,
+ "%s: '%s' argument to -v not in 'var=value' form\n",
+ myname, v);
+ usage();
+ }
+}
+
+int
+catchsig(sig, code)
+int sig, code;
+{
+#ifdef lint
+ code = 0; sig = code; code = sig;
+#endif
+ if (sig == SIGFPE) {
+ fatal("floating point exception");
+ } else if (sig == SIGSEGV) {
+ msg("fatal error: segmentation fault");
+ /* fatal won't abort() if not compiled for debugging */
+ abort();
+ } else
+ cant_happen();
+ /* NOTREACHED */
+}
diff --git a/missing.c b/missing.c
new file mode 100644
index 00000000..b9a25f6f
--- /dev/null
+++ b/missing.c
@@ -0,0 +1,52 @@
+
+#ifdef DUP2_MISSING
+#include "missing.d/dup2.c"
+#endif /* DUP2_MISSING */
+
+#ifdef GCVT_MISSING
+#include "missing.d/gcvt.c"
+#endif /* GCVT_MISSING */
+
+#ifdef GETOPT_MISSING
+#include "missing.d/getopt.c"
+#endif /* GETOPT_MISSING */
+
+#ifdef MEMCMP_MISSING
+#include "missing.d/memcmp.c"
+#endif /* MEMCMP_MISSING */
+
+#ifdef MEMCPY_MISSING
+#include "missing.d/memcpy.c"
+#endif /* MEMCPY_MISSING */
+
+#ifdef MEMSET_MISSING
+#include "missing.d/memset.c"
+#endif /* MEMSET_MISSING */
+
+#ifdef RANDOM_MISSING
+#include "missing.d/random.c"
+#endif /* RANDOM_MISSING */
+
+#ifdef STRCASE_MISSING
+#include "missing.d/strcase.c"
+#endif /* STRCASE_MISSING */
+
+#ifdef STRCHR_MISSING
+#include "missing.d/strchr.c"
+#endif /* STRCHR_MISSING */
+
+#ifdef STRERROR_MISSING
+#include "missing.d/strerror.c"
+#endif /* STRERROR_MISSING */
+
+#ifdef STRTOD_MISSING
+#include "missing.d/strtod.c"
+#endif /* STRTOD_MISSING */
+
+#ifdef TMPNAM_MISSING
+#include "missing.d/tmpnam.c"
+#endif /* TMPNAM_MISSING */
+
+#if defined(VPRINTF_MISSING) && defined(BSDSTDIO)
+#include "missing.d/vprintf.c"
+#endif /* VPRINTF_MISSING && BSDSTDIO */
diff --git a/missing.d/dup2.c b/missing.d/dup2.c
new file mode 100644
index 00000000..01068348
--- /dev/null
+++ b/missing.d/dup2.c
@@ -0,0 +1,12 @@
+#ifndef F_DUPFD
+#include <fcntl.h>
+#endif
+
+int
+dup2 (old, new)
+int old, new;
+{
+ (void) close(new);
+
+ return fcntl(old, F_DUPFD, new);
+}
diff --git a/missing.d/gcvt.c b/missing.d/gcvt.c
new file mode 100644
index 00000000..1ebe41e1
--- /dev/null
+++ b/missing.d/gcvt.c
@@ -0,0 +1,9 @@
+char *
+gcvt(value, digits, buff)
+double value;
+int digits;
+char *buff;
+{
+ sprintf(buff, "%*g", digits, value);
+ return (buff);
+}
diff --git a/att.getopt.c b/missing.d/getopt.c
index df68405f..d9e52945 100644
--- a/att.getopt.c
+++ b/missing.d/getopt.c
@@ -22,11 +22,8 @@
* However, I am not about to post a copy of anything licensed by AT&T.
*/
-/* This include is needed only to get "index" defined as "strchr" on Sys V. */
-#ifdef MSDOS
+#if defined(MSDOS) || defined(USG)
#define index strchr
-#else
-#include "defs.h"
#endif
/*LINTLIBRARY*/
diff --git a/missing.d/memcmp.c b/missing.d/memcmp.c
new file mode 100644
index 00000000..e39c10ec
--- /dev/null
+++ b/missing.d/memcmp.c
@@ -0,0 +1,18 @@
+/*
+ * memcmp --- compare strings.
+ *
+ * We use our own routine since it has to act like strcmp() for return
+ * value, and the BSD manual says bcmp() only returns zero/non-zero.
+ */
+
+int
+memcmp (s1, s2, l)
+register char *s1, *s2;
+register int l;
+{
+ for (; l--; s1++, s2++) {
+ if (*s1 != *s2)
+ return (*s1 - *s2);
+ }
+ return (*--s1 - *--s2);
+}
diff --git a/missing.d/memcpy.c b/missing.d/memcpy.c
new file mode 100644
index 00000000..3c4accdf
--- /dev/null
+++ b/missing.d/memcpy.c
@@ -0,0 +1,18 @@
+/*
+ * memcpy --- copy strings.
+ *
+ * We supply this routine for those systems that aren't standard yet.
+ */
+
+char *
+memcpy (dest, src, l)
+register char *dest, *src;
+register int l;
+{
+ register char *ret = dest;
+
+ while (l--)
+ *dest++ = *src++;
+
+ return ret;
+}
diff --git a/missing.d/memset.c b/missing.d/memset.c
new file mode 100644
index 00000000..120bdcb4
--- /dev/null
+++ b/missing.d/memset.c
@@ -0,0 +1,18 @@
+/*
+ * memset --- initialize memory
+ *
+ * We supply this routine for those systems that aren't standard yet.
+ */
+
+char *
+memset (dest, val, l)
+register char *dest, val;
+register int l;
+{
+ register char *ret = dest;
+
+ while (l--)
+ *dest++ = val;
+
+ return ret;
+}
diff --git a/random.c b/missing.d/random.c
index 5830024b..5830024b 100644
--- a/random.c
+++ b/missing.d/random.c
diff --git a/missing.d/strcase.c b/missing.d/strcase.c
new file mode 100644
index 00000000..d8fa674a
--- /dev/null
+++ b/missing.d/strcase.c
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 1987 Regents of the University of California.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms are permitted
+ * provided that the above copyright notice and this paragraph are
+ * duplicated in all such forms and that any documentation,
+ * advertising materials, and other materials related to such
+ * distribution and use acknowledge that the software was developed
+ * by the University of California, Berkeley. The name of the
+ * University may not be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+ * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char sccsid[] = "@(#)strcasecmp.c 5.6 (Berkeley) 6/27/88";
+#endif /* LIBC_SCCS and not lint */
+
+#ifndef USG
+#include <sys/types.h>
+#else
+#define u_char unsigned char
+#endif
+
+/*
+ * This array is designed for mapping upper and lower case letter
+ * together for a case independent comparison. The mappings are
+ * based upon ascii character sequences.
+ */
+static u_char charmap[] = {
+ '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
+ '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
+ '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
+ '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
+ '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
+ '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
+ '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
+ '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
+ '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
+ '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
+ '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
+ '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
+ '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
+ '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
+ '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
+ '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
+ '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
+ '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
+ '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
+ '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
+ '\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
+ '\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
+ '\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
+ '\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
+ '\300', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
+ '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
+ '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
+ '\370', '\371', '\372', '\333', '\334', '\335', '\336', '\337',
+ '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
+ '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
+ '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
+ '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377',
+};
+
+strcasecmp(s1, s2)
+ char *s1, *s2;
+{
+ register u_char *cm = charmap,
+ *us1 = (u_char *)s1,
+ *us2 = (u_char *)s2;
+
+ while (cm[*us1] == cm[*us2++])
+ if (*us1++ == '\0')
+ return(0);
+ return(cm[*us1] - cm[*--us2]);
+}
+
+strncasecmp(s1, s2, n)
+ char *s1, *s2;
+ register int n;
+{
+ register u_char *cm = charmap,
+ *us1 = (u_char *)s1,
+ *us2 = (u_char *)s2;
+
+ while (--n >= 0 && cm[*us1] == cm[*us2++])
+ if (*us1++ == '\0')
+ return(0);
+ return(n < 0 ? 0 : cm[*us1] - cm[*--us2]);
+}
diff --git a/missing.d/strchr.c b/missing.d/strchr.c
new file mode 100644
index 00000000..234ac883
--- /dev/null
+++ b/missing.d/strchr.c
@@ -0,0 +1,35 @@
+/*
+ * strchr --- search a string for a character
+ *
+ * We supply this routine for those systems that aren't standard yet.
+ */
+
+char *
+strchr (str, c)
+register char *str, c;
+{
+ for (; *str; str++)
+ if (*str == c)
+ return str;
+
+ return NULL;
+}
+
+/*
+ * strrchr --- find the last occurrence of a character in a string
+ *
+ * We supply this routine for those systems that aren't standard yet.
+ */
+
+char *
+strrchr (str, c)
+register char *str, c;
+{
+ register char *save = NULL;
+
+ for (; *str; str++)
+ if (*str == c)
+ save = str;
+
+ return save;
+}
diff --git a/do_free.c b/missing.d/strerror.c
index a9b85957..e9c20804 100644
--- a/do_free.c
+++ b/missing.d/strerror.c
@@ -1,5 +1,5 @@
/*
- * do_free.c -- debugging memory releaser for GNU Awk
+ * strerror.c --- ANSI C compatible system error routine
*/
/*
@@ -23,11 +23,23 @@
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
-extern void free();
+extern int sys_nerr;
+extern char *sys_errlist[];
-void
-do_free(s)
-char *s;
+/* have to get right decl of sprintf early on */
+#ifndef BUFSIZ /* stdio specific definition */
+#include <stdio.h>
+#endif
+
+char *
+strerror(n)
+int n;
{
- free(s);
+ static char mesg[30];
+
+ if (n < 0 || n > sys_nerr) {
+ sprintf (mesg, "Unknown error (%d)", n);
+ return mesg;
+ } else
+ return sys_errlist[n];
}
diff --git a/missing.d/strtod.c b/missing.d/strtod.c
new file mode 100644
index 00000000..79350a1e
--- /dev/null
+++ b/missing.d/strtod.c
@@ -0,0 +1,117 @@
+/*
+ * strtod.c
+ *
+ * Stupid version of System V strtod(3) library routine.
+ * Does no overflow/underflow checking.
+ *
+ * A real number is defined to be
+ * optional leading white space
+ * optional sign
+ * string of digits with optional decimal point
+ * optional 'e' or 'E'
+ * followed by optional sign or space
+ * followed by an integer
+ *
+ * if ptr is not NULL a pointer to the character terminating the
+ * scan is returned in *ptr. If no number formed, *ptr is set to str
+ * and 0 is returned.
+ *
+ * For speed, we don't do the conversion ourselves. Instead, we find
+ * the end of the number and then call atof() to do the dirty work.
+ * This bought us a 10% speedup on a sample program at uunet.uu.net.
+ */
+
+#include <ctype.h>
+
+extern double atof();
+
+double
+strtod (s, ptr)
+register char *s, **ptr;
+{
+ double ret = 0.0;
+ char *start = s;
+ char *begin = NULL;
+ int success = 0;
+
+ /* optional white space */
+ while (isspace(*s))
+ s++;
+
+ /* optional sign */
+ if (*s == '+' || *s == '-') {
+ s++;
+ if (*(s-1) == '-')
+ begin = s - 1;
+ else
+ begin = s;
+ }
+
+ /* string of digits with optional decimal point */
+ if (isdigit(*s) && ! begin)
+ begin = s;
+
+ while (isdigit(*s)) {
+ s++;
+ success++;
+ }
+
+ if (*s == '.') {
+ if (! begin)
+ begin = s;
+ s++;
+ while (isdigit(*s))
+ s++;
+ success++;
+ }
+
+ if (s == start || success == 0) /* nothing there */
+ goto out;
+
+ /*
+ * optional 'e' or 'E'
+ * followed by optional sign or space
+ * followed by an integer
+ */
+
+ if (*s == 'e' || *s == 'E') {
+ s++;
+
+ /* XXX - atof probably doesn't allow spaces here */
+ while (isspace(*s))
+ s++;
+
+ if (*s == '+' || *s == '-')
+ s++;
+
+ while (isdigit(*s))
+ s++;
+ }
+
+ /* go for it */
+ ret = atof(begin);
+
+out:
+ if (! success)
+ s = start; /* in case all we did was skip whitespace */
+
+ if (ptr)
+ *ptr = s;
+
+ return ret;
+}
+
+#ifdef TEST
+main (argc, argv)
+int argc;
+char **argv;
+{
+ double d;
+ char *p;
+
+ for (argc--, argv++; argc; argc--, argv++) {
+ d = strtod (*argv, & p);
+ printf ("%lf [%s]\n", d, p);
+ }
+}
+#endif
diff --git a/missing.d/tmpnam.c b/missing.d/tmpnam.c
new file mode 100644
index 00000000..8f49859a
--- /dev/null
+++ b/missing.d/tmpnam.c
@@ -0,0 +1,27 @@
+/*
+ * tmpnam - an implementation for systems lacking a library version
+ * this version does not rely on the P_tmpdir and L_tmpnam constants.
+ */
+
+#ifndef NULL
+#define NULL 0
+#endif
+
+static char template[] = "/tmp/gawkXXXXXX";
+
+char *
+tmpnam(tmp)
+char *tmp;
+{
+ static char tmpbuf[sizeof(template)];
+
+ if (tmp == NULL) {
+ (void) strcpy(tmpbuf, template);
+ (void) mktemp(tmpbuf);
+ return tmpbuf;
+ } else {
+ (void) strcpy(tmp, template);
+ (void) mktemp(tmp);
+ return tmp;
+ }
+}
diff --git a/missing.d/vprintf.c b/missing.d/vprintf.c
new file mode 100644
index 00000000..dea4ca86
--- /dev/null
+++ b/missing.d/vprintf.c
@@ -0,0 +1,54 @@
+#include <stdio.h>
+#include <varargs.h>
+
+#ifndef BUFSIZ
+#include <stdio.h>
+#endif
+
+#ifndef va_dcl
+#include <varargs.h>
+#endif
+
+int
+vsprintf(str, fmt, ap)
+ char *str, *fmt;
+ va_list ap;
+{
+ FILE f;
+ int len;
+
+ f._flag = _IOWRT+_IOSTRG;
+ f._ptr = (char *)str; /* My copy of BSD stdio.h has this as (char *)
+ * with a comment that it should be
+ * (unsigned char *). Since this code is
+ * intended for use on a vanilla BSD system,
+ * we'll stick with (char *) for now.
+ */
+ f._cnt = 32767;
+ len = _doprnt(fmt, ap, &f);
+ *f._ptr = 0;
+ return (len);
+}
+
+int
+vfprintf(iop, fmt, ap)
+ FILE *iop;
+ char *fmt;
+ va_list ap;
+{
+ int len;
+
+ len = _doprnt(fmt, ap, iop);
+ return (ferror(iop) ? EOF : len);
+}
+
+int
+vprintf(fmt, ap)
+ char *fmt;
+ va_list ap;
+{
+ int len;
+
+ len = _doprnt(fmt, ap, stdout);
+ return (ferror(stdout) ? EOF : len);
+}
diff --git a/awk5.c b/msg.c
index 0fc3ebf4..6f1090fd 100644
--- a/awk5.c
+++ b/msg.c
@@ -1,40 +1,5 @@
/*
- * routines for error messages
- *
- * $Log: awk5.c,v $
- * Revision 1.15 89/03/31 13:26:11 david
- * GNU license
- *
- * Revision 1.14 89/03/30 10:22:23 david
- * fixed up varargs usage
- *
- * Revision 1.13 89/03/29 14:14:37 david
- * delinting
- *
- * Revision 1.12 89/03/21 18:31:46 david
- * changed defines for system without vprintf()
- *
- * Revision 1.11 89/03/21 10:52:53 david
- * cleanup
- *
- * Revision 1.10 88/12/08 11:00:07 david
- * add $Log: awk5.c,v $
- * Revision 1.15 89/03/31 13:26:11 david
- * GNU license
- *
- * Revision 1.14 89/03/30 10:22:23 david
- * fixed up varargs usage
- *
- * Revision 1.13 89/03/29 14:14:37 david
- * delinting
- *
- * Revision 1.12 89/03/21 18:31:46 david
- * changed defines for system without vprintf()
- *
- * Revision 1.11 89/03/21 10:52:53 david
- * cleanup
- *
- *
+ * msg.c - routines for error messages
*/
/*
@@ -77,17 +42,19 @@ va_list *argp;
vfprintf(stderr, msg, *argp);
(void) fprintf(stderr, "\n");
line = (int) FNR_node->var_value->numbr;
- if (line)
+ if (line) {
(void) fprintf(stderr, " input line number %d", line);
- file = FILENAME_node->var_value->stptr;
- if (file && !STREQ(file, "-"))
- (void) fprintf(stderr, ", file `%s'", file);
- (void) fprintf(stderr, "\n");
- if (sourceline)
+ file = FILENAME_node->var_value->stptr;
+ if (file && !STREQ(file, "-"))
+ (void) fprintf(stderr, ", file `%s'", file);
+ (void) fprintf(stderr, "\n");
+ }
+ if (sourceline) {
(void) fprintf(stderr, " source line number %d", sourceline);
- if (source)
- (void) fprintf(stderr, ", file `%s'", source);
- (void) fprintf(stderr, "\n");
+ if (source)
+ (void) fprintf(stderr, ", file `%s'", source);
+ (void) fprintf(stderr, "\n");
+ }
}
/*VARARGS0*/
@@ -135,44 +102,3 @@ va_dcl
#endif
exit(1);
}
-
-#if defined(HASDOPRNT) && defined(NOVPRINTF)
-int
-vsprintf(str, fmt, ap)
- char *str, *fmt;
- va_list ap;
-{
- FILE f;
- int len;
-
- f._flag = _IOWRT+_IOSTRG;
- f._ptr = (unsigned char *)str;
- f._cnt = 32767;
- len = _doprnt(fmt, ap, &f);
- *f._ptr = 0;
- return (len);
-}
-
-int
-vfprintf(iop, fmt, ap)
- FILE *iop;
- char *fmt;
- va_list ap;
-{
- int len;
-
- len = _doprnt(fmt, ap, iop);
- return (ferror(iop) ? EOF : len);
-}
-
-int
-vprintf(fmt, ap)
- char *fmt;
- va_list ap;
-{
- int len;
-
- len = _doprnt(fmt, ap, stdout);
- return (ferror(stdout) ? EOF : len);
-}
-#endif
diff --git a/awk9.c b/node.c
index 39cec854..3d006fe6 100644
--- a/awk9.c
+++ b/node.c
@@ -1,5 +1,5 @@
/*
- * awk9.c -- routines for node management
+ * node.c -- routines for node management
*/
/*
@@ -25,10 +25,20 @@
#include "awk.h"
+extern double strtod();
+
+/*
+ * We can't dereference a variable until after we've given it its new value.
+ * This variable points to the value we have to free up
+ */
+NODE *deref;
+
AWKNUM
r_force_number(n)
NODE *n;
{
+ char *ptr;
+
#ifdef DEBUG
if (n == NULL)
cant_happen();
@@ -39,15 +49,28 @@ NODE *n;
if (n->flags & NUM)
return n->numbr;
#endif
- n->numbr = (AWKNUM) atof(n->stptr);
+ if (n->stlen == 0)
+ n->numbr = 0.0;
+ else if (n->stlen == 1) {
+ if (isdigit(n->stptr[0])) {
+ n->numbr = n->stptr[0] - '0';
+ n->flags |= NUMERIC;
+ } else
+ n->numbr = 0.0;
+ } else {
+ errno = 0;
+ n->numbr = (AWKNUM) strtod(n->stptr, &ptr);
+ if (errno == 0 && ptr == n->stptr + n->stlen)
+ n->flags |= NUMERIC;
+ }
n->flags |= NUM;
return n->numbr;
}
/*
* the following lookup table is used as an optimization in force_string
- * variations on this theme didn't seem to pay off, but systematic
- * testing might be in order at some point
+ * (more complicated) variations on this theme didn't seem to pay off, but
+ * systematic testing might be in order at some point
*/
static char *values[] = {
"0",
@@ -69,7 +92,7 @@ NODE *s;
{
char buf[128];
char *fmt;
- int num;
+ long num;
char *sp = buf;
#ifdef DEBUG
@@ -87,14 +110,13 @@ NODE *s;
s->flags |= STR;
/* should check validity of user supplied OFMT */
fmt = OFMT_node->var_value->stptr;
- if (STREQ(fmt, "%.6g") && (long) s->numbr == s->numbr) {
- /* integral value */
- if ((num = s->numbr) < NVAL) {
+ if ((num = s->numbr) == s->numbr) {
+ /* integral value */
+ if (num < NVAL && num >= 0) {
sp = values[num];
s->stlen = 1;
} else {
- fmt = "%.11g";
- (void) sprintf(sp, fmt, s->numbr);
+ (void) sprintf(sp, "%ld", num);
s->stlen = strlen(sp);
}
} else {
@@ -103,37 +125,13 @@ NODE *s;
}
s->stref = 1;
emalloc(s->stptr, char *, s->stlen + 1, "force_string");
- bcopy(sp, s->stptr, s->stlen+1);
+ memcpy(s->stptr, sp, s->stlen+1);
return s;
}
/*
- * This allocates a new node of type ty. Note that this node will not go
- * away unless freed.
- */
-#ifdef notdef
-NODE *
-newnode(ty)
-NODETYPE ty;
-{
- register NODE *r;
-
- emalloc(r, NODE *, sizeof(NODE), "newnode");
- r->type = ty;
- r->flags = MALLOC;
- return r;
-}
-
-freenode(n)
-NODE *n;
-{
- free((char *)n);
-}
-#endif
-
-/*
- * Duplicate a node. (For global strings, "duplicate" means crank up the
- * reference count.) This creates global nodes. . .
+ * Duplicate a node. (For strings, "duplicate" means crank up the
+ * reference count.)
*/
NODE *
dupnode(n)
@@ -158,14 +156,12 @@ NODE *n;
if (n->type == Node_val && (n->flags & STR)) {
r->stref = 1;
emalloc(r->stptr, char *, r->stlen + 1, "dupnode");
- bcopy(n->stptr, r->stptr, r->stlen);
- r->stptr[r->stlen] = '\0';
+ memcpy(r->stptr, n->stptr, r->stlen+1);
}
return r;
}
/* this allocates a node with defined numbr */
-/* This creates global nodes! */
NODE *
make_number(x)
AWKNUM x;
@@ -174,13 +170,13 @@ AWKNUM x;
r = newnode(Node_val);
r->numbr = x;
- r->flags |= NUM;
+ r->flags |= (NUM|NUMERIC);
r->stref = 0;
return r;
}
/*
- * This creates temporary nodes. They go away quite quicly, so don't use
+ * This creates temporary nodes. They go away quite quickly, so don't use
* them for anything important
*/
NODE *
@@ -195,131 +191,50 @@ AWKNUM x;
}
/*
- * Make a string node. If len==-1, the string passed in S is supposed to end
- * with a double quote, but have had the beginning double quote already
- * stripped off by yylex. If LEN!=-1, we don't care what s ends with. This
- * creates a global node
+ * Make a string node.
*/
NODE *
-make_string(s, len)
+make_str_node(s, len, scan)
char *s;
+int len;
+int scan;
{
register NODE *r;
- register char *pf, *pt;
+ char *pf;
+ register char *pt;
register int c;
- int count;
+ register char *end;
- /*
- * the aborts are impossible because yylex is supposed to have
- * already checked for unterminated strings
- */
- if (len == -1) { /* Called from yyparse, find our own len */
- for (pf = pt = s; *pf != '\0' && *pf != '\"';) {
+ r = newnode(Node_val);
+ emalloc(r->stptr, char *, len + 1, s);
+ memcpy(r->stptr, s, len);
+ r->stptr[len] = '\0';
+ end = &(r->stptr[len]);
+
+ if (scan) { /* scan for escape sequences */
+ for (pf = pt = r->stptr; pf < end;) {
c = *pf++;
- switch (c) {
- case '\0':
- cant_happen();
-
- case '\\':
- if (*pf == '\0')
+ if (c == '\\') {
+ c = parse_escape(&pf);
+ if (c < 0)
cant_happen();
- c = *pf++;
- switch (c) {
- case '\\': /* no massagary needed */
- case '\'':
- case '\"':
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
-#ifdef notdef
- case '8':
- case '9':
-#endif
- c -= '0';
- count = 1;
- while (*pf && *pf >= '0' && *pf <= '7') {
- c = c * 8 + *pf++ - '0';
- if (++count >= 3)
- break;
- }
- break;
- case 'a':
- if (strict)
- goto def;
- else
- c = BELL;
- break;
- case 'b':
- c = '\b';
- break;
- case 'f':
- c = '\f';
- break;
- case 'n':
- c = '\n';
- break;
- case 'r':
- c = '\r';
- break;
- case 't':
- c = '\t';
- break;
- case 'v':
- if (strict)
- goto def;
- else
- c = '\v';
- break;
- case 'x':
- if (strict)
- goto def;
- else {
- c = 0;
- while (*pf && isxdigit(*pf)) {
- if (isdigit(*pf))
- c += *pf - '0';
- else if (isupper(*pf))
- c += *pf - 'A' + 10;
- else
- c += *pf - 'a' + 10;
- pf++;
- }
- }
- break;
- default:
- def:
- *pt++ = '\\';
- break;
- }
- /* FALL THROUGH */
- default:
*pt++ = c;
- break;
- }
+ } else
+ *pt++ = c;
}
- if (*pf == '\0')
- cant_happen(); /* hit the end of the buf */
- len = pt - s;
+ len = pt - r->stptr;
+ erealloc(r->stptr, char *, len + 1, "make_str_node");
+ r->stptr[len] = '\0';
+ r->flags |= PERM;
}
- r = newnode(Node_val);
- emalloc(r->stptr, char *, len + 1, s);
r->stlen = len;
r->stref = 1;
- bcopy(s, r->stptr, len);
- r->stptr[len] = '\0'; /* a hack */
- r->flags = (STR|MALLOC);
+ r->flags |= (STR|MALLOC);
return r;
}
-/* This should be a macro for speed, but the C compiler chokes. */
/* Read the warning under tmp_number */
NODE *
tmp_string(s, len)
@@ -332,3 +247,96 @@ int len;
r->flags |= TEMP;
return r;
}
+
+
+#define NODECHUNK 100
+
+static NODE *nextfree = NULL;
+
+NODE *
+newnode(ty)
+NODETYPE ty;
+{
+ NODE *it;
+ NODE *np;
+
+#ifdef MPROF
+ emalloc(it, NODE *, sizeof(NODE), "newnode");
+#else
+ if (nextfree == NULL) {
+ /* get more nodes and initialize list */
+ emalloc(nextfree, NODE *, NODECHUNK * sizeof(NODE), "newnode");
+ for (np = nextfree; np < &nextfree[NODECHUNK - 1]; np++)
+ np->nextp = np + 1;
+ np->nextp = NULL;
+ }
+ /* get head of freelist */
+ it = nextfree;
+ nextfree = nextfree->nextp;
+#endif
+ it->type = ty;
+ it->flags = MALLOC;
+#ifdef MEMDEBUG
+ fprintf(stderr, "node: new: %0x\n", it);
+#endif
+ return it;
+}
+
+void
+freenode(it)
+NODE *it;
+{
+#ifdef DEBUG
+ NODE *nf;
+#endif
+#ifdef MEMDEBUG
+ fprintf(stderr, "node: free: %0x\n", it);
+#endif
+#ifdef MPROF
+ free((char *) it);
+#else
+#ifdef DEBUG
+ for (nf = nextfree; nf; nf = nf->nextp)
+ if (nf == it)
+ fatal("attempt to free free node");
+#endif
+ /* add it to head of freelist */
+ it->nextp = nextfree;
+ nextfree = it;
+#endif
+}
+
+#ifdef DEBUG
+pf()
+{
+ NODE *nf = nextfree;
+ while (nf != NULL) {
+ fprintf(stderr, "%0x ", nf);
+ nf = nf->nextp;
+ }
+}
+#endif
+
+void
+do_deref()
+{
+ if (deref == NULL)
+ return;
+ if (deref->flags & PERM) {
+ deref = 0;
+ return;
+ }
+ if ((deref->flags & MALLOC) || (deref->flags & TEMP)) {
+ deref->flags &= ~TEMP;
+ if (deref->flags & STR) {
+ if (deref->stref > 1 && deref->stref != 255) {
+ deref->stref--;
+ deref = 0;
+ return;
+ }
+ free(deref->stptr);
+ }
+ freenode(deref);
+ }
+ deref = 0;
+}
diff --git a/patchlevel.h b/patchlevel.h
new file mode 100644
index 00000000..2867bba9
--- /dev/null
+++ b/patchlevel.h
@@ -0,0 +1 @@
+#define PATCHLEVEL 0
diff --git a/makefile.pc b/pc.d/makefile.pc
index b812dad4..b812dad4 100644
--- a/makefile.pc
+++ b/pc.d/makefile.pc
diff --git a/names.lnk b/pc.d/names.lnk
index 28e1a0d5..28e1a0d5 100644
--- a/names.lnk
+++ b/pc.d/names.lnk
diff --git a/pc.d/popen.c b/pc.d/popen.c
new file mode 100644
index 00000000..48952c22
--- /dev/null
+++ b/pc.d/popen.c
@@ -0,0 +1,90 @@
+#include <stdio.h>
+#include "popen.h"
+#include <io.h>
+#include <string.h>
+#include <process.h>
+
+static char template[] = "piXXXXXX";
+typedef enum { unopened = 0, reading, writing } pipemode;
+static
+struct {
+ char *command;
+ char *name;
+ pipemode pmode;
+} pipes[_NFILE];
+
+FILE *
+popen( char *command, char *mode ) {
+ FILE *current;
+ char *name;
+ int cur;
+ pipemode curmode;
+ /*
+ ** decide on mode.
+ */
+ if(strcmp(mode,"r") == 0)
+ curmode = reading;
+ else if(strcmp(mode,"w") == 0)
+ curmode = writing;
+ else
+ return NULL;
+ /*
+ ** get a name to use.
+ */
+ if((name = tempnam(".","pip"))==NULL)
+ return NULL;
+ /*
+ ** If we're reading, just call system to get a file filled with
+ ** output.
+ */
+ if(curmode == reading) {
+ char cmd[256];
+ sprintf(cmd,"%s > %s",command,name);
+ system(cmd);
+ if((current = fopen(name,"r")) == NULL)
+ return NULL;
+ } else {
+ if((current = fopen(name,"w")) == NULL)
+ return NULL;
+ }
+ cur = fileno(current);
+ pipes[cur].name = name;
+ pipes[cur].pmode = curmode;
+ pipes[cur].command = strdup(command);
+ return current;
+}
+
+int
+pclose( FILE * current) {
+ int cur = fileno(current),rval;
+ /*
+ ** check for an open file.
+ */
+ if(pipes[cur].pmode == unopened)
+ return -1;
+ if(pipes[cur].pmode == reading) {
+ /*
+ ** input pipes are just files we're done with.
+ */
+ rval = fclose(current);
+ unlink(pipes[cur].name);
+ } else {
+ /*
+ ** output pipes are temporary files we have
+ ** to cram down the throats of programs.
+ */
+ char command[256];
+ fclose(current);
+ sprintf(command,"%s < %s",pipes[cur].command,pipes[cur].name);
+ rval = system(command);
+ unlink(pipes[cur].name);
+ }
+ /*
+ ** clean up current pipe.
+ */
+ pipes[cur].pmode = unopened;
+ free(pipes[cur].name);
+ free(pipes[cur].command);
+ return rval;
+}
+
diff --git a/pc.d/popen.h b/pc.d/popen.h
new file mode 100644
index 00000000..55501324
--- /dev/null
+++ b/pc.d/popen.h
@@ -0,0 +1,8 @@
+/*
+** popen.h -- prototypes for pipe functions
+*/
+#if !defined(FILE)
+#include <stdio.h>
+#endif
+extern FILE *popen( char *, char * );
+
diff --git a/regex.c b/regex.c
index bb2d6124..a04a4398 100644
--- a/regex.c
+++ b/regex.c
@@ -136,13 +136,14 @@ extern int re_exec(char *s);
#else /* not emacs */
-#if defined(USG) || defined(MSDOS)
-#define bcopy(s,d,n) memcpy(d,s,n)
-#define bcmp(s1,s2,n) memcmp(s1,s2,n)
-#define bzero(s,n) memset(s,0,n)
-#ifdef MSDOS
-#include <malloc.h>
-#endif
+#ifdef BCOPY_MISSING
+#define bcopy(s,d,n) memcpy((d),(s),(n))
+#define bcmp(s1,s2,n) memcmp((s1),(s2),(n))
+#define bzero(s,n) memset((s),0,(n))
+#else
+void bcopy();
+int bcmp();
+void bzero();
#endif
/* Make alloca work the best possible way. */
@@ -269,11 +270,6 @@ re_set_syntax (syntax)
#else
#define MaxAllocation (1<<16)
#endif
-/* The pointer math version is inappropriate for large model, as realloc
- could move stuff off into a different segment somewhere, in which case
- the pointer offsets would be wrong. At least that's how I think I
- understand it - ADR. */
-#ifndef M_I86LM
#define EXTEND_BUFFER \
{ char *old_buffer = bufp->buffer; \
if (bufp->allocated == MaxAllocation) goto too_big; \
@@ -291,7 +287,8 @@ re_set_syntax (syntax)
if (pending_exact) \
pending_exact += c; \
}
-#else
+
+#ifdef NEVER
#define EXTEND_BUFFER \
{ unsigned b_off = b - bufp->buffer, \
f_off, l_off, p_off, \
@@ -557,9 +554,8 @@ re_compile_pattern (pattern, size, bufp)
{
PATFETCH (c);
- /* If awk, \ escapes a ] when inside [...]. */
- if ((obscure_syntax & RE_AWK_CLASS_HACK)
- && c == '\\' && *p == ']')
+ /* If awk, \ escapes characters inside [...]. */
+ if ((obscure_syntax & RE_AWK_CLASS_HACK) && c == '\\')
{
PATFETCH(c1);
b[c1 / BYTEWIDTH] |= 1 << (c1 % BYTEWIDTH);
diff --git a/regex.h b/regex.h
index 27f963f9..7ad5da24 100644
--- a/regex.h
+++ b/regex.h
@@ -143,15 +143,16 @@ what you give them. Help stamp out software-hoarding! */
*, +, ? - only special when not after the beginning, (, or | */
#define RE_CONTEXT_INDEP_OPS 32
-/* 0 means that \ before a ] inside [ and ] is taken as a real \.
- 1 means that such a \ escapes the following ]. This is a
- special case for AWK. Other \ inside [ ] seem to work ok. */
+/* 0 means that \ before anything inside [ and ] is taken as a real \.
+ 1 means that such a \ escapes the following character This is a
+ special case for AWK. */
#define RE_AWK_CLASS_HACK 64
/* Now define combinations of bits for the standard possibilities. */
-#define RE_SYNTAX_AWK (RE_NO_BK_PARENS | RE_NO_BK_VBAR \
- | RE_CONTEXT_INDEP_OPS | RE_AWK_CLASS_HACK)
-#define RE_SYNTAX_EGREP (RE_SYNTAX_AWK | RE_NEWLINE_OR)
+#define RE_SYNTAX_POSIX_EGREP (RE_NO_BK_PARENS | RE_NO_BK_VBAR \
+ | RE_CONTEXT_INDEP_OPS)
+#define RE_SYNTAX_AWK (RE_SYNTAX_POSIX_EGREP | RE_AWK_CLASS_HACK)
+#define RE_SYNTAX_EGREP (RE_SYNTAX_POSIX_EGREP | RE_NEWLINE_OR)
#define RE_SYNTAX_GREP (RE_BK_PLUS_QM | RE_NEWLINE_OR)
#define RE_SYNTAX_EMACS 0
diff --git a/support/texindex.c b/support/texindex.c
new file mode 100644
index 00000000..33b5fdbc
--- /dev/null
+++ b/support/texindex.c
@@ -0,0 +1,1673 @@
+/* Prepare Tex index dribble output into an actual index.
+ Copyright (C) 1987 Free Software Foundation, Inc.
+
+ NO WARRANTY
+
+ BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
+NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW. EXCEPT
+WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
+RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
+WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY
+AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
+DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
+CORRECTION.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
+STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
+WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
+LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
+OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
+DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
+A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
+PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
+
+ GENERAL PUBLIC LICENSE TO COPY
+
+ 1. You may copy and distribute verbatim copies of this source file
+as you receive it, in any medium, provided that you conspicuously
+and appropriately publish on each copy a valid copyright notice
+"Copyright (C) 1987 Free Software Foundation, Inc.", and include
+following the copyright notice a verbatim copy of the above disclaimer
+of warranty and of this License.
+
+ 2. You may modify your copy or copies of this source file or
+any portion of it, and copy and distribute such modifications under
+the terms of Paragraph 1 above, provided that you also do the following:
+
+ a) cause the modified files to carry prominent notices stating
+ that you changed the files and the date of any change; and
+
+ b) cause the whole of any work that you distribute or publish,
+ that in whole or in part contains or is a derivative of this
+ program or any part thereof, to be licensed at no charge to all
+ third parties on terms identical to those contained in this
+ License Agreement (except that you may choose to grant more extensive
+ warranty protection to some or all third parties, at your option).
+
+ c) You may charge a distribution fee for the physical act of
+ transferring a copy, and you may at your option offer warranty
+ protection in exchange for a fee.
+
+Mere aggregation of another unrelated program with this program (or its
+derivative) on a volume of a storage or distribution medium does not bring
+the other program under the scope of these terms.
+
+ 3. You may copy and distribute this program (or a portion or derivative
+of it, under Paragraph 2) in object code or executable form under the terms
+of Paragraphs 1 and 2 above provided that you also do one of the following:
+
+ a) accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of
+ Paragraphs 1 and 2 above; or,
+
+ b) accompany it with a written offer, valid for at least three
+ years, to give any third party free (except for a nominal
+ shipping charge) a complete machine-readable copy of the
+ corresponding source code, to be distributed under the terms of
+ Paragraphs 1 and 2 above; or,
+
+ c) accompany it with the information you received as to where the
+ corresponding source code may be obtained. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form alone.)
+
+For an executable file, complete source code means all the source code for
+all modules it contains; but, as a special exception, it need not include
+source code for modules which are standard libraries that accompany the
+operating system on which the executable file runs.
+
+ 4. You may not copy, sublicense, distribute or transfer this program
+except as expressly provided under this License Agreement. Any attempt
+otherwise to copy, sublicense, distribute or transfer this program is void and
+your rights to use the program under this License agreement shall be
+automatically terminated. However, parties who have received computer
+software programs from you with this License Agreement will not have
+their licenses terminated so long as such parties remain in full compliance.
+
+ 5. If you wish to incorporate parts of this program into other free
+programs whose distribution conditions are different, write to the Free
+Software Foundation at 675 Mass Ave, Cambridge, MA 02139. We have not yet
+worked out a simple rule that can be stated here, but we will often permit
+this. We will be guided by the two goals of preserving the free status of
+all derivatives of our free software and of promoting the sharing and reuse of
+software.
+
+ In other words, you are welcome to use, share and improve this program.
+ You are forbidden to forbid anyone else to use, share and improve
+ what you give them. Help stamp out software-hoarding! */
+
+
+#include <stdio.h>
+#include <ctype.h>
+
+#ifdef VMS
+#include <file.h>
+
+#define EXIT_SUCCESS ((1 << 28) | 1)
+#define EXIT_FATAL ((1 << 28) | 4)
+#define unlink delete
+#define tell(fd) lseek(fd, 0L, 1)
+#else
+#include <sys/file.h>
+
+#define EXIT_SUCCESS 0
+#define EXIT_FATAL 1
+#endif
+
+
+#ifndef L_XTND
+#define L_XTND 2
+#endif
+
+/* When sorting in core, this structure describes one line
+ and the position and length of its first keyfield. */
+
+struct lineinfo
+ {
+ char *text; /* The actual text of the line */
+ union
+ { /* The start of the key (for textual comparison) */
+ char *text;
+ long number; /* or the numeric value (for numeric comparison) */
+ } key;
+ long keylen; /* Length of key field */
+ };
+
+/* This structure describes a field to use as a sort key */
+
+struct keyfield
+ {
+ int startwords; /* # words to skip */
+ int startchars; /* and # additional chars to skip, to start of field */
+ int endwords; /* similar, from beg (or end) of line, to find end of field */
+ int endchars;
+ char ignore_blanks; /* Ignore spaces and tabs within the field */
+ char fold_case; /* Convert upper case to lower before comparing */
+ char reverse; /* Compare in reverse order */
+ char numeric; /* Parse text as an integer and compare the integers */
+ char positional; /* Sort according to position within the file */
+ char braced; /* Count balanced-braced groupings as fields */
+ };
+
+/* Vector of keyfields to use */
+
+struct keyfield keyfields[3];
+
+/* Number of keyfields stored in that vector. */
+
+int num_keyfields = 3;
+
+/* Vector of input file names, terminated with a zero (null pointer) */
+
+char **infiles;
+
+/* Vector of corresponding output file names, or zero meaning default it */
+
+char **outfiles;
+
+/* Length of `infiles' */
+
+int num_infiles;
+
+/* Pointer to the array of pointers to lines being sorted */
+
+char **linearray;
+
+/* The allocated length of `linearray'. */
+
+long lines;
+
+/* Directory to use for temporary files. On Unix, it ends with a slash. */
+
+char *tempdir;
+
+/* Start of filename to use for temporary files. */
+
+char *tempbase;
+
+/* Number of last temporary file. */
+
+int tempcount;
+
+/* Number of last temporary file already deleted.
+ Temporary files are deleted by `flush_tempfiles' in order of creation. */
+
+int last_deleted_tempcount;
+
+/* During in-core sort, this points to the base of the data block
+ which contains all the lines of data. */
+
+char *text_base;
+
+/* Additional command switches */
+
+int keep_tempfiles; /* Nonzero means do not delete tempfiles -- for debugging */
+
+/* Forward declarations of functions in this file */
+
+void decode_command ();
+void sort_in_core ();
+void sort_offline ();
+char **parsefile ();
+char *find_field ();
+char *find_pos ();
+long find_value ();
+char *find_braced_pos ();
+char *find_braced_end ();
+void writelines ();
+int compare_full ();
+long readline ();
+int merge_files ();
+int merge_direct ();
+char *concat ();
+char *maketempname ();
+void flush_tempfiles ();
+char *tempcopy ();
+
+extern char *mktemp ();
+
+#define MAX_IN_CORE_SORT 500000
+
+int
+main (argc, argv)
+ int argc;
+ char **argv;
+{
+ int i;
+
+ tempcount = 0;
+ last_deleted_tempcount = 0;
+
+ /* Describe the kind of sorting to do. */
+ /* The first keyfield uses the first braced field and folds case */
+ keyfields[0].braced = 1;
+ keyfields[0].fold_case = 1;
+ keyfields[0].endwords = -1;
+ keyfields[0].endchars = -1;
+ /* The second keyfield uses the second braced field, numerically */
+ keyfields[1].braced = 1;
+ keyfields[1].numeric = 1;
+ keyfields[1].startwords = 1;
+ keyfields[1].endwords = -1;
+ keyfields[1].endchars = -1;
+ /* The third keyfield (which is ignored while discarding duplicates)
+ compares the whole line */
+ keyfields[2].endwords = -1;
+ keyfields[2].endchars = -1;
+
+ decode_command (argc, argv);
+
+ tempbase = mktemp (concat ("txiXXXXXX", "", ""));
+
+ /* Process input files completely, one by one. */
+
+ for (i = 0; i < num_infiles; i++)
+ {
+ int desc;
+ long ptr;
+ char *outfile;
+ char *p;
+
+ desc = open (infiles[i], 0, 0);
+ if (desc < 0) pfatal_with_name (infiles[i]);
+ lseek (desc, 0, L_XTND);
+ ptr = tell (desc);
+ close (desc);
+
+ outfile = outfiles[i];
+ if (!outfile)
+ {
+ outfile = concat (infiles[i], "s", "");
+ }
+
+ if (ptr < MAX_IN_CORE_SORT)
+ /* Sort a small amount of data */
+ sort_in_core (infiles[i], ptr, outfile);
+ else
+ sort_offline (infiles[i], ptr, outfile);
+ }
+
+ flush_tempfiles (tempcount);
+ exit (EXIT_SUCCESS);
+}
+
+/* This page decodes the command line arguments to set the parameter variables
+ and set up the vector of keyfields and the vector of input files */
+
+void
+decode_command (argc, argv)
+ int argc;
+ char **argv;
+{
+ int i;
+ char **ip;
+ char **op;
+
+ /* Store default values into parameter variables */
+
+#ifdef VMS
+ tempdir = "sys$scratch:";
+#else
+ tempdir = "/tmp/";
+#endif
+
+ keep_tempfiles = 0;
+
+ /* Allocate argc input files, which must be enough. */
+
+ infiles = (char **) xmalloc (argc * sizeof (char *));
+ outfiles = (char **) xmalloc (argc * sizeof (char *));
+ ip = infiles;
+ op = outfiles;
+
+ /* First find all switches that control the default kind-of-sort */
+
+ for (i = 1; i < argc; i++)
+ {
+ int tem = classify_arg (argv[i]);
+ char c;
+ char *p;
+
+ if (tem <= 0)
+ {
+ *ip++ = argv[i];
+ *op++ = 0;
+ continue;
+ }
+ if (tem > 1)
+ {
+ if (i + 1 == argc)
+ fatal ("switch %s given with no argument following it", argv[i]);
+ else if (!strcmp (argv[i], "-T"))
+ tempdir = argv[i + 1];
+ else if (!strcmp (argv[i], "-o"))
+ *(op - 1) = argv[i + 1];
+ i += tem - 1;
+ continue;
+ }
+
+ p = &argv[i][1];
+ while (c = *p++)
+ switch (c)
+ {
+ case 'k':
+ keep_tempfiles = 1;
+ break;
+
+ default:
+ fatal ("invalid command switch %c", c);
+ }
+ switchdone: ;
+ }
+
+ /* Record number of keyfields, terminate list of filenames */
+
+ num_infiles = ip - infiles;
+ *ip = 0;
+}
+
+/* Return 0 for an argument that is not a switch;
+ for a switch, return 1 plus the number of following arguments that the switch swallows.
+*/
+
+int
+classify_arg (arg)
+ char *arg;
+{
+ if (!strcmp (arg, "-T") || !strcmp (arg, "-o"))
+ return 2;
+ if (arg[0] == '-')
+ return 1;
+ return 0;
+}
+
+/* Create a name for a temporary file */
+
+char *
+maketempname (count)
+ int count;
+{
+ char tempsuffix[10];
+ sprintf (tempsuffix, "%d", count);
+ return concat (tempdir, tempbase, tempsuffix);
+}
+
+/* Delete all temporary files up to the specified count */
+
+void
+flush_tempfiles (to_count)
+ int to_count;
+{
+ if (keep_tempfiles) return;
+ while (last_deleted_tempcount < to_count)
+ unlink (maketempname (++last_deleted_tempcount));
+}
+
+/* Copy an input file into a temporary file, and return the temporary file name */
+
+#define BUFSIZE 1024
+
+char *
+tempcopy (idesc)
+ int idesc;
+{
+ char *outfile = maketempname (++tempcount);
+ int odesc;
+ char buffer[BUFSIZE];
+
+ odesc = open (outfile, O_WRONLY | O_CREAT, 0666);
+
+ if (odesc < 0) pfatal_with_name (outfile);
+
+ while (1)
+ {
+ int nread = read (idesc, buffer, BUFSIZE);
+ write (odesc, buffer, nread);
+ if (!nread) break;
+ }
+
+ close (odesc);
+
+ return outfile;
+}
+
+/* Compare two lines, provided as pointers to pointers to text,
+ according to the specified set of keyfields */
+
+int
+compare_full (line1, line2)
+ char **line1, **line2;
+{
+ int i;
+
+ /* Compare using the first keyfield;
+ if that does not distinguish the lines, try the second keyfield; and so on. */
+
+ for (i = 0; i < num_keyfields; i++)
+ {
+ long length1, length2;
+ char *start1 = find_field (&keyfields[i], *line1, &length1);
+ char *start2 = find_field (&keyfields[i], *line2, &length2);
+ int tem = compare_field (&keyfields[i], start1, length1, *line1 - text_base,
+ start2, length2, *line2 - text_base);
+ if (tem)
+ {
+ if (keyfields[i].reverse)
+ return - tem;
+ return tem;
+ }
+ }
+
+ return 0; /* Lines match exactly */
+}
+
+/* Compare two lines described by structures
+ in which the first keyfield is identified in advance.
+ For positional sorting, assumes that the order of the lines in core
+ reflects their nominal order. */
+
+int
+compare_prepared (line1, line2)
+ struct lineinfo *line1, *line2;
+{
+ int i;
+ int tem;
+ char *text1, *text2;
+
+ /* Compare using the first keyfield, which has been found for us already */
+ if (keyfields->positional)
+ {
+ if (line1->text - text_base > line2->text - text_base)
+ tem = 1;
+ else
+ tem = -1;
+ }
+ else if (keyfields->numeric)
+ tem = line1->key.number - line2->key.number;
+ else
+ tem = compare_field (keyfields, line1->key.text, line1->keylen, 0, line2->key.text, line2->keylen, 0);
+ if (tem)
+ {
+ if (keyfields->reverse)
+ return - tem;
+ return tem;
+ }
+
+ text1 = line1->text;
+ text2 = line2->text;
+
+ /* Compare using the second keyfield;
+ if that does not distinguish the lines, try the third keyfield; and so on. */
+
+ for (i = 1; i < num_keyfields; i++)
+ {
+ long length1, length2;
+ char *start1 = find_field (&keyfields[i], text1, &length1);
+ char *start2 = find_field (&keyfields[i], text2, &length2);
+ int tem = compare_field (&keyfields[i], start1, length1, text1 - text_base,
+ start2, length2, text2 - text_base);
+ if (tem)
+ {
+ if (keyfields[i].reverse)
+ return - tem;
+ return tem;
+ }
+ }
+
+ return 0; /* Lines match exactly */
+}
+
+/* Like compare_full but more general.
+ You can pass any strings, and you can say how many keyfields to use.
+ `pos1' and `pos2' should indicate the nominal positional ordering of
+ the two lines in the input. */
+
+int
+compare_general (str1, str2, pos1, pos2, use_keyfields)
+ char *str1, *str2;
+ long pos1, pos2;
+ int use_keyfields;
+{
+ int i;
+
+ /* Compare using the first keyfield;
+ if that does not distinguish the lines, try the second keyfield; and so on. */
+
+ for (i = 0; i < use_keyfields; i++)
+ {
+ long length1, length2;
+ char *start1 = find_field (&keyfields[i], str1, &length1);
+ char *start2 = find_field (&keyfields[i], str2, &length2);
+ int tem = compare_field (&keyfields[i], start1, length1, pos1, start2, length2, pos2);
+ if (tem)
+ {
+ if (keyfields[i].reverse)
+ return - tem;
+ return tem;
+ }
+ }
+
+ return 0; /* Lines match exactly */
+}
+
+/* Find the start and length of a field in `str' according to `keyfield'.
+ A pointer to the starting character is returned, and the length
+ is stored into the int that `lengthptr' points to. */
+
+char *
+find_field (keyfield, str, lengthptr)
+ struct keyfield *keyfield;
+ char *str;
+ long *lengthptr;
+{
+ char *start;
+ char *end;
+ char *(*fun) ();
+
+ if (keyfield->braced) fun = find_braced_pos;
+ else fun = find_pos;
+
+ start = ( *fun )(str, keyfield->startwords, keyfield->startchars,
+ keyfield->ignore_blanks);
+ if (keyfield->endwords < 0)
+ {
+ if (keyfield->braced)
+ end = find_braced_end (start);
+ else
+ {
+ end = start;
+ while (*end && *end != '\n') end++;
+ }
+ }
+ else
+ {
+ end = ( *fun )(str, keyfield->endwords, keyfield->endchars, 0);
+ if (end - str < start - str) end = start;
+ }
+ *lengthptr = end - start;
+ return start;
+}
+
+/* Find a pointer to a specified place within `str',
+ skipping (from the beginning) `words' words and then `chars' chars.
+ If `ignore_blanks' is nonzero, we skip all blanks
+ after finding the specified word. */
+
+char *
+find_pos (str, words, chars, ignore_blanks)
+ char *str;
+ int words, chars;
+ int ignore_blanks;
+{
+ int i;
+ char *p = str;
+
+ for (i = 0; i < words; i++)
+ {
+ char c;
+ /* Find next bunch of nonblanks and skip them. */
+ while ((c = *p) == ' ' || c == '\t') p++;
+ while ((c = *p) && c != '\n' && !(c == ' ' || c == '\t')) p++;
+ if (!*p || *p == '\n') return p;
+ }
+
+ while (*p == ' ' || *p == '\t') p++;
+
+ for (i = 0; i < chars; i++)
+ {
+ if (!*p || *p == '\n') break;
+ p++;
+ }
+ return p;
+}
+
+/* Like find_pos but assumes that each field is surrounded by braces
+ and that braces within fields are balanced. */
+
+char *
+find_braced_pos (str, words, chars, ignore_blanks)
+ char *str;
+ int words, chars;
+ int ignore_blanks;
+{
+ int i;
+ int bracelevel;
+ char *p = str;
+ char c;
+
+ for (i = 0; i < words; i++)
+ {
+ bracelevel = 1;
+ while ((c = *p++) != '{' && c != '\n' && c);
+ if (c != '{')
+ return p - 1;
+ while (bracelevel)
+ {
+ c = *p++;
+ if (c == '{') bracelevel++;
+ if (c == '}') bracelevel--;
+ if (c == '\\') c = *p++; /* \ quotes braces and \ */
+ if (c == 0 || c == '\n') return p-1;
+ }
+ }
+
+ while ((c = *p++) != '{' && c != '\n' && c);
+
+ if (c != '{')
+ return p-1;
+
+ if (ignore_blanks)
+ while ((c = *p) == ' ' || c == '\t') p++;
+
+ for (i = 0; i < chars; i++)
+ {
+ if (!*p || *p == '\n') break;
+ p++;
+ }
+ return p;
+}
+
+/* Find the end of the balanced-brace field which starts at `str'.
+ The position returned is just before the closing brace. */
+
+char *
+find_braced_end (str)
+ char *str;
+{
+ int bracelevel;
+ char *p = str;
+ char c;
+
+ bracelevel = 1;
+ while (bracelevel)
+ {
+ c = *p++;
+ if (c == '{') bracelevel++;
+ if (c == '}') bracelevel--;
+ if (c == '\\') c = *p++;
+ if (c == 0 || c == '\n') return p-1;
+ }
+ return p - 1;
+}
+
+long
+find_value (start, length)
+ char *start;
+ long length;
+{
+ while (length != 0L) {
+ if (isdigit(*start))
+ return atol(start);
+ length--;
+ start++;
+ }
+ return 0l;
+}
+
+/* Vector used to translate characters for comparison.
+ This is how we make all alphanumerics follow all else,
+ and ignore case in the first sorting. */
+int char_order[256];
+
+init_char_order ()
+{
+ int i;
+ for (i = 1; i < 256; i++)
+ char_order[i] = i;
+
+ for (i = '0'; i <= '9'; i++)
+ char_order[i] += 512;
+
+ for (i = 'a'; i <= 'z'; i++) {
+ char_order[i] = 512 + i;
+ char_order[i + 'A' - 'a'] = 512 + i;
+ }
+}
+
+/* Compare two fields (each specified as a start pointer and a character count)
+ according to `keyfield'. The sign of the value reports the relation between the fields */
+
+int
+compare_field (keyfield, start1, length1, pos1, start2, length2, pos2)
+ struct keyfield *keyfield;
+ char *start1;
+ long length1;
+ long pos1;
+ char *start2;
+ long length2;
+ long pos2;
+{
+ if (keyfields->positional)
+ {
+ if (pos1 > pos2)
+ return 1;
+ else
+ return -1;
+ }
+ if (keyfield->numeric)
+ {
+ long value = find_value (start1, length1) - find_value (start2, length2);
+ if (value > 0) return 1;
+ if (value < 0) return -1;
+ return 0;
+ }
+ else
+ {
+ char *p1 = start1;
+ char *p2 = start2;
+ char *e1 = start1 + length1;
+ char *e2 = start2 + length2;
+
+ int fold_case = keyfield->fold_case;
+
+ while (1)
+ {
+ int c1, c2;
+
+ if (p1 == e1) c1 = 0;
+ else c1 = *p1++;
+ if (p2 == e2) c2 = 0;
+ else c2 = *p2++;
+
+ if (char_order[c1] != char_order[c2])
+ return char_order[c1] - char_order[c2];
+ if (!c1) break;
+ }
+
+ /* Strings are equal except possibly for case. */
+ p1 = start1;
+ p2 = start2;
+ while (1)
+ {
+ int c1, c2;
+
+ if (p1 == e1) c1 = 0;
+ else c1 = *p1++;
+ if (p2 == e2) c2 = 0;
+ else c2 = *p2++;
+
+ if (c1 != c2)
+ /* Reverse sign here so upper case comes out last. */
+ return c2 - c1;
+ if (!c1) break;
+ }
+
+ return 0;
+ }
+}
+
+/* A `struct linebuffer' is a structure which holds a line of text.
+ `readline' reads a line from a stream into a linebuffer
+ and works regardless of the length of the line. */
+
+struct linebuffer
+ {
+ long size;
+ char *buffer;
+ };
+
+/* Initialize a linebuffer for use */
+
+void
+initbuffer (linebuffer)
+ struct linebuffer *linebuffer;
+{
+ linebuffer->size = 200;
+ linebuffer->buffer = (char *) xmalloc (200);
+}
+
+/* Read a line of text from `stream' into `linebuffer'.
+ Return the length of the line. */
+
+long
+readline (linebuffer, stream)
+ struct linebuffer *linebuffer;
+ FILE *stream;
+{
+ char *buffer = linebuffer->buffer;
+ char *p = linebuffer->buffer;
+ char *end = p + linebuffer->size;
+
+ while (1)
+ {
+ int c = getc (stream);
+ if (p == end)
+ {
+ buffer = (char *) xrealloc (buffer, linebuffer->size *= 2);
+ p += buffer - linebuffer->buffer;
+ end += buffer - linebuffer->buffer;
+ linebuffer->buffer = buffer;
+ }
+ if (c < 0 || c == '\n')
+ {
+ *p = 0;
+ break;
+ }
+ *p++ = c;
+ }
+
+ return p - buffer;
+}
+
+/* Sort an input file too big to sort in core. */
+
+void
+sort_offline (infile, nfiles, total, outfile)
+ char *infile;
+ long total;
+ char *outfile;
+{
+ int ntemps = 2 * (total + MAX_IN_CORE_SORT - 1) / MAX_IN_CORE_SORT; /* More than enough */
+ char **tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
+ FILE *istream = fopen (infile, "r");
+ int i;
+ struct linebuffer lb;
+ long linelength;
+ int failure = 0;
+
+ initbuffer (&lb);
+
+ /* Read in one line of input data. */
+
+ linelength = readline (&lb, istream);
+
+ if (lb.buffer[0] != '\\')
+ {
+ error ("%s: not a texinfo index file", infile);
+ return;
+ }
+
+ /* Split up the input into `ntemps' temporary files, or maybe fewer,
+ and put the new files' names into `tempfiles' */
+
+ for (i = 0; i < ntemps; i++)
+ {
+ char *outname = maketempname (++tempcount);
+ FILE *ostream = fopen (outname, "w");
+ long tempsize = 0;
+
+ if (!ostream) pfatal_with_name (outname);
+ tempfiles[i] = outname;
+
+ /* Copy lines into this temp file as long as it does not make file "too big"
+ or until there are no more lines. */
+
+ while (tempsize + linelength + 1 <= MAX_IN_CORE_SORT)
+ {
+ tempsize += linelength + 1;
+ fputs (lb.buffer, ostream);
+ putc ('\n', ostream);
+
+ /* Read another line of input data. */
+
+ linelength = readline (&lb, istream);
+ if (!linelength && feof (istream)) break;
+
+ if (lb.buffer[0] != '\\')
+ {
+ error ("%s: not a texinfo index file", infile);
+ failure = 1;
+ goto fail;
+ }
+ }
+ fclose (ostream);
+ if (feof (istream)) break;
+ }
+
+ free (lb.buffer);
+
+ fail:
+ /* Record number of temp files we actually needed. */
+
+ ntemps = i;
+
+ /* Sort each tempfile into another tempfile.
+ Delete the first set of tempfiles and put the names of the second into `tempfiles' */
+
+ for (i = 0; i < ntemps; i++)
+ {
+ char *newtemp = maketempname (++tempcount);
+ sort_in_core (&tempfiles[i], MAX_IN_CORE_SORT, newtemp);
+ if (!keep_tempfiles)
+ unlink (tempfiles[i]);
+ tempfiles[i] = newtemp;
+ }
+
+ if (failure)
+ return;
+
+ /* Merge the tempfiles together and indexify */
+
+ merge_files (tempfiles, ntemps, outfile);
+}
+
+/* Sort `infile', whose size is `total',
+ assuming that is small enough to be done in-core,
+ then indexify it and send the output to `outfile' (or to stdout). */
+
+void
+sort_in_core (infile, total, outfile)
+ char *infile;
+ long total;
+ char *outfile;
+{
+ char **nextline;
+ char *data = (char *) xmalloc (total + 1);
+ char *file_data;
+ long file_size;
+ int i;
+ FILE *ostream = stdout;
+ struct lineinfo *lineinfo;
+
+ /* Read the contents of the file into the moby array `data' */
+
+ int desc = open (infile, 0, 0);
+
+ if (desc < 0)
+ fatal ("failure reopening %s", infile);
+ for (file_size = 0; ; )
+ {
+ if ((i = read (desc, data + file_size, total - file_size)) <= 0)
+ break;
+ file_size += i;
+ }
+ file_data = data;
+ data[file_size] = 0;
+
+ close (desc);
+
+ if (file_size > 0 && data[0] != '\\')
+ {
+ error ("%s: not a texinfo index file", infile);
+ return;
+ }
+
+ init_char_order ();
+
+ /* Sort routines want to know this address */
+
+ text_base = data;
+
+ /* Create the array of pointers to lines, with a default size frequently enough. */
+
+ lines = total / 50;
+ if (!lines) lines = 2;
+ linearray = (char **) xmalloc (lines * sizeof (char *));
+
+ /* `nextline' points to the next free slot in this array.
+ `lines' is the allocated size. */
+
+ nextline = linearray;
+
+ /* Parse the input file's data, and make entries for the lines. */
+
+ nextline = parsefile (infile, nextline, file_data, file_size);
+ if (nextline == 0)
+ {
+ error ("%s: not a texinfo index file", infile);
+ return;
+ }
+
+ /* Sort the lines */
+
+ /* If we have enough space, find the first keyfield of each line in advance.
+ Make a `struct lineinfo' for each line, which records the keyfield
+ as well as the line, and sort them. */
+
+ lineinfo = (struct lineinfo *) malloc ((nextline - linearray) * sizeof (struct lineinfo));
+
+ if (lineinfo)
+ {
+ struct lineinfo *lp;
+ char **p;
+
+ for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
+ {
+ lp->text = *p;
+ lp->key.text = find_field (keyfields, *p, &lp->keylen);
+ if (keyfields->numeric)
+ lp->key.number = find_value (lp->key.text, lp->keylen);
+ }
+
+ qsort (lineinfo, nextline - linearray, sizeof (struct lineinfo), compare_prepared);
+
+ for (lp = lineinfo, p = linearray; p != nextline; lp++, p++)
+ *p = lp->text;
+
+ free (lineinfo);
+ }
+ else
+ qsort (linearray, nextline - linearray, sizeof (char *), compare_full);
+
+ /* Open the output file */
+
+ if (outfile)
+ {
+ ostream = fopen (outfile, "w");
+ if (!ostream)
+ pfatal_with_name (outfile);
+ }
+
+ writelines (linearray, nextline - linearray, ostream);
+ if (outfile) fclose (ostream);
+
+ free (linearray);
+ free (data);
+}
+
+/* Parse an input string in core into lines.
+ DATA is the input string, and SIZE is its length.
+ Data goes in LINEARRAY starting at NEXTLINE.
+ The value returned is the first entry in LINEARRAY still unused.
+ Value 0 means input file contents are invalid. */
+
+char **
+parsefile (filename, nextline, data, size)
+ char *filename;
+ char **nextline;
+ char *data;
+ long size;
+{
+ char *p, *end;
+ char **line = nextline;
+
+ p = data;
+ end = p + size;
+ *end = 0;
+
+ while (p != end)
+ {
+ if (p[0] != '\\')
+ return 0;
+
+ *line = p;
+ while (*p && *p != '\n') p++;
+ if (p != end) p++;
+
+ line++;
+ if (line == linearray + lines)
+ {
+ char **old = linearray;
+ linearray = (char **) xrealloc (linearray, sizeof (char *) * (lines *= 4));
+ line += linearray - old;
+ }
+ }
+
+ return line;
+}
+
+/* Indexification is a filter applied to the sorted lines
+ as they are being written to the output file.
+ Multiple entries for the same name, with different page numbers,
+ get combined into a single entry with multiple page numbers.
+ The first braced field, which is used for sorting, is discarded.
+ However, its first character is examined, folded to lower case,
+ and if it is different from that in the previous line fed to us
+ a \initial line is written with one argument, the new initial.
+
+ If an entry has four braced fields, then the second and third
+ constitute primary and secondary names.
+ In this case, each change of primary name
+ generates a \primary line which contains only the primary name,
+ and in between these are \secondary lines which contain
+ just a secondary name and page numbers.
+*/
+
+/* The last primary name we wrote a \primary entry for.
+ If only one level of indexing is being done, this is the last name seen */
+char *lastprimary;
+int lastprimarylength; /* Length of storage allocated for lastprimary */
+
+/* Similar, for the secondary name. */
+char *lastsecondary;
+int lastsecondarylength;
+
+/* Zero if we are not in the middle of writing an entry.
+ One if we have written the beginning of an entry but have not
+ yet written any page numbers into it.
+ Greater than one if we have written the beginning of an entry
+ plus at least one page number. */
+int pending;
+
+/* The initial (for sorting purposes) of the last primary entry written.
+ When this changes, a \initial {c} line is written */
+
+char * lastinitial;
+
+int lastinitiallength;
+
+/* When we need a string of length 1 for the value of lastinitial,
+ store it here. */
+
+char lastinitial1[2];
+
+/* Initialize static storage for writing an index */
+
+void
+init_index ()
+{
+ pending = 0;
+ lastinitial = lastinitial1;
+ lastinitial1[0] = 0;
+ lastinitial1[1] = 0;
+ lastinitiallength = 0;
+ lastprimarylength = 100;
+ lastprimary = (char *) xmalloc (lastprimarylength + 1);
+ bzero (lastprimary, lastprimarylength + 1);
+ lastsecondarylength = 100;
+ lastsecondary = (char *) xmalloc (lastsecondarylength + 1);
+ bzero (lastsecondary, lastsecondarylength + 1);
+}
+
+/* Indexify. Merge entries for the same name,
+ insert headers for each initial character, etc. */
+
+indexify (line, ostream)
+ char *line;
+ FILE *ostream;
+{
+ char *primary, *secondary, *pagenumber;
+ int primarylength, secondarylength, pagelength;
+ int len = strlen (line);
+ int nosecondary;
+ int initiallength;
+ char *initial;
+ char initial1[2];
+ register char *p;
+
+ /* First, analyze the parts of the entry fed to us this time */
+
+ p = find_braced_pos (line, 0, 0, 0);
+ if (*p == '{')
+ {
+ initial = p;
+ /* Get length of inner pair of braces starting at p,
+ including that inner pair of braces. */
+ initiallength = find_braced_end (p + 1) + 1 - p;
+ }
+ else
+ {
+ initial = initial1;
+ initial1[0] = *p;
+ initial1[1] = 0;
+ initiallength = 1;
+
+ if (initial1[0] >= 'a' && initial1[0] <= 'z')
+ initial1[0] -= 040;
+ }
+
+ pagenumber = find_braced_pos (line, 1, 0, 0);
+ pagelength = find_braced_end (pagenumber) - pagenumber;
+ if (pagelength == 0)
+ abort ();
+
+ primary = find_braced_pos (line, 2, 0, 0);
+ primarylength = find_braced_end (primary) - primary;
+
+ secondary = find_braced_pos (line, 3, 0, 0);
+ nosecondary = !*secondary;
+ if (!nosecondary)
+ secondarylength = find_braced_end (secondary) - secondary;
+
+ /* If the primary is different from before, make a new primary entry */
+ if (strncmp (primary, lastprimary, primarylength))
+ {
+ /* Close off current secondary entry first, if one is open */
+ if (pending)
+ {
+ fputs ("}\n", ostream);
+ pending = 0;
+ }
+
+ /* If this primary has a different initial, include an entry for the initial */
+ if (initiallength != lastinitiallength ||
+ strncmp (initial, lastinitial, initiallength))
+ {
+ fprintf (ostream, "\\initial {");
+ fwrite (initial, 1, initiallength, ostream);
+ fprintf (ostream, "}\n", initial);
+ if (initial == initial1)
+ {
+ lastinitial = lastinitial1;
+ *lastinitial1 = *initial1;
+ }
+ else
+ {
+ lastinitial = initial;
+ }
+ lastinitiallength = initiallength;
+ }
+
+ /* Make the entry for the primary. */
+ if (nosecondary)
+ fputs ("\\entry {", ostream);
+ else
+ fputs ("\\primary {", ostream);
+ fwrite (primary, primarylength, 1, ostream);
+ if (nosecondary)
+ {
+ fputs ("}{", ostream);
+ pending = 1;
+ }
+ else
+ fputs ("}\n", ostream);
+
+ /* Record name of most recent primary */
+ if (lastprimarylength < primarylength)
+ {
+ lastprimarylength = primarylength + 100;
+ lastprimary = (char *) xrealloc (lastprimary,
+ 1 + lastprimarylength);
+ }
+ strncpy (lastprimary, primary, primarylength);
+ lastprimary[primarylength] = 0;
+
+ /* There is no current secondary within this primary, now */
+ lastsecondary[0] = 0;
+ }
+
+ /* Should not have an entry with no subtopic following one with a subtopic */
+
+ if (nosecondary && *lastsecondary)
+ error ("entry %s follows an entry with a secondary name", line);
+
+ /* Start a new secondary entry if necessary */
+ if (!nosecondary && strncmp (secondary, lastsecondary, secondarylength))
+ {
+ if (pending)
+ {
+ fputs ("}\n", ostream);
+ pending = 0;
+ }
+
+ /* Write the entry for the secondary. */
+ fputs ("\\secondary {", ostream);
+ fwrite (secondary, secondarylength, 1, ostream);
+ fputs ("}{", ostream);
+ pending = 1;
+
+ /* Record name of most recent secondary */
+ if (lastsecondarylength < secondarylength)
+ {
+ lastsecondarylength = secondarylength + 100;
+ lastsecondary = (char *) xrealloc (lastsecondary,
+ 1 + lastsecondarylength);
+ }
+ strncpy (lastsecondary, secondary, secondarylength);
+ lastsecondary[secondarylength] = 0;
+ }
+
+ /* Here to add one more page number to the current entry */
+ if (pending++ != 1)
+ fputs (", ", ostream); /* Punctuate first, if this is not the first */
+ fwrite (pagenumber, pagelength, 1, ostream);
+}
+
+/* Close out any unfinished output entry */
+
+void
+finish_index (ostream)
+ FILE *ostream;
+{
+ if (pending)
+ fputs ("}\n", ostream);
+ free (lastprimary);
+ free (lastsecondary);
+}
+
+/* Copy the lines in the sorted order.
+ Each line is copied out of the input file it was found in. */
+
+void
+writelines (linearray, nlines, ostream)
+ char **linearray;
+ int nlines;
+ FILE *ostream;
+{
+ char **stop_line = linearray + nlines;
+ char **next_line;
+
+ init_index ();
+
+ /* Output the text of the lines, and free the buffer space */
+
+ for (next_line = linearray; next_line != stop_line; next_line++)
+ {
+ /* If -u was specified, output the line only if distinct from previous one. */
+ if (next_line == linearray
+ /* Compare previous line with this one, using only the explicitly specd keyfields */
+ || compare_general (*(next_line - 1), *next_line, 0L, 0L, num_keyfields - 1))
+ {
+ char *p = *next_line;
+ char c;
+ while ((c = *p++) && c != '\n');
+ *(p-1) = 0;
+ indexify (*next_line, ostream);
+ }
+ }
+
+ finish_index (ostream);
+}
+
+/* Assume (and optionally verify) that each input file is sorted;
+ merge them and output the result.
+ Returns nonzero if any input file fails to be sorted.
+
+ This is the high-level interface that can handle an unlimited number of files. */
+
+#define MAX_DIRECT_MERGE 10
+
+int
+merge_files (infiles, nfiles, outfile)
+ char **infiles;
+ int nfiles;
+ char *outfile;
+{
+ char **tempfiles;
+ int ntemps;
+ int i;
+ int value = 0;
+ int start_tempcount = tempcount;
+
+ if (nfiles <= MAX_DIRECT_MERGE)
+ return merge_direct (infiles, nfiles, outfile);
+
+ /* Merge groups of MAX_DIRECT_MERGE input files at a time,
+ making a temporary file to hold each group's result. */
+
+ ntemps = (nfiles + MAX_DIRECT_MERGE - 1) / MAX_DIRECT_MERGE;
+ tempfiles = (char **) xmalloc (ntemps * sizeof (char *));
+ for (i = 0; i < ntemps; i++)
+ {
+ int nf = MAX_DIRECT_MERGE;
+ if (i + 1 == ntemps)
+ nf = nfiles - i * MAX_DIRECT_MERGE;
+ tempfiles[i] = maketempname (++tempcount);
+ value |= merge_direct (&infiles[i * MAX_DIRECT_MERGE], nf, tempfiles[i]);
+ }
+
+ /* All temporary files that existed before are no longer needed
+ since their contents have been merged into our new tempfiles.
+ So delete them. */
+ flush_tempfiles (start_tempcount);
+
+ /* Now merge the temporary files we created. */
+
+ merge_files (tempfiles, ntemps, outfile);
+
+ free (tempfiles);
+
+ return value;
+}
+
+/* Assume (and optionally verify) that each input file is sorted;
+ merge them and output the result.
+ Returns nonzero if any input file fails to be sorted.
+
+ This version of merging will not work if the number of
+ input files gets too high. Higher level functions
+ use it only with a bounded number of input files. */
+
+int
+merge_direct (infiles, nfiles, outfile)
+ char **infiles;
+ int nfiles;
+ char *outfile;
+{
+ char **ip = infiles;
+ struct linebuffer *lb1, *lb2;
+ struct linebuffer **thisline, **prevline;
+ FILE **streams;
+ int i;
+ int nleft;
+ int lossage = 0;
+ int *file_lossage;
+ struct linebuffer *prev_out = 0;
+ FILE *ostream = stdout;
+
+ if (outfile)
+ {
+ ostream = fopen (outfile, "w");
+ }
+ if (!ostream) pfatal_with_name (outfile);
+
+ init_index ();
+
+ if (nfiles == 0)
+ {
+ if (outfile)
+ fclose (ostream);
+ return 0;
+ }
+
+ /* For each file, make two line buffers.
+ Also, for each file, there is an element of `thisline'
+ which points at any time to one of the file's two buffers,
+ and an element of `prevline' which points to the other buffer.
+ `thisline' is supposed to point to the next available line from the file,
+ while `prevline' holds the last file line used,
+ which is remembered so that we can verify that the file is properly sorted. */
+
+ /* lb1 and lb2 contain one buffer each per file */
+ lb1 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
+ lb2 = (struct linebuffer *) xmalloc (nfiles * sizeof (struct linebuffer));
+
+ /* thisline[i] points to the linebuffer holding the next available line in file i,
+ or is zero if there are no lines left in that file. */
+ thisline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *));
+ /* prevline[i] points to the linebuffer holding the last used line from file i.
+ This is just for verifying that file i is properly sorted. */
+ prevline = (struct linebuffer **) xmalloc (nfiles * sizeof (struct linebuffer *));
+ /* streams[i] holds the input stream for file i. */
+ streams = (FILE **) xmalloc (nfiles * sizeof (FILE *));
+ /* file_lossage[i] is nonzero if we already know file i is not properly sorted. */
+ file_lossage = (int *) xmalloc (nfiles * sizeof (int));
+
+ /* Allocate and initialize all that storage */
+
+ for (i = 0; i < nfiles; i++)
+ {
+ initbuffer (&lb1[i]);
+ initbuffer (&lb2[i]);
+ thisline[i] = &lb1[i];
+ prevline[i] = &lb2[i];
+ file_lossage[i] = 0;
+ streams[i] = fopen (infiles[i], "r");
+ if (!streams[i])
+ pfatal_with_name (infiles[i]);
+
+ readline (thisline[i], streams[i]);
+ }
+
+ /* Keep count of number of files not at eof */
+ nleft = nfiles;
+
+ while (nleft)
+ {
+ struct linebuffer *best = 0;
+ struct linebuffer *exch;
+ int bestfile = -1;
+ int i;
+
+ /* Look at the next avail line of each file; choose the least one. */
+
+ for (i = 0; i < nfiles; i++)
+ {
+ if (thisline[i] &&
+ (!best ||
+ 0 < compare_general (best->buffer, thisline[i]->buffer,
+ (long) bestfile, (long) i, num_keyfields)))
+ {
+ best = thisline[i];
+ bestfile = i;
+ }
+ }
+
+ /* Output that line, unless it matches the previous one and we don't want duplicates */
+
+ if (!(prev_out &&
+ !compare_general (prev_out->buffer, best->buffer, 0L, 1L, num_keyfields - 1)))
+ indexify (best->buffer, ostream);
+ prev_out = best;
+
+ /* Now make the line the previous of its file, and fetch a new line from that file */
+
+ exch = prevline[bestfile];
+ prevline[bestfile] = thisline[bestfile];
+ thisline[bestfile] = exch;
+
+ while (1)
+ {
+ /* If the file has no more, mark it empty */
+
+ if (feof (streams[bestfile]))
+ {
+ thisline[bestfile] = 0;
+ nleft--; /* Update the number of files still not empty */
+ break;
+ }
+ readline (thisline[bestfile], streams[bestfile]);
+ if (thisline[bestfile]->buffer[0] || !feof (streams[bestfile])) break;
+ }
+ }
+
+ finish_index (ostream);
+
+ /* Free all storage and close all input streams */
+
+ for (i = 0; i < nfiles; i++)
+ {
+ fclose (streams[i]);
+ free (lb1[i].buffer);
+ free (lb2[i].buffer);
+ }
+ free (file_lossage);
+ free (lb1);
+ free (lb2);
+ free (thisline);
+ free (prevline);
+ free (streams);
+
+ if (outfile)
+ fclose (ostream);
+
+ return lossage;
+}
+
+/* Print error message and exit. */
+
+fatal (s1, s2)
+ char *s1, *s2;
+{
+ error (s1, s2);
+ exit (EXIT_FATAL);
+}
+
+/* Print error message. `s1' is printf control string, `s2' is arg for it. */
+
+error (s1, s2)
+ char *s1, *s2;
+{
+ printf ("texindex: ");
+ printf (s1, s2);
+ printf ("\n");
+}
+
+perror_with_name (name)
+ char *name;
+{
+#ifdef VMS
+#include <errno.h>
+ extern noshare int sys_nerr;
+ extern noshare char *sys_errlist[];
+#else
+ extern int errno, sys_nerr;
+ extern char *sys_errlist[];
+#endif
+ char *s;
+
+ if (errno < sys_nerr)
+ s = concat ("", sys_errlist[errno], " for %s");
+ else
+ s = "cannot open %s";
+ error (s, name);
+}
+
+pfatal_with_name (name)
+ char *name;
+{
+ extern int errno, sys_nerr;
+ extern char *sys_errlist[];
+ char *s;
+
+ if (errno < sys_nerr)
+ s = concat ("", sys_errlist[errno], " for %s");
+ else
+ s = "cannot open %s";
+ fatal (s, name);
+}
+
+/* Return a newly-allocated string whose contents concatenate those of s1, s2, s3. */
+
+char *
+concat (s1, s2, s3)
+ char *s1, *s2, *s3;
+{
+ int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
+ char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
+
+ strcpy (result, s1);
+ strcpy (result + len1, s2);
+ strcpy (result + len1 + len2, s3);
+ *(result + len1 + len2 + len3) = 0;
+
+ return result;
+}
+
+/* Like malloc but get fatal error if memory is exhausted. */
+
+int
+xmalloc (size)
+ int size;
+{
+ int result = malloc (size);
+ if (!result)
+ fatal ("virtual memory exhausted", 0);
+ return result;
+}
+
+
+int
+xrealloc (ptr, size)
+ char *ptr;
+ int size;
+{
+ int result = realloc (ptr, size);
+ if (!result)
+ fatal ("virtual memory exhausted");
+ return result;
+}
+
+bzero (b, length)
+ register char *b;
+ register int length;
+{
+#ifdef VMS
+ short zero = 0;
+ long max_str = 65535;
+
+ while (length > max_str) {
+ (void) LIB$MOVC5 (&zero, &zero, &zero, &max_str, b);
+ length -= max_str;
+ b += max_str;
+ }
+ (void) LIB$MOVC5 (&zero, &zero, &zero, &length, b);
+#else
+ while (length-- > 0)
+ *b++ = 0;
+#endif /* not VMS */
+}
diff --git a/support/texinfo.tex b/support/texinfo.tex
new file mode 100644
index 00000000..0810241a
--- /dev/null
+++ b/support/texinfo.tex
@@ -0,0 +1,2357 @@
+%% TeX macros to handle texinfo files
+
+% Copyright (C) 1985, 1986, 1988 Free Software Foundation, Inc.
+
+%GNU CC is free software; you can redistribute it and/or modify
+%it under the terms of the GNU General Public License as published by
+%the Free Software Foundation; either version 1, or (at your option)
+%any later version.
+
+%GNU CC is distributed in the hope that it will be useful,
+%but WITHOUT ANY WARRANTY; without even the implied warranty of
+%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+%GNU General Public License for more details.
+
+%You should have received a copy of the GNU General Public License
+%along with GNU CC; see the file COPYING. If not, write to
+%the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
+
+
+%In other words, you are welcome to use, share and improve this program.
+%You are forbidden to forbid anyone else to use, share and improve
+%what you give them. Help stamp out software-hoarding!
+
+\def\texinfoversion{2.1}
+\message{Loading texinfo package [Version \texinfoversion]:}
+\message{}
+
+% Save some parts of plain tex whose names we will redefine.
+
+\let\ptexlbrace=\{
+\let\ptexrbrace=\}
+\let\ptexdot=\.
+\let\ptexstar=\*
+\let\ptexend=\end
+\let\ptexbullet=\bullet
+\let\ptexb=\b
+\let\ptexc=\c
+\let\ptexi=\i
+\let\ptext=\t
+\let\ptexl=\l
+\let\ptexL=\L
+
+\def\tie{\penalty 10000\ } % Save plain tex definition of ~.
+
+\message{Basics,}
+\chardef\other=12
+
+\hyphenation{ap-pen-dix}
+\hyphenation{mini-buf-fer mini-buf-fers}
+\hyphenation{eshell}
+
+% Margin to add to right of even pages, to left of odd pages.
+\newdimen \bindingoffset \bindingoffset=0pt
+\newdimen \normaloffset \normaloffset=\hoffset
+\newdimen\pagewidth \newdimen\pageheight
+\pagewidth=\hsize \pageheight=\vsize
+
+%---------------------Begin change-----------------------
+%
+% Dimensions to add cropmarks at corners Added by P. A. MacKay, 12 Nov. 1986
+%
+\newdimen\cornerlong \newdimen\cornerthick
+\newdimen \topandbottommargin
+\newdimen \outerhsize \newdimen \outervsize
+\cornerlong=1pc\cornerthick=.3pt % These set size of cropmarks
+\outerhsize=7in
+\outervsize=9.5in
+\topandbottommargin=.75in
+%
+%---------------------End change-----------------------
+
+% \onepageout takes a vbox as an argument. Note that \pagecontents
+% does insertions itself, but you have to call it yourself.
+\chardef\PAGE=255 \output={\onepageout{\pagecontents\PAGE}}
+\def\onepageout#1{\hoffset=\normaloffset
+\ifodd\pageno \advance\hoffset by \bindingoffset
+\else \advance\hoffset by -\bindingoffset\fi
+\shipout\vbox{{\let\hsize=\pagewidth \makeheadline} \pagebody{#1}%
+ {\let\hsize=\pagewidth \makefootline}}
+\advancepageno \ifnum\outputpenalty>-20000 \else\dosupereject\fi}
+
+
+% Here is a modification of the main output routine for Near East Publications
+% This provides right-angle cropmarks at all four corners.
+% The contents of the page are centerlined into the cropmarks,
+% and any desired binding offset is added as an \hskip on either
+% site of the centerlined box. (P. A. MacKay, 12 November, 1986)
+%
+\def\croppageout#1{\hoffset=0pt % make sure this doesn't mess things up
+ \shipout
+ \vbox to \outervsize{\hsize=\outerhsize
+ \vbox{\line{\ewtop\hfill\ewtop}}
+ \nointerlineskip
+ \line{\vbox{\moveleft\cornerthick\nstop}
+ \hfill
+ \vbox{\moveright\cornerthick\nstop}}
+ \vskip \topandbottommargin
+ \centerline{\ifodd\pageno\hskip\bindingoffset\fi
+ \vbox{
+ {\let\hsize=\pagewidth \makeheadline}
+ \pagebody{#1}
+ {\let\hsize=\pagewidth \makefootline}}
+ \ifodd\pageno\else\hskip\bindingoffset\fi}
+ \vskip \topandbottommargin plus1fill minus1fill
+ \boxmaxdepth\cornerthick
+ \line{\vbox{\moveleft\cornerthick\nsbot}
+ \hfill
+ \vbox{\moveright\cornerthick\nsbot}}
+ \nointerlineskip
+ \vbox{\line{\ewbot\hfill\ewbot}}
+ }
+ \advancepageno
+ \ifnum\outputpenalty>-20000 \else\dosupereject\fi}
+%
+% Do @cropmarks to get crop marks
+\def\cropmarks{\let\onepageout=\croppageout }
+
+\def\pagebody#1{\vbox to\pageheight{\boxmaxdepth=\maxdepth #1}}
+{\catcode`\@ =11
+\gdef\pagecontents#1{\ifvoid\topins\else\unvbox\topins\fi
+\dimen@=\dp#1 \unvbox#1
+\ifvoid\footins\else\vskip\skip\footins\footnoterule \unvbox\footins\fi
+\ifr@ggedbottom \kern-\dimen@ \vfil \fi}
+}
+
+%
+% Here are the rules for the cropmarks. Note that they are
+% offset so that the space between them is truly \outerhsize or \outervsize
+% (P. A. MacKay, 12 November, 1986)
+%
+\def\ewtop{\vrule height\cornerthick depth0pt width\cornerlong}
+\def\nstop{\vbox
+ {\hrule height\cornerthick depth\cornerlong width\cornerthick}}
+\def\ewbot{\vrule height0pt depth\cornerthick width\cornerlong}
+\def\nsbot{\vbox
+ {\hrule height\cornerlong depth\cornerthick width\cornerthick}}
+
+% Parse an argument, then pass it to #1.
+% The argument can be delimited with [...] or with "..." or braces
+% or it can be a whole line.
+% #1 should be a macro which expects
+% an ordinary undelimited TeX argument.
+
+\def\parsearg #1{\let\next=#1\begingroup\obeylines\futurelet\temp\parseargx}
+
+\def\parseargx{%
+\ifx \obeyedspace\temp \aftergroup\parseargdiscardspace \else%
+\aftergroup \parseargline %
+\fi \endgroup}
+
+{\obeyspaces %
+\gdef\parseargdiscardspace {\begingroup\obeylines\futurelet\temp\parseargx}}
+
+\gdef\obeyedspace{\ }
+
+\def\parseargline{\begingroup \obeylines \parsearglinex}
+{\obeylines %
+\gdef\parsearglinex #1^^M{\endgroup \next {#1}}}
+
+\def\flushcr{\ifx\par\lisppar \def\next##1{}\else \let\next=\relax \fi \next}
+
+%% These are used to keep @begin/@end levels from running away
+%% Call \inENV within environments (after a \begingroup)
+\newif\ifENV \ENVfalse \def\inENV{\ifENV\relax\else\ENVtrue\fi}
+\def\ENVcheck{%
+\ifENV\errmessage{Still within an environment. Type Return to continue.}
+\endgroup\fi} % This is not perfect, but it should reduce lossage
+
+% @begin foo is the same as @foo, for now.
+\newhelp\EMsimple{Type <Return> to continue}
+
+\outer\def\begin{\parsearg\beginxxx}
+
+\def\beginxxx #1{%
+\expandafter\ifx\csname #1\endcsname\relax
+{\errhelp=\EMsimple \errmessage{Undefined command @begin #1}}\else
+\csname #1\endcsname\fi}
+
+%% @end foo executes the definition of \Efoo.
+%% foo can be delimited by doublequotes or brackets.
+
+\def\end{\parsearg\endxxx}
+
+\def\endxxx #1{%
+\expandafter\ifx\csname E#1\endcsname\relax
+\expandafter\ifx\csname #1\endcsname\relax
+\errmessage{Undefined command @end #1}\else
+\errorE{#1}\fi\fi
+\csname E#1\endcsname}
+\def\errorE#1{
+{\errhelp=\EMsimple \errmessage{@end #1 not within #1 environment}}}
+
+% Single-spacing is done by various environments.
+
+\newskip\singlespaceskip \singlespaceskip = \baselineskip
+\def\singlespace{%
+{\advance \baselineskip by -\singlespaceskip
+\kern \baselineskip}%
+\baselineskip=\singlespaceskip
+}
+
+%% Simple single-character @ commands
+
+% @@ prints an @
+% Kludge this until the fonts are right (grr).
+\def\@{{\sf \char '100}}
+
+% Define @` and @' to be the same as ` and '
+% but suppressing ligatures.
+\def\`{{`}}
+\def\'{{'}}
+
+% Used to generate quoted braces.
+
+\def\mylbrace {{\tt \char '173}}
+\def\myrbrace {{\tt \char '175}}
+\let\{=\mylbrace
+\let\}=\myrbrace
+
+% @: forces normal size whitespace following.
+\def\:{\spacefactor=1000 }
+
+% @* forces a line break.
+\def\*{\hfil\break}
+
+% @. is an end-of-sentence period.
+\def\.{.\spacefactor=3000 }
+
+% @w prevents a word break
+\def\w #1{\hbox{#1}}
+
+% @group ... @end group forces ... to be all on one page.
+
+\def\group{\begingroup% \inENV ???
+\def \Egroup{\egroup\endgroup}
+\vbox\bgroup}
+
+% @br forces paragraph break
+
+\let\br = \par
+
+% @dots{} output some dots
+
+\def\dots{$\ldots$}
+
+% @page forces the start of a new page
+
+\def\page{\par\vfill\supereject}
+
+% @exdent text....
+% outputs text on separate line in roman font, starting at standard page margin
+
+\def\exdent{\errmessage{@exdent in filled text}}
+ % @lisp, etc, define \exdent locally from \internalexdent
+
+{\obeyspaces
+\gdef\internalexdent{\parsearg\exdentzzz}}
+
+\def\exdentzzz #1{{\advance \leftskip by -\lispnarrowing
+\advance \hsize by -\leftskip
+\advance \hsize by -\rightskip
+\leftline{{\rm#1}}}}
+
+% @include file insert text of that file as input.
+
+\def\include{\parsearg\includezzz}
+\def\includezzz #1{{\def\thisfile{#1}\input #1
+}}
+
+\def\thisfile{}
+
+% @center line outputs that line, centered
+
+\def\center{\parsearg\centerzzz}
+\def\centerzzz #1{{\advance\hsize by -\leftskip
+\advance\hsize by -\rightskip
+\centerline{#1}}}
+
+% @sp n outputs n lines of vertical space
+
+\def\sp{\parsearg\spxxx}
+\def\spxxx #1{\par \vskip #1\baselineskip}
+
+% @comment ...line which is ignored...
+% @c is the same as @comment
+% @ignore ... @end ignore is another way to write a comment
+
+\def\comment{\parsearg \commentxxx}
+
+\def\commentxxx #1{}
+
+\let\c=\comment
+
+% Prevent errors for section commands.
+% Used in @ignore and in failing conditionals.
+\def\ignoresections{%
+\let\chapter=\relax
+\let\unnumbered=\relax
+\let\unnumberedsec=\relax
+\let\unnumberedsection=\relax
+\let\unnumberedsubsec=\relax
+\let\unnumberedsubsection=\relax
+\let\unnumberedsubsubsec=\relax
+\let\unnumberedsubsubsection=\relax
+\let\section=\relax
+\let\subsec=\relax
+\let\subsubsec=\relax
+\let\subsection=\relax
+\let\subsubsection=\relax
+\let\appendix=\relax
+\let\appendixsec=\relax
+\let\appendixsection=\relax
+\let\appendixsubsec=\relax
+\let\appendixsubsection=\relax
+\let\appendixsubsubsec=\relax
+\let\appendixsubsubsection=\relax
+}
+
+\def\ignore{\begingroup\ignoresections\ignorexxx}
+\long\def\ignorexxx #1\end ignore{\endgroup}
+
+% Conditionals to test whether a flag is set.
+
+\outer\def\ifset{\begingroup\ignoresections\parsearg\ifsetxxx}
+
+\def\ifsetxxx #1{\endgroup
+\expandafter\ifx\csname IF#1\endcsname\relax \let\temp=\ifsetfail
+\else \let\temp=\relax \fi
+\temp}
+\def\Eifset{}
+\def\ifsetfail{\begingroup\ignoresections\ifsetfailxxx}
+\long\def\ifsetfailxxx #1\end ifset{\endgroup}
+
+\outer\def\ifclear{\begingroup\ignoresections\parsearg\ifclearxxx}
+
+\def\ifclearxxx #1{\endgroup
+\expandafter\ifx\csname IF#1\endcsname\relax \let\temp=\relax
+\else \let\temp=\ifclearfail \fi
+\temp}
+\def\Eifclear{}
+\def\ifclearfail{\begingroup\ignoresections\ifclearfailxxx}
+\long\def\ifclearfailxxx #1\end ifclear{\endgroup}
+
+% Some texinfo constructs that are trivial in tex
+
+\def\iftex{}
+\def\Eiftex{}
+\def\ifinfo{\begingroup\ignoresections\ifinfoxxx}
+\long\def\ifinfoxxx #1\end ifinfo{\endgroup}
+
+\long\def\menu #1\end menu{}
+\def\asis#1{#1}
+
+\def\node{\ENVcheck\parsearg\nodezzz}
+\def\nodezzz#1{\nodexxx [#1,]}
+\def\nodexxx[#1,#2]{\gdef\lastnode{#1}}
+\let\lastnode=\relax
+
+\def\donoderef{\ifx\lastnode\relax\else
+\expandafter\expandafter\expandafter\setref{\lastnode}\fi
+\let\lastnode=\relax}
+
+\def\unnumbnoderef{\ifx\lastnode\relax\else
+\expandafter\expandafter\expandafter\unnumbsetref{\lastnode}\fi
+\let\lastnode=\relax}
+
+\def\appendixnoderef{\ifx\lastnode\relax\else
+\expandafter\expandafter\expandafter\appendixsetref{\lastnode}\fi
+\let\lastnode=\relax}
+
+\let\refill=\relax
+
+% @setfilename is done at the beginning of every texinfo file.
+% So open here the files we need to have open while reading the input.
+% This makes it possible to make a .fmt file for texinfo.
+\def\setfilename{%
+ \readauxfile
+ \opencontents
+ \openindices
+ \fixbackslash % Turn off hack to swallow `\input texinfo'.
+ \comment % Ignore the actual filename.
+}
+
+\outer\def\bye{\pagealignmacro\tracingstats=1\ptexend}
+
+\def\inforef #1{\inforefzzz #1,,,,**}
+\def\inforefzzz #1,#2,#3,#4**{See Info file \file{\losespace#3{}}, node `\losespace#1{}'}
+\def\losespace #1{#1}
+
+\message{fonts,}
+
+% Font-change commands.
+
+%% Try out Computer Modern fonts at \magstephalf
+\font\tenrm=cmr10 scaled \magstephalf
+\font\tentt=cmtt10 scaled \magstephalf
+% Instead of cmb10, you many want to use cmbx10.
+% cmbx10 is a prettier font on its own, but cmb10
+% looks better when embedded in a line with cmr10.
+\font\tenbf=cmb10 scaled \magstephalf
+\font\tenit=cmti10 scaled \magstephalf
+\font\tensl=cmsl10 scaled \magstephalf
+\font\tensf=cmss10 scaled \magstephalf
+\def\li{\sf}
+\font\tensc=cmcsc10 scaled \magstephalf
+
+% Fonts for @defun, etc.
+\font\defbf=cmbx10 scaled \magstep1 %was 1314
+\let\deftt=\tentt
+\def\df{\let\tt=\deftt \defbf}
+
+% Font for title
+\font\titlerm = cmbx10 scaled \magstep5
+
+% Fonts for indices
+\font\indit=cmti9 \font\indrm=cmr9
+\font\indtt=cmtt9
+\def\indbf{\indrm} \def\indsl{\indit}
+\def\indexfonts{\let\it=\indit \let\sl=\indsl \let\bf=\indbf \let\rm=\indrm
+\let\tt=\indtt}
+
+% Fonts for headings
+\font\chaprm=cmbx10 scaled \magstep3
+\font\chapit=cmti10 scaled \magstep3
+\font\chapsl=cmsl10 scaled \magstep3
+\font\chaptt=cmtt10 scaled \magstep3
+\font\chapsf=cmss10 scaled \magstep3
+\let\chapbf=\chaprm
+
+\font\secrm=cmbx10 scaled \magstep2
+\font\secit=cmti10 scaled \magstep2
+\font\secsl=cmsl10 scaled \magstep2
+\font\sectt=cmtt10 scaled \magstep2
+\font\secsf=cmss10 scaled \magstep2
+\let\secbf=\secrm
+
+% \font\ssecrm=cmbx10 scaled \magstep1 % This size an fontlooked bad.
+% \font\ssecit=cmti10 scaled \magstep1 % The letters were too crowded.
+% \font\ssecsl=cmsl10 scaled \magstep1
+% \font\ssectt=cmtt10 scaled \magstep1
+% \font\ssecsf=cmss10 scaled \magstep1
+
+\font\ssecrm=cmb10 at 13pt % Note the use of cmb rather than cmbx.
+\font\ssecit=cmti10 at 13pt % Also, the size is a little larger than
+\font\ssecsl=cmsl10 at 13pt % being scaled magstep1.
+\font\ssectt=cmtt10 at 13pt
+\font\ssecsf=cmss10 at 13pt
+
+\let\ssecbf=\ssecrm
+
+\def\textfonts{\let\rm=\tenrm\let\it=\tenit\let\sl=\tensl\let\bf=\tenbf%
+\let\smallcaps=\tensc\let\sf=\tensf}
+\def\chapfonts{\let\rm=\chaprm\let\it=\chapit\let\sl=\chapsl\let\bf=\chapbf\let\tt=\chaptt\let\sf=\chapsf}
+\def\secfonts{\let\rm=\secrm\let\it=\secit\let\sl=\secsl\let\bf=\secbf\let\tt=\sectt\let\sf=\secsf}
+\def\subsecfonts{\let\rm=\ssecrm\let\it=\ssecit\let\sl=\ssecsl\let\bf=\ssecbf\let\tt=\ssectt\let\sf=\ssecsf}
+% Count depth in font-changes, for error checks
+\newcount\fontdepth \fontdepth=0
+
+% Font for table of contents.
+\font\truesecrm=cmr12
+
+%% Add scribe-like font environments, plus @l for inline lisp (usually sans
+%% serif) and @ii for TeX italic
+
+% \smartitalic{ARG} outputs arg in italics, followed by an italic correction
+% unless the following character is such as not to need one.
+\def\smartitalicx{\ifx\next,\else\ifx\next-\else\ifx\next.\else\/\fi\fi\fi}
+\def\smartitalic#1{{\sl #1}\futurelet\next\smartitalicx}
+
+\let\i=\smartitalic
+\let\var=\smartitalic
+\let\dfn=\smartitalic
+\let\emph=\smartitalic
+\let\cite=\smartitalic
+
+\def\b#1{{\bf #1}}
+\let\strong=\b
+
+\def\t#1{{\tt \rawbackslash \frenchspacing #1}\null}
+\let\ttfont = \t
+%\def\samp #1{`{\tt \rawbackslash \frenchspacing #1}'\null}
+\def\samp #1{`\tclose{#1}'\null}
+\def\key #1{{\tt \uppercase{#1}}\null}
+\def\ctrl #1{{\tt \rawbackslash \hat}#1}
+
+\let\file=\samp
+
+% @code is a modification of @t,
+% which makes spaces the same size as normal in the surrounding text.
+\newdimen\tclosesave
+\newdimen\tcloserm
+\def\tclose#1{{\rm \tcloserm=\fontdimen2\font \tt \tclosesave=\fontdimen2\font
+\fontdimen2\font=\tcloserm
+\def\ {{\fontdimen2\font=\tclosesave{} }}%
+ \rawbackslash \frenchspacing #1\fontdimen2\font=\tclosesave}\null}
+\let\code=\tclose
+%\let\exp=\tclose %Was temporary
+
+% @kbd is like @code, except that if the argument is just one @key command,
+% then @kbd has no effect.
+
+\def\xkey{\key}
+\def\kbdfoo#1#2#3*{\def\one{#1}\def\three{#3}\def\threex{??}%
+\ifx\one\xkey\ifx\threex\three \key{#2}
+\else\tclose{\look}\fi
+\else\tclose{\look}\fi}
+
+\def\kbd#1{\def\look{#1}\expandafter\kbdfoo\look??*}
+
+\def\l#1{{\li #1}\null} %
+
+\def\r#1{{\rm #1}} % roman font
+\def\sc#1{{\smallcaps #1}} % smallcaps font
+\def\ii#1{{\it #1}} % italic font
+
+\message{page headings,}
+
+\newskip\titlepagetopglue \titlepagetopglue = 1.5in
+\newskip\titlepagebottomglue \titlepagebottomglue = 2pc
+
+% First the title page. Must do @settitle before @titlepage.
+\font\titlerm = cmbx12 scaled \magstep2
+\def\titlefont#1{{\titlerm #1}}
+
+\newtoks\realeverypar
+\newif\ifseenauthor
+
+\def\titlepage{\begingroup \parindent=0pt \textfonts
+ \font\subtitlerm = cmr10 scaled \magstephalf
+ \def\subtitlefont{\subtitlerm \normalbaselineskip = 12pt \normalbaselines}%
+ %
+ \font\authorrm = cmbx12 scaled \magstep1
+ \def\authorfont{\authorrm \normalbaselineskip = 16pt \normalbaselines}%
+ %
+ % The first subtitle should have some space before it, but not the
+ % others. They all should be ragged left.
+% This code caused a bug, since two groups were started, but only
+% one was ended. Also, I can't see the point of this code.
+% \begingroup \realeverypar = {\leftskip = 2in plus 3em minus 1em
+% \parfillskip = 0pt}%
+% \everypar = {\vglue \baselineskip \the\realeverypar
+% \everypar={\the\realeverypar}}%
+ %
+ % Now you can print the title using @title.
+ \def\title{\parsearg\titlezzz}%
+ \def\titlezzz##1{\leftline{\titlefont{##1}
+ \vskip4pt \hrule height 4pt \vskip4pt}}%
+ \vglue\titlepagetopglue
+ %
+ % Now you can put text using @subtitle.
+ \def\subtitle{\parsearg\subtitlezzz}%
+ \def\subtitlezzz##1{{\subtitlefont \rightline{##1}}}%
+ %
+ % @author should come last, but may come many times.
+ \def\author{\parsearg\authorzzz}%
+ \def\authorzzz##1{\ifseenauthor\else\vskip 0pt plus 1filll\seenauthortrue\fi
+ {\authorfont \leftline{##1}}}%
+ %
+ % Most title ``pages'' are actually two pages long, with space
+ % at the top of the second. We don't want the ragged left on the second.
+ \let\oldpage = \page
+% \def\page{\vskip4pt \hrule height 2pt \vskip\titlepagebottomglue
+% \oldpage \endgroup\hrule height0pt\relax}%
+ \def\page{\oldpage \hbox{}}
+}
+
+\def\Etitlepage{\endgroup\page\HEADINGSon}
+
+%%% Set up page headings and footings.
+
+\let\thispage=\folio
+
+\newtoks \evenheadline % Token sequence for heading line of even pages
+\newtoks \oddheadline % Token sequence for heading line of odd pages
+\newtoks \evenfootline % Token sequence for footing line of even pages
+\newtoks \oddfootline % Token sequence for footing line of odd pages
+
+% Now make Tex use those variables
+\headline={{\textfonts\rm \ifodd\pageno \the\oddheadline \else \the\evenheadline \fi}}
+\footline={{\textfonts\rm \ifodd\pageno \the\oddfootline \else \the\evenfootline \fi}}
+
+% Commands to set those variables.
+% For example, this is what @headings on does
+% @evenheading @thistitle|@thispage|@thischapter
+% @oddheading @thischapter|@thispage|@thistitle
+% @evenfooting @thisfile||
+% @oddfooting ||@thisfile
+
+\def\evenheading{\parsearg\evenheadingxxx}
+\def\oddheading{\parsearg\oddheadingxxx}
+\def\everyheading{\parsearg\everyheadingxxx}
+
+\def\evenfooting{\parsearg\evenfootingxxx}
+\def\oddfooting{\parsearg\oddfootingxxx}
+\def\everyfooting{\parsearg\everyfootingxxx}
+
+{\catcode`\@=0 %
+
+\gdef\evenheadingxxx #1{\evenheadingyyy #1@|@|@|@|\finish}
+\gdef\evenheadingyyy #1@|#2@|#3@|#4\finish{%
+\global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
+
+\gdef\oddheadingxxx #1{\oddheadingyyy #1@|@|@|@|\finish}
+\gdef\oddheadingyyy #1@|#2@|#3@|#4\finish{%
+\global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
+
+\gdef\everyheadingxxx #1{\everyheadingyyy #1@|@|@|@|\finish}
+\gdef\everyheadingyyy #1@|#2@|#3@|#4\finish{%
+\global\evenheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}
+\global\oddheadline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
+
+\gdef\evenfootingxxx #1{\evenfootingyyy #1@|@|@|@|\finish}
+\gdef\evenfootingyyy #1@|#2@|#3@|#4\finish{%
+\global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
+
+\gdef\oddfootingxxx #1{\oddfootingyyy #1@|@|@|@|\finish}
+\gdef\oddfootingyyy #1@|#2@|#3@|#4\finish{%
+\global\oddfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
+
+\gdef\everyfootingxxx #1{\everyfootingyyy #1@|@|@|@|\finish}
+\gdef\everyfootingyyy #1@|#2@|#3@|#4\finish{%
+\global\evenfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}
+\global\oddfootline={\rlap{\centerline{#2}}\line{#1\hfil#3}}}
+%
+}% unbind the catcode of @.
+
+% @headings double turns headings on for double-sided printing.
+% @headings single turns headings on for single-sided printing.
+% @headings off turns them off.
+% @headings on same as @headings double, retained for compatibility.
+% By default, they are off.
+
+\def\headings #1 {\csname HEADINGS#1\endcsname}
+
+\def\HEADINGSoff{
+\global\evenheadline={\hfil} \global\evenfootline={\hfil}
+\global\oddheadline={\hfil} \global\oddfootline={\hfil}}
+\HEADINGSoff
+% When we turn headings on, set the page number to 1.
+% For double-sided printing, put current file name in lower left corner,
+% chapter name on inside top of right hand pages, document
+% title on inside top of left hand pages, and page numbers on outside top
+% edge of all pages.
+\def\HEADINGSdouble{
+%\pagealignmacro
+\global\pageno=1
+\global\evenfootline={\hfil}
+\global\oddfootline={\hfil}
+\global\evenheadline={\line{\folio\hfil\thistitle}}
+\global\oddheadline={\line{\thischapter\hfil\folio}}
+}
+% For single-sided printing, chapter title goes across top left of page,
+% page number on top right.
+\def\HEADINGSsingle{
+%\pagealignmacro
+\global\pageno=1
+\global\evenfootline={\hfil}
+\global\oddfootline={\hfil}
+\global\evenheadline={\line{\thischapter\hfil\folio}}
+\global\oddheadline={\line{\thischapter\hfil\folio}}
+}
+\def\HEADINGSon{\HEADINGSdouble}
+
+% Subroutines used in generating headings
+% Produces Day Month Year style of output.
+\def\today{\number\day\space
+\ifcase\month\or
+January\or February\or March\or April\or May\or June\or
+July\or August\or September\or October\or November\or December\fi
+\space\number\year}
+
+% Use this if you want the Month Day, Year style of output.
+%\def\today{\ifcase\month\or
+%January\or February\or March\or April\or May\or June\or
+%July\or August\or September\or October\or November\or December\fi
+%\space\number\day, \number\year}
+
+% @settitle line... specifies the title of the document, for headings
+% It generates no output of its own
+
+\def\thistitle{No Title}
+\def\settitle{\parsearg\settitlezzz}
+\def\settitlezzz #1{\gdef\thistitle{#1}}
+
+\message{tables,}
+
+% Tables -- @table, @ftable, @item(x), @kitem(x), @xitem(x).
+
+% default indentation of table text
+\newdimen\tableindent \tableindent=.8in
+% default indentation of @itemize and @enumerate text
+\newdimen\itemindent \itemindent=.3in
+% margin between end of table item and start of table text.
+\newdimen\itemmargin \itemmargin=.1in
+
+% used internally for \itemindent minus \itemmargin
+\newdimen\itemmax
+
+% Note @table and @ftable define @item, @itemx, etc., with these defs.
+% They also define \itemindex
+% to index the item name in whatever manner is desired (perhaps none).
+
+\def\internalBitem{\smallbreak \parsearg\itemzzz}
+\def\internalBitemx{\par \parsearg\itemzzz}
+
+\def\internalBxitem "#1"{\def\xitemsubtopix{#1} \smallbreak \parsearg\xitemzzz}
+\def\internalBxitemx "#1"{\def\xitemsubtopix{#1} \par \parsearg\xitemzzz}
+
+\def\internalBkitem{\smallbreak \parsearg\kitemzzz}
+\def\internalBkitemx{\par \parsearg\kitemzzz}
+
+\def\kitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \lastfunction}}\itemzzz {#1}}
+
+\def\xitemzzz #1{\dosubind {kw}{\code{#1}}{for {\bf \xitemsubtopic}}\itemzzz {#1}}
+
+\def\itemzzz #1{\begingroup %
+\advance \hsize by -\rightskip %
+\advance \hsize by -\leftskip %
+\setbox0=\hbox{\itemfont{#1}}%
+\itemindex{#1}%
+\parskip=0in %
+\noindent %
+\ifdim \wd0>\itemmax %
+\vadjust{\penalty 10000}%
+\hbox to \hsize{\hskip -\tableindent\box0\hss}\ %
+\else %
+\hbox to 0pt{\hskip -\tableindent\box0\hss}%
+\fi %
+\endgroup %
+}
+
+\def\item{\errmessage{@item while not in a table}}
+\def\itemx{\errmessage{@itemx while not in a table}}
+\def\kitem{\errmessage{@kitem while not in a table}}
+\def\kitemx{\errmessage{@kitemx while not in a table}}
+\def\xitem{\errmessage{@xitem while not in a table}}
+\def\xitemx{\errmessage{@xitemx while not in a table}}
+
+%% Contains a kludge to get @end[description] to work
+\def\description{\tablez{\dontindex}{1}{}{}{}{}}
+
+\def\table{\begingroup\inENV\obeylines\obeyspaces\tablex}
+{\obeylines\obeyspaces%
+\gdef\tablex #1^^M{%
+\tabley\dontindex#1 \endtabley}}
+
+\def\ftable{\begingroup\inENV\obeylines\obeyspaces\ftablex}
+{\obeylines\obeyspaces%
+\gdef\ftablex #1^^M{%
+\tabley\fnitemindex#1 \endtabley}}
+
+\def\dontindex #1{}
+\def\fnitemindex #1{\doind {fn}{\code{#1}}}%
+
+{\obeyspaces %
+\gdef\tabley#1#2 #3 #4 #5 #6 #7\endtabley{\endgroup%
+\tablez{#1}{#2}{#3}{#4}{#5}{#6}}}
+
+\def\tablez #1#2#3#4#5#6{%
+\aboveenvbreak %
+\begingroup %
+\def\Edescription{\Etable}% Neccessary kludge.
+\let\itemindex=#1%
+\ifnum 0#3>0 \advance \leftskip by #3\mil \fi %
+\ifnum 0#4>0 \tableindent=#4\mil \fi %
+\ifnum 0#5>0 \advance \rightskip by #5\mil \fi %
+\def\itemfont{#2}%
+\itemmax=\tableindent %
+\advance \itemmax by -\itemmargin %
+\advance \leftskip by \tableindent %
+\parindent = 0pt
+\parskip = \smallskipamount
+\ifdim \parskip=0pt \parskip=2pt \fi%
+\def\Etable{\endgraf\endgroup\afterenvbreak}%
+\let\item = \internalBitem %
+\let\itemx = \internalBitemx %
+\let\kitem = \internalBkitem %
+\let\kitemx = \internalBkitemx %
+\let\xitem = \internalBxitem %
+\let\xitemx = \internalBxitemx %
+}
+
+% This is the counter used by @enumerate, which is really @itemize
+
+\newcount \itemno
+
+\def\itemize{\parsearg\itemizezzz}
+
+\def\itemizezzz #1{\itemizey {#1}{\Eitemize}}
+
+\def\itemizey #1#2{%
+\aboveenvbreak %
+\begingroup %
+\itemno = 0 %
+\itemmax=\itemindent %
+\advance \itemmax by -\itemmargin %
+\advance \leftskip by \itemindent %
+\parindent = 0pt
+\parskip = \smallskipamount
+\ifdim \parskip=0pt \parskip=2pt \fi%
+\def#2{\endgraf\endgroup\afterenvbreak}%
+\def\itemcontents{#1}%
+\let\item=\itemizeitem}
+
+\def\bullet{$\ptexbullet$}
+\def\minus{$-$}
+
+% Set sfcode to normal for the chars that usually have another value.
+% These are `.?!:;,'
+\def\frenchspacing{\sfcode46=1000 \sfcode63=1000 \sfcode33=1000
+ \sfcode58=1000 \sfcode59=1000 \sfcode44=1000 }
+
+\def\enumerate{\itemizey{\the\itemno.}\Eenumerate\flushcr}
+
+% Definition of @item while inside @itemize.
+
+\def\itemizeitem{%
+\advance\itemno by 1
+{\let\par=\endgraf \smallbreak}%
+\ifhmode \errmessage{\in hmode at itemizeitem}\fi
+{\parskip=0in \hskip 0pt
+\hbox to 0pt{\hss \itemcontents\hskip \itemmargin}%
+\vadjust{\penalty 300}}%
+\flushcr}
+
+\message{indexing,}
+% Index generation facilities
+
+% Define \newwrite to be identical to plain tex's \newwrite
+% except not \outer, so it can be used within \newindex.
+{\catcode`\@=11
+\gdef\newwrite{\alloc@7\write\chardef\sixt@@n}}
+
+% \newindex {foo} defines an index named foo.
+% It automatically defines \fooindex such that
+% \fooindex ...rest of line... puts an entry in the index foo.
+% It also defines \fooindfile to be the number of the output channel for
+% the file that accumulates this index. The file's extension is foo.
+% The name of an index should be no more than 2 characters long
+% for the sake of vms.
+
+\def\newindex #1{
+\expandafter\newwrite \csname#1indfile\endcsname% Define number for output file
+\openout \csname#1indfile\endcsname \jobname.#1 % Open the file
+\expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex
+\noexpand\doindex {#1}}
+}
+
+% @defindex foo == \newindex{foo}
+
+\def\defindex{\parsearg\newindex}
+
+% Define @defcodeindex, like @defindex except put all entries in @code.
+
+\def\newcodeindex #1{
+\expandafter\newwrite \csname#1indfile\endcsname% Define number for output file
+\openout \csname#1indfile\endcsname \jobname.#1 % Open the file
+\expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex
+\noexpand\docodeindex {#1}}
+}
+
+\def\defcodeindex{\parsearg\newcodeindex}
+
+% @synindex foo bar makes index foo feed into index bar.
+% Do this instead of @defindex foo if you don't want it as a separate index.
+\def\synindex #1 #2 {%
+\expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex
+\noexpand\doindex {#2}}%
+}
+
+% @syncodeindex foo bar similar, but put all entries made for index foo
+% inside @code.
+\def\syncodeindex #1 #2 {%
+\expandafter\xdef\csname#1index\endcsname{% % Define \xxxindex
+\noexpand\docodeindex {#2}}%
+}
+
+% Define \doindex, the driver for all \fooindex macros.
+% Argument #1 is generated by the calling \fooindex macro,
+% and it is "foo", the name of the index.
+
+% \doindex just uses \parsearg; it calls \doind for the actual work.
+% This is because \doind is more useful to call from other macros.
+
+% There is also \dosubind {index}{topic}{subtopic}
+% which makes an entry in a two-level index such as the operation index.
+
+\def\doindex#1{\edef\indexname{#1}\parsearg\singleindexer}
+\def\singleindexer #1{\doind{\indexname}{#1}}
+
+% like the previous two, but they put @code around the argument.
+\def\docodeindex#1{\edef\indexname{#1}\parsearg\singlecodeindexer}
+\def\singlecodeindexer #1{\doind{\indexname}{\code{#1}}}
+
+\def\indexdummies{%
+\def\bf{\realbackslash bf }%
+\def\rm{\realbackslash rm }%
+\def\sl{\realbackslash sl }%
+\def\dots{\realbackslash dots }%
+\def\copyright{\realbackslash copyright }%
+\def\tclose##1{\realbackslash tclose {##1}}%
+\def\code##1{\realbackslash code {##1}}%
+\def\samp##1{\realbackslash samp {##1}}%
+\def\r##1{\realbackslash r {##1}}%
+\def\i##1{\realbackslash i {##1}}%
+\def\b##1{\realbackslash b {##1}}%
+\def\cite##1{\realbackslash cite {##1}}%
+\def\key##1{\realbackslash key {##1}}%
+\def\file##1{\realbackslash file {##1}}%
+\def\var##1{\realbackslash var {##1}}%
+\def\kbd##1{\realbackslash kbd {##1}}%
+}
+
+% \indexnofonts no-ops all font-change commands.
+% This is used when outputting the strings to sort the index by.
+\def\indexdummyfont#1{#1}
+\def\indexnofonts{%
+\let\r=\indexdummyfont
+\let\i=\indexdummyfont
+\let\b=\indexdummyfont
+\let\emph=\indexdummyfont
+\let\strong=\indexdummyfont
+\let\cite=\indexdummyfont
+\let\sc=\indexdummyfont
+%Don't no-op \tt, since it isn't a user-level command
+% and is used in the definitions of the actuve chars like <, >, |...
+%\let\tt=\indexdummyfont
+\let\tclose=\indexdummyfont
+\let\code=\indexdummyfont
+\let\file=\indexdummyfont
+\let\samp=\indexdummyfont
+\let\kbd=\indexdummyfont
+\let\key=\indexdummyfont
+\let\var=\indexdummyfont
+}
+
+% To define \realbackslash, we must make \ not be an escape.
+% We must first make another character (@) an escape
+% so we do not become unable to do a definition.
+
+{\catcode`\@=0 \catcode`\\=\other
+@gdef@realbackslash{\}}
+
+\let\indexbackslash=0 %overridden during \printindex.
+
+\def\doind #1#2{%
+{\indexdummies % Must do this here, since \bf, etc expand at this stage
+\count10=\lastpenalty %
+\escapechar=`\\%
+{\let\folio=0% Expand all macros now EXCEPT \folio
+\def\rawbackslashxx{\indexbackslash}% \indexbackslash isn't defined now
+% so it will be output as is; and it will print as backslash in the indx.
+%
+% Now process the index-string once, with all font commands turned off,
+% to get the string to sort the index by.
+{\indexnofonts
+\xdef\temp1{#2}%
+}%
+% Now produce the complete index entry. We process the index-string again,
+% this time with font commands expanded, to get what to print in the index.
+\edef\temp{%
+\write \csname#1indfile\endcsname{%
+\realbackslash entry {\temp1}{\folio}{#2}}}%
+\temp }%
+\penalty\count10}}
+
+\def\dosubind #1#2#3{%
+{\indexdummies % Must do this here, since \bf, etc expand at this stage
+\count10=\lastpenalty %
+\escapechar=`\\%
+{\let\folio=0%
+\def\rawbackslashxx{\indexbackslash}%
+%
+% Now process the index-string once, with all font commands turned off,
+% to get the string to sort the index by.
+{\indexnofonts
+\xdef\temp1{#2 #3}%
+}%
+% Now produce the complete index entry. We process the index-string again,
+% this time with font commands expanded, to get what to print in the index.
+\edef\temp{%
+\write \csname#1indfile\endcsname{%
+\realbackslash entry {\temp1}{\folio}{#2}{#3}}}%
+\temp }%
+\penalty\count10}}
+
+% The index entry written in the file actually looks like
+% \entry {sortstring}{page}{topic}
+% or
+% \entry {sortstring}{page}{topic}{subtopic}
+% The texindex program reads in these files and writes files
+% containing these kinds of lines:
+% \initial {c}
+% before the first topic whose initial is c
+% \entry {topic}{pagelist}
+% for a topic that is used without subtopics
+% \primary {topic}
+% for the beginning of a topic that is used with subtopics
+% \secondary {subtopic}{pagelist}
+% for each subtopic.
+
+% Define the user-accessible indexing commands
+% @findex, @vindex, @kindex, @cindex.
+
+\def\findex {\fnindex}
+\def\kindex {\kyindex}
+\def\cindex {\cpindex}
+\def\vindex {\vrindex}
+\def\tindex {\tpindex}
+\def\pindex {\pgindex}
+
+\def\cindexsub {\begingroup\obeylines\cindexsub}
+{\obeylines %
+\gdef\cindexsub "#1" #2^^M{\endgroup %
+\dosubind{cp}{#2}{#1}}}
+
+% Define the macros used in formatting output of the sorted index material.
+
+% This is what you call to cause a particular index to get printed.
+% Write
+% @unnumbered Function Index
+% @printindex fn
+
+\def\printindex{\parsearg\doprintindex}
+
+\def\doprintindex#1{\tex %
+\catcode`\%=\other\catcode`\&=\other\catcode`\#=\other
+\catcode`\$=\other\catcode`\_=\other
+\catcode`\~=\other
+% The following don't help, since the chars were translated
+% when the raw index was written, and their fonts were discarded
+% due to \indexnofonts.
+%\catcode`\"=\active
+%\catcode`\^=\active
+%\catcode`\_=\active
+%\catcode`\|=\active
+%\catcode`\<=\active
+%\catcode`\>=\active
+\def\indexbackslash{\rawbackslashxx}
+\indexfonts\rm \tolerance=9500 \advance\baselineskip -1pt
+\begindoublecolumns
+\openin 1 \jobname.#1s
+\ifeof 1 \else \closein 1 \input \jobname.#1s
+\fi
+\enddoublecolumns
+\Etex}
+
+% These macros are used by the sorted index file itself.
+% Change them to control the appearance of the index.
+
+% Same as \bigskipamount except no shrink.
+% \balancecolumns gets confused if there is any shrink.
+\newskip\initialskipamount \initialskipamount 12pt plus4pt
+
+\outer\def\initial #1{%
+{\let\tentt=\sectt \let\sf=\sectt
+\ifdim\lastskip<\initialskipamount
+\removelastskip \penalty-200 \vskip \initialskipamount\fi
+\line{\secbf#1\hfill}\kern 2pt\penalty10000}}
+
+\outer\def\entry #1#2{
+{\parfillskip=0in \parskip=0in \parindent=0in
+\hangindent=1in \hangafter=1%
+\noindent\hbox{#1}\dotfill #2\par
+}}
+
+\def\primary #1{\line{#1\hfil}}
+
+\newskip\secondaryindent \secondaryindent=0.5cm
+
+\def\secondary #1#2{
+{\parfillskip=0in \parskip=0in
+\hangindent =1in \hangafter=1
+\noindent\hskip\secondaryindent\hbox{#1}\dotfill #2\par
+}}
+
+%% Define two-column mode, which is used in indexes.
+%% Adapted from the TeXBook, page 416
+\catcode `\@=11
+
+\newbox\partialpage
+
+\newdimen\doublecolumnhsize \doublecolumnhsize = 3.11in
+\newdimen\doublecolumnvsize \doublecolumnvsize = 19.1in
+\newdimen\availdimen@
+
+\def\begindoublecolumns{\begingroup
+ \output={\global\setbox\partialpage=\vbox{\unvbox255\kern -\topskip \kern \baselineskip}}\eject
+ \output={\doublecolumnout} \hsize=\doublecolumnhsize \vsize=\doublecolumnvsize}
+\def\enddoublecolumns{\output={\balancecolumns}\eject
+ \endgroup \pagegoal=\vsize}
+
+\def\doublecolumnout{\splittopskip=\topskip \splitmaxdepth=\maxdepth
+ \dimen@=\pageheight \advance\dimen@ by-\ht\partialpage
+ \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@
+ \onepageout\pagesofar \unvbox255 \penalty\outputpenalty}
+\def\pagesofar{\unvbox\partialpage %
+ \hsize=\doublecolumnhsize % have to restore this since output routine
+% changes it to set cropmarks (P. A. MacKay, 12 Nov. 1986)
+ \wd0=\hsize \wd2=\hsize \hbox to\pagewidth{\box0\hfil\box2}}
+\def\balancecolumns{%
+% Unset the glue.
+ \setbox255=\vbox{\unvbox255}
+ \dimen@=\ht255
+ \advance\dimen@ by\topskip \advance\dimen@ by-\baselineskip
+ \divide\dimen@ by2
+ \availdimen@=\pageheight \advance\availdimen@ by-\ht\partialpage
+% If the remaining data is too big for one page,
+% output one page normally, then work with what remains.
+ \ifdim \dimen@>\availdimen@
+ {
+ \splittopskip=\topskip \splitmaxdepth=\maxdepth
+ \dimen@=\pageheight \advance\dimen@ by-\ht\partialpage
+ \setbox0=\vsplit255 to\dimen@ \setbox2=\vsplit255 to\dimen@
+ \onepageout\pagesofar
+ }
+% Recompute size of what remains, in case we just output some of it.
+ \dimen@=\ht255
+ \advance\dimen@ by\topskip \advance\dimen@ by-\baselineskip
+ \divide\dimen@ by2
+ \fi
+ \setbox0=\vbox{\unvbox255}
+ \splittopskip=\topskip
+ {\vbadness=10000 \loop \global\setbox3=\copy0
+ \global\setbox1=\vsplit3 to\dimen@
+ \ifdim\ht3>\dimen@ \global\advance\dimen@ by1pt \repeat}
+ \setbox0=\vbox to\dimen@{\unvbox1} \setbox2=\vbox to\dimen@{\unvbox3}
+ \pagesofar}
+
+\catcode `\@=\other
+\message{sectioning,}
+% Define chapters, sections, etc.
+
+\newcount \chapno
+\newcount \secno
+\newcount \subsecno
+\newcount \subsubsecno
+
+% This counter is funny since it counts through charcodes of letters A, B, ...
+\newcount \appendixno \appendixno = `\@
+\def\appendixletter{\char\the\appendixno}
+
+\newwrite \contentsfile
+% This is called from \setfilename.
+\def\opencontents{\openout \contentsfile = \jobname.toc}
+
+% Each @chapter defines this as the name of the chapter.
+% page headings and footings can use it. @section does likewise
+
+\def\thischapter{} \def\thissection{}
+\def\seccheck#1{\if \pageno<0 %
+\errmessage{@#1 not allowed after generating table of contents}\fi
+%
+}
+
+\def\chapternofonts{%
+\let\rawbackslash=\relax%
+\let\frenchspacing=\relax%
+\def\char{\realbackslash char}
+\def\tclose##1{\realbackslash tclose {##1}}
+\def\code##1{\realbackslash code {##1}}
+\def\samp##1{\realbackslash samp {##1}}
+\def\r##1{\realbackslash r {##1}}
+\def\i##1{\realbackslash i {##1}}
+\def\b##1{\realbackslash b {##1}}
+\def\cite##1{\realbackslash cite {##1}}
+\def\key##1{\realbackslash key {##1}}
+\def\file##1{\realbackslash file {##1}}
+\def\var##1{\realbackslash var {##1}}
+\def\kbd##1{\realbackslash kbd {##1}}
+}
+
+\outer\def\chapter{\parsearg\chapterzzz}
+\def\chapterzzz #1{\seccheck{chapter}%
+\secno=0 \subsecno=0 \subsubsecno=0 \global\advance \chapno by 1 \message{Chapter \the\chapno}%
+\chapmacro {#1}{\the\chapno}%
+\gdef\thissection{#1}\gdef\thischapter{#1}%
+{\chapternofonts%
+\edef\temp{{\realbackslash chapentry {#1}{\the\chapno}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\donoderef %
+}}
+
+\outer\def\appendix{\parsearg\appendixzzz}
+\def\appendixzzz #1{\seccheck{appendix}%
+\secno=0 \subsecno=0 \subsubsecno=0 \global\advance \appendixno by 1 \message{Appendix \appendixletter}%
+\chapmacro {#1}{Appendix \appendixletter}%
+\gdef\thischapter{#1}\gdef\thissection{#1}%
+{\chapternofonts%
+\edef\temp{{\realbackslash chapentry {#1}{Appendix \appendixletter}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\appendixnoderef %
+}}
+
+\outer\def\unnumbered{\parsearg\unnumberedzzz}
+\def\unnumberedzzz #1{\seccheck{unnumbered}%
+\secno=0 \subsecno=0 \subsubsecno=0 \message{(#1)}
+\unnumbchapmacro {#1}%
+\gdef\thischapter{#1}\gdef\thissection{#1}%
+{\chapternofonts%
+\edef\temp{{\realbackslash unnumbchapentry {#1}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\unnumbnoderef %
+}}
+
+\outer\def\section{\parsearg\sectionzzz}
+\def\sectionzzz #1{\seccheck{section}%
+\subsecno=0 \subsubsecno=0 \global\advance \secno by 1 %
+\gdef\thissection{#1}\secheading {#1}{\the\chapno}{\the\secno}%
+{\chapternofonts%
+\edef\temp{{\realbackslash secentry %
+{#1}{\the\chapno}{\the\secno}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\donoderef %
+\penalty 10000 %
+}}
+
+\outer\def\appendixsection{\parsearg\appendixsectionzzz}
+\outer\def\appendixsec{\parsearg\appendixsectionzzz}
+\def\appendixsectionzzz #1{\seccheck{appendixsection}%
+\subsecno=0 \subsubsecno=0 \global\advance \secno by 1 %
+\gdef\thissection{#1}\secheading {#1}{\appendixletter}{\the\secno}%
+{\chapternofonts%
+\edef\temp{{\realbackslash secentry %
+{#1}{\appendixletter}{\the\secno}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\appendixnoderef %
+\penalty 10000 %
+}}
+
+\outer\def\unnumberedsec{\parsearg\unnumberedseczzz}
+\def\unnumberedseczzz #1{\seccheck{unnumberedsec}%
+\plainsecheading {#1}\gdef\thissection{#1}%
+{\chapternofonts%
+\edef\temp{{\realbackslash unnumbsecentry{#1}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\unnumbnoderef %
+\penalty 10000 %
+}}
+
+\outer\def\subsection{\parsearg\subsectionzzz}
+\def\subsectionzzz #1{\seccheck{subsection}%
+\gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 %
+\subsecheading {#1}{\the\chapno}{\the\secno}{\the\subsecno}%
+{\chapternofonts%
+\edef\temp{{\realbackslash subsecentry %
+{#1}{\the\chapno}{\the\secno}{\the\subsecno}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\donoderef %
+\penalty 10000 %
+}}
+
+\outer\def\appendixsubsec{\parsearg\appendixsubseczzz}
+\def\appendixsubseczzz #1{\seccheck{appendixsubsec}%
+\gdef\thissection{#1}\subsubsecno=0 \global\advance \subsecno by 1 %
+\subsecheading {#1}{\appendixletter}{\the\secno}{\the\subsecno}%
+{\chapternofonts%
+\edef\temp{{\realbackslash subsecentry %
+{#1}{\appendixletter}{\the\secno}{\the\subsecno}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\appendixnoderef %
+\penalty 10000 %
+}}
+
+\outer\def\unnumberedsubsec{\parsearg\unnumberedsubseczzz}
+\def\unnumberedsubseczzz #1{\seccheck{unnumberedsubsec}%
+\plainsecheading {#1}\gdef\thissection{#1}%
+{\chapternofonts%
+\edef\temp{{\realbackslash unnumbsubsecentry{#1}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\unnumbnoderef %
+\penalty 10000 %
+}}
+
+\outer\def\subsubsection{\parsearg\subsubsectionzzz}
+\def\subsubsectionzzz #1{\seccheck{subsubsection}%
+\gdef\thissection{#1}\global\advance \subsubsecno by 1 %
+\subsubsecheading {#1}{\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}%
+{\chapternofonts%
+\edef\temp{{\realbackslash subsubsecentry %
+{#1}{\the\chapno}{\the\secno}{\the\subsecno}{\the\subsubsecno}{\noexpand\folio}}}%\
+\escapechar=`\\%
+\write \contentsfile \temp %
+\donoderef %
+\penalty 10000 %
+}}
+
+\outer\def\appendixsubsubsec{\parsearg\appendixsubsubseczzz}
+\def\appendixsubsubseczzz #1{\seccheck{appendixsubsubsec}%
+\gdef\thissection{#1}\global\advance \subsubsecno by 1 %
+\subsubsecheading {#1}{\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}%
+{\chapternofonts%
+\edef\temp{{\realbackslash subsubsecentry{#1}%
+{\appendixletter}{\the\secno}{\the\subsecno}{\the\subsubsecno}{\noexpand\folio}}}%\
+\escapechar=`\\%
+\write \contentsfile \temp %
+\appendixnoderef %
+\penalty 10000 %
+}}
+
+\outer\def\unnumberedsubsubsec{\parsearg\unnumberedsubsubseczzz}
+\def\unnumberedsubsubseczzz #1{\seccheck{unnumberedsubsubsec}%
+\plainsecheading {#1}\gdef\thissection{#1}%
+{\chapternofonts%
+\edef\temp{{\realbackslash unnumbsubsubsecentry{#1}{\noexpand\folio}}}%
+\escapechar=`\\%
+\write \contentsfile \temp %
+\unnumbnoderef %
+\penalty 10000 %
+}}
+
+% These are variants which are not "outer", so they can appear in @ifinfo.
+\def\infounnumbered{\parsearg\unnumberedzzz}
+\def\infounnumberedsec{\parsearg\unnumberedseczzz}
+\def\infounnumberedsubsec{\parsearg\unnumberedsubseczzz}
+\def\infounnumberedsubsubsec{\parsearg\unnumberedsubsubseczzz}
+
+\def\infoappendix{\parsearg\appendixzzz}
+\def\infoappendixsec{\parsearg\appendixseczzz}
+\def\infoappendixsubsec{\parsearg\appendixsubseczzz}
+\def\infoappendixsubsubsec{\parsearg\appendixsubsubseczzz}
+
+\def\infochapter{\parsearg\chapterzzz}
+\def\infosection{\parsearg\sectionzzz}
+\def\infosubsection{\parsearg\subsectionzzz}
+\def\infosubsubsection{\parsearg\subsubsectionzzz}
+
+% Define @majorheading, @heading and @subheading
+
+\def\majorheading #1{%
+{\advance\chapheadingskip by 10pt \chapbreak }%
+{\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 200}
+
+\def\chapheading #1{\chapbreak %
+{\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 200}
+
+\def\heading{\parsearg\secheadingi}
+
+% These macros generate a chapter, section, etc. heading only
+% (including whitespace, linebreaking, etc. around it),
+% given all the information in convenient, parsed form.
+
+%%% Args are the skip and penalty (usually negative)
+\def\dobreak#1#2{\par\ifdim\lastskip<#1\removelastskip\penalty#2\vskip#1\fi}
+
+\def\setchapterstyle #1 {\csname CHAPF#1\endcsname}
+
+%%% Define plain chapter starts, and page on/off switching for it
+% Parameter controlling skip before chapter headings (if needed)
+
+\newskip \chapheadingskip \chapheadingskip = 30pt plus 8pt minus 4pt
+
+\def\chapbreak{\dobreak \chapheadingskip {-4000}}
+\def\chappager{\par\vfill\supereject}
+\def\chapoddpage{\chappager \ifodd\pageno \else \hbox to 0pt{} \chappager\fi}
+
+\def\setchapternewpage #1 {\csname CHAPPAG#1\endcsname}
+
+\def\CHAPPAGoff{
+\global\let\pchapsepmacro=\chapbreak
+\global\let\pagealignmacro=\chappager}
+
+\def\CHAPPAGon{
+\global\let\pchapsepmacro=\chappager
+\global\let\pagealignmacro=\chappager
+\global\def\HEADINGSon{\HEADINGSsingle}}
+
+\def\CHAPPAGodd{
+\global\let\pchapsepmacro=\chapoddpage
+\global\let\pagealignmacro=\chapoddpage
+\global\def\HEADINGSon{\HEADINGSdouble}}
+
+\CHAPPAGon
+
+\def\CHAPFplain{
+\global\let\chapmacro=\chfplain
+\global\let\unnumbchapmacro=\unnchfplain}
+
+\def\chfplain #1#2{%
+\pchapsepmacro %
+{\chapfonts \line{\rm #2.\enspace #1\hfill}}\bigskip \par\penalty 5000 %
+}
+
+\def\unnchfplain #1{%
+\pchapsepmacro %
+{\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 10000 %
+}
+\CHAPFplain % The default
+
+\def\unnchfopen #1{%
+\chapoddpage {\chapfonts \line{\rm #1\hfill}}\bigskip \par\penalty 10000 %
+}
+
+\def\chfopen #1#2{\chapoddpage {\chapfonts
+\vbox to 3in{\vfil \hbox to\hsize{\hfil #2} \hbox to\hsize{\hfil #1} \vfil}}%
+\par\penalty 5000 %
+}
+
+\def\CHAPFopen{
+\global\let\chapmacro=\chfopen
+\global\let\unnumbchapmacro=\unnchfopen}
+
+% Parameter controlling skip before section headings.
+
+\newskip \subsecheadingskip \subsecheadingskip = 17pt plus 8pt minus 4pt
+\def\subsecheadingbreak{\dobreak \subsecheadingskip {-500}}
+
+\newskip \secheadingskip \secheadingskip = 21pt plus 8pt minus 4pt
+\def\secheadingbreak{\dobreak \secheadingskip {-1000}}
+
+
+% Section fonts are the base font at magstep2, which produces
+% a size a bit more than 14 points in the default situation.
+
+\def\secheading #1#2#3{\secheadingi {#2.#3\enspace #1}}
+\def\plainsecheading #1{\secheadingi {#1}}
+\def\secheadingi #1{{\advance \secheadingskip by \parskip %
+\secheadingbreak}%
+{\secfonts \line{\rm #1\hfill}}%
+\ifdim \parskip<10pt \kern 10pt\kern -\parskip\fi \penalty 10000 }
+
+
+% Subsection fonts are the base font at magstep1,
+% which produces a size of 12 points.
+
+\def\subsecheading #1#2#3#4{{\advance \subsecheadingskip by \parskip %
+\subsecheadingbreak}%
+{\subsecfonts \line{\rm#2.#3.#4\enspace #1\hfill}}%
+\ifdim \parskip<10pt \kern 10pt\kern -\parskip\fi \penalty 10000 }
+
+\def\subsubsecfonts{\subsecfonts} % Maybe this should change:
+ % Perhaps make sssec fonts scaled
+ % magstep half
+\def\subsubsecheading #1#2#3#4#5{{\advance \subsecheadingskip by \parskip %
+\subsecheadingbreak}%
+{\subsubsecfonts \line{\rm#2.#3.#4.#5\enspace #1\hfill}}%
+\ifdim \parskip<10pt \kern 10pt\kern -\parskip\fi \penalty 10000}
+
+
+\message{toc printing,}
+
+% Finish up the main text and prepare to read what we've written
+% to \contentsfile.
+
+\def\startcontents#1{%
+ \ifnum \pageno>0
+ \pagealignmacro
+ \immediate\closeout \contentsfile
+ \pageno = -1 % Request roman numbered pages.
+ \fi
+ \unnumbchapmacro{#1}\def\thischapter{#1}%
+ \begingroup % Set up to handle contents files properly.
+ \catcode`\\=0 \catcode`\{=1 \catcode`\}=2 \catcode`\@=11
+ \raggedbottom % Worry more about breakpoints than the bottom.
+ \advance\hsize by -1in % Don't use the full line length.
+}
+
+
+% Normal (long) toc.
+\outer\def\contents{%
+ \startcontents{Table of Contents}%
+ \input \jobname.toc
+ \endgroup
+ \vfill \eject
+}
+
+% And just the chapters.
+\outer\def\summarycontents{%
+ \startcontents{Short Contents}%
+ %
+ \let\chapentry = \shortchapentry
+ \let\unnumbchapentry = \shortunnumberedentry
+ % We want a true roman here for the page numbers.
+ \secfonts \let\rm = \truesecrm \rm
+ \advance\baselineskip by 1pt % Open it up a little.
+ \def\secentry ##1##2##3##4{}
+ \def\unnumbsecentry ##1##2{}
+ \def\subsecentry ##1##2##3##4##5{}
+ \def\unnumbsubsecentry ##1##2{}
+ \def\subsubsecentry ##1##2##3##4##5##6{}
+ \def\unnumbsubsubsecentry ##1##2{}
+ \input \jobname.toc
+ \endgroup
+ \vfill \eject
+}
+\let\shortcontents = \summarycontents
+
+% These macros generate individual entries in the table of contents.
+% The first argument is the chapter or section name.
+% The last argument is the page number.
+% The arguments in between are the chapter number, section number, ...
+
+% Chapter-level things, for both the long and short contents.
+\def\chapentry#1#2#3{\dochapentry{#2\labelspace#1}{#3}}
+\def\shortchapentry#1#2#3{%
+ \line{{#2\labelspace #1}\dotfill\doshortpageno{#3}}%
+}
+
+\def\unnumbchapentry#1#2{\dochapentry{#1}{#2}}
+\def\shortunnumberedentry#1#2{%
+ \line{#1\dotfill\doshortpageno{#2}}%
+}
+
+% Sections.
+\def\secentry#1#2#3#4{\dosecentry{#2.#3\labelspace#1}{#4}}
+\def\unnumbsecentry#1#2{\dosecentry{#1}{#2}}
+
+% Subsections.
+\def\subsecentry#1#2#3#4#5{\dosubsecentry{#2.#3.#4\labelspace#1}{#5}}
+\def\unnumbsubsecentry#1#2{\dosubsecentry{#1}{#2}}
+
+% And subsubsections.
+\def\subsubsecentry#1#2#3#4#5#6{\dosubsubsecentry{#2.#3.#4.#5\labelspace#1}{#6}}
+\def\unnumbsubsecentry#1#2{\dosubsubsecentry{#1}{#2}}
+
+
+% This parameter controls the indentation of the various levels.
+\newdimen\tocindent \tocindent = 3pc
+
+% Now for the actual typesetting. In all these, #1 is the text and #2 is the
+% page number.
+%
+% If the toc has to be broken over pages, we would want to be at chapters
+% if at all possible; hence the \penalty.
+\def\dochapentry#1#2{%
+ \penalty-300 \vskip\baselineskip
+ \line{\chapentryfonts #1\dotfill \dopageno{#2}}%
+ \nobreak\vskip .25\baselineskip
+}
+
+\def\dosecentry#1#2{%
+ \line{\secentryfonts \hskip\tocindent #1\dotfill \dopageno{#2}}%
+}
+
+\def\dosubsecentry#1#2{%
+ \line{\subsecentryfonts \hskip2\tocindent #1\dotfill \dopageno{#2}}%
+}
+
+\def\dosubsubsecentry#1#2{%
+ \line{\subsubsecentryfonts \hskip3\tocindent #1\dotfill \dopageno{#2}}%
+}
+
+% Space between chapter (or whatever) number and the title.
+\def\labelspace{\hskip1em \relax}
+
+\def\dopageno#1{{\rm #1}}
+\def\doshortpageno#1{{\rm #1}}
+
+\def\chapentryfonts{\secfonts \rm}
+\def\secentryfonts{\textfonts}
+\let\subsecentryfonts = \textfonts
+\let\subsubsecentryfonts = \textfonts
+
+
+\message{environments,}
+
+% Since these characters are used in examples, it should be an even number of
+% \tt widths. Each \tt character is 1en, so two makes it 1em.
+% Furthermore, these definitions must come after we define our fonts.
+\newbox\dblarrowbox \newbox\longdblarrowbox
+\newbox\pushcharbox \newbox\bullbox
+\newbox\equivbox \newbox\errorbox
+
+\let\ptexequiv = \equiv
+
+{\tentt
+\global\setbox\dblarrowbox = \hbox to 1em{\hfil$\Rightarrow$\hfil}
+\global\setbox\longdblarrowbox = \hbox to 1em{\hfil$\mapsto$\hfil}
+\global\setbox\pushcharbox = \hbox to 1em{\hfil$\dashv$\hfil}
+\global\setbox\equivbox = \hbox to 1em{\hfil$\ptexequiv$\hfil}
+% Adapted from the manmac format (p.420 of TeXbook)
+\global\setbox\bullbox = \hbox to 1em{\kern.15em\vrule height .75ex width .85ex
+ depth .1ex\hfil}
+}
+
+\def\point{$\star$}
+
+\def\result{\leavevmode\raise.15ex\copy\dblarrowbox}
+\def\expansion{\leavevmode\raise.1ex\copy\longdblarrowbox}
+\def\print{\leavevmode\lower.1ex\copy\pushcharbox}
+
+\def\equiv{\leavevmode\lower.1ex\copy\equivbox}
+
+% Does anyone really want this?
+% \def\bull{\leavevmode\copy\bullbox}
+
+% Adapted from the TeXbook's \boxit.
+\dimen0 = 3em % Width of the box.
+\dimen2 = .55pt % Thickness of rules
+% The text. (`r' is open on the right, `e' somewhat less so on the left.)
+\setbox0 = \hbox{\kern-.75pt \tensf error\kern-1.5pt}
+
+\global\setbox\errorbox=\hbox to \dimen0{\hfil
+ \vbox{\hsize = \dimen0 \advance\hsize by -5.8pt % Space to left+right.
+ \advance\hsize by -2\dimen2 % Rules.
+ \hrule height\dimen2
+ \hbox{\vrule width\dimen2 \kern3pt % Space to left of text.
+ \vtop{\kern2.4pt \box0 \kern2.4pt}% Space above/below.
+ \kern3pt\vrule width\dimen2}% Space to right.
+ \hrule height\dimen2}
+ \hfil}
+
+% The @error{} command.
+\def\error{\leavevmode\lower.7ex\copy\errorbox}
+
+% @tex ... @end tex escapes into raw Tex temporarily.
+% One exception: @ is still an escape character, so that @end tex works.
+% But \@ or @@ will get a plain tex @ character.
+
+\def\tex{\begingroup
+\catcode `\\=0 \catcode `\{=1 \catcode `\}=2
+\catcode `\$=3 \catcode `\&=4 \catcode `\#=6
+\catcode `\^=7 \catcode `\_=8 \catcode `\~=13 \let~=\tie
+\catcode `\%=14
+\catcode`\"=12
+\catcode`\==12
+\catcode`\|=12
+\catcode`\<=12
+\catcode`\>=12
+\escapechar=`\\
+%
+\let\{=\ptexlbrace
+\let\}=\ptexrbrace
+\let\.=\ptexdot
+\let\*=\ptexstar
+\def\@={@}%
+\let\bullet=\ptexbullet
+\let\b=\ptexb \let\c=\ptexc \let\i=\ptexi \let\t=\ptext \let\l=\ptexl
+\let\L=\ptexL
+%
+\let\Etex=\endgroup}
+
+% Define @lisp ... @endlisp.
+% @lisp does a \begingroup so it can rebind things,
+% including the definition of @endlisp (which normally is erroneous).
+
+% Amount to narrow the margins by for @lisp.
+\newskip\lispnarrowing \lispnarrowing=0.4in
+
+% This is the definition that ^M gets inside @lisp
+% phr: changed space to \null, to avoid overfull hbox problems.
+{\obeyspaces%
+\gdef\lisppar{\null\endgraf}}
+
+% Cause \obeyspaces to make each Space cause a word-separation
+% rather than the default which is that it acts punctuation.
+% This is because space in tt font looks funny.
+{\obeyspaces %
+\gdef\sepspaces{\def {\ }}}
+
+\newskip\aboveenvskipamount \aboveenvskipamount= 0pt
+\def\aboveenvbreak{{\advance\aboveenvskipamount by \parskip
+\endgraf \ifdim\lastskip<\aboveenvskipamount
+\removelastskip \penalty-50 \vskip\aboveenvskipamount \fi}}
+
+\def\afterenvbreak{\endgraf \ifdim\lastskip<\aboveenvskipamount
+\removelastskip \penalty-50 \vskip\aboveenvskipamount \fi}
+
+\def\lisp{\aboveenvbreak\begingroup\inENV %This group ends at the end of the @lisp body
+\hfuzz=12truept % Don't be fussy
+% Make spaces be word-separators rather than space tokens.
+\sepspaces %
+% Single space lines
+\singlespace %
+% The following causes blank lines not to be ignored
+% by adding a space to the end of each line.
+\let\par=\lisppar
+\def\Elisp{\endgroup\afterenvbreak}%
+\parskip=0pt
+\advance \leftskip by \lispnarrowing
+\parindent=0pt
+\let\exdent=\internalexdent
+\obeyspaces \obeylines \tt \rawbackslash
+\def\next##1{}\next}
+
+
+\let\example=\lisp
+\def\Eexample{\Elisp}
+
+\let\smallexample=\lisp
+\def\Esmallexample{\Elisp}
+
+% Macro for 9 pt. examples, necessary to print with 5" lines.
+% From Pavel@xerox. This is not really used unless the
+% @smallbook command is given.
+
+\def\smalllispx{\aboveenvbreak\begingroup\inENV
+% This group ends at the end of the @lisp body
+\hfuzz=12truept % Don't be fussy
+% Make spaces be word-separators rather than space tokens.
+\sepspaces %
+% Single space lines
+\singlespace %
+% The following causes blank lines not to be ignored
+% by adding a space to the end of each line.
+\let\par=\lisppar
+\def\Esmalllisp{\endgroup\afterenvbreak}%
+\parskip=0pt
+\advance \leftskip by \lispnarrowing
+\parindent=0pt
+\let\exdent=\internalexdent
+\obeyspaces \obeylines \ninett \rawbackslash
+\def\next##1{}\next}
+
+% This is @display; same as @lisp except use roman font.
+
+\def\display{\begingroup\inENV %This group ends at the end of the @display body
+\aboveenvbreak
+% Make spaces be word-separators rather than space tokens.
+\sepspaces %
+% Single space lines
+\singlespace %
+% The following causes blank lines not to be ignored
+% by adding a space to the end of each line.
+\let\par=\lisppar
+\def\Edisplay{\endgroup\afterenvbreak}%
+\parskip=0pt
+\advance \leftskip by \lispnarrowing
+\parindent=0pt
+\let\exdent=\internalexdent
+\obeyspaces \obeylines
+\def\next##1{}\next}
+
+% This is @format; same as @lisp except use roman font and don't narrow margins
+
+\def\format{\begingroup\inENV %This group ends at the end of the @format body
+\aboveenvbreak
+% Make spaces be word-separators rather than space tokens.
+\sepspaces %
+\singlespace %
+% The following causes blank lines not to be ignored
+% by adding a space to the end of each line.
+\let\par=\lisppar
+\def\Eformat{\endgroup\afterenvbreak}
+\parskip=0pt \parindent=0pt
+\obeyspaces \obeylines
+\def\next##1{}\next}
+
+% @flushleft and @flushright
+
+\def\flushleft{\begingroup\inENV %This group ends at the end of the @format body
+\aboveenvbreak
+% Make spaces be word-separators rather than space tokens.
+\sepspaces %
+% The following causes blank lines not to be ignored
+% by adding a space to the end of each line.
+% This also causes @ to work when the directive name
+% is terminated by end of line.
+\let\par=\lisppar
+\def\Eflushleft{\endgroup\afterenvbreak}%
+\parskip=0pt \parindent=0pt
+\obeyspaces \obeylines
+\def\next##1{}\next}
+
+\def\flushright{\begingroup\inENV %This group ends at the end of the @format body
+\aboveenvbreak
+% Make spaces be word-separators rather than space tokens.
+\sepspaces %
+% The following causes blank lines not to be ignored
+% by adding a space to the end of each line.
+% This also causes @ to work when the directive name
+% is terminated by end of line.
+\let\par=\lisppar
+\def\Eflushright{\endgroup\afterenvbreak}%
+\parskip=0pt \parindent=0pt
+\advance \leftskip by 0pt plus 1fill
+\obeyspaces \obeylines
+\def\next##1{}\next}
+
+% @quotation - narrow the margins.
+
+\def\quotation{\begingroup\inENV %This group ends at the end of the @quotation body
+{\parskip=0pt % because we will skip by \parskip too, later
+\aboveenvbreak}%
+\singlespace
+\parindent=0pt
+\def\Equotation{\par\endgroup\afterenvbreak}%
+\advance \rightskip by \lispnarrowing
+\advance \leftskip by \lispnarrowing}
+
+\message{defuns,}
+% Define formatter for defuns
+% First, allow user to change definition object font (\df) internally
+\def\setdeffont #1 {\csname DEF#1\endcsname}
+
+\newskip\defbodyindent \defbodyindent=.4in
+\newskip\defargsindent \defargsindent=50pt
+\newskip\deftypemargin \deftypemargin=12pt
+\newskip\deflastargmargin \deflastargmargin=18pt
+
+\newcount\parencount
+% define \functionparens, which makes ( and ) and & do special things.
+% \functionparens affects the group it is contained in.
+\def\activeparens{%
+\catcode`\(=\active \catcode`\)=\active \catcode`\&=\active
+\catcode`\[=\active \catcode`\]=\active}
+{\activeparens % Now, smart parens don't turn on until &foo (see \amprm)
+\gdef\functionparens{\boldbrax\let&=\amprm\parencount=0 }
+\gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb}
+
+% Definitions of (, ) and & used in args for functions.
+% This is the definition of ( outside of all parentheses.
+\gdef\oprm#1 {{\rm\char`\(}#1 \bf \let(=\opnested %
+\global\advance\parencount by 1 }
+%
+% This is the definition of ( when already inside a level of parens.
+\gdef\opnested{\char`\(\global\advance\parencount by 1 }
+%
+\gdef\clrm{% Print a paren in roman if it is taking us back to depth of 0.
+% also in that case restore the outer-level definition of (.
+\ifnum \parencount=1 {\rm \char `\)}\sl \let(=\oprm \else \char `\) \fi
+\global\advance \parencount by -1 }
+% If we encounter &foo, then turn on ()-hacking afterwards
+\gdef\amprm#1 {{\rm\&#1}\let(=\oprm \let)=\clrm\ }
+%
+\gdef\normalparens{\boldbrax\let&=\ampnr}
+} % End of definition inside \activeparens
+%% These parens (in \boldbrax) actually are a little bolder than the
+%% contained text. This is especially needed for [ and ]
+\def\opnr{{\sf\char`\(}} \def\clnr{{\sf\char`\)}} \def\ampnr{\&}
+\def\lbrb{{\tt\char`\[}} \def\rbrb{{\tt\char`\]}}
+
+% First, defname, which formats the header line itself.
+% #1 should be the function name.
+% #2 should be the type of definition, such as "Function".
+
+\def\defname #1#2{%
+\leftskip = 0in %
+\noindent %
+\setbox0=\hbox{\hskip \deflastargmargin{\rm #2}\hskip \deftypemargin}%
+\dimen0=\hsize \advance \dimen0 by -\wd0 % compute size for first line
+\dimen1=\hsize \advance \dimen1 by -\defargsindent %size for continuations
+\parshape 2 0in \dimen0 \defargsindent \dimen1 %
+% Now output arg 2 ("Function" or some such)
+% ending at \deftypemargin from the right margin,
+% but stuck inside a box of width 0 so it does not interfere with linebreaking
+\rlap{\rightline{{\rm #2}\hskip \deftypemargin}}%
+\tolerance=10000 \hbadness=10000 % Make all lines underfull and no complaints
+{\df #1}\enskip % Generate function name
+}
+
+% Actually process the body of a definition
+% #1 should be the terminating control sequence, such as \Edefun.
+% #2 should be the "another name" control sequence, such as \defunx.
+% #3 should be the control sequence that actually processes the header,
+% such as \defunheader.
+
+\def\defparsebody #1#2#3{\begingroup\inENV% Environment for definitionbody
+\medbreak %
+% Define the end token that this defining construct specifies
+% so that it will exit this group.
+\def#1{\endgraf\endgroup\medbreak}%
+\def#2{\begingroup\obeylines\activeparens\spacesplit#3}%
+\parindent=0in \leftskip=\defbodyindent \rightskip=\defbodyindent %
+\begingroup\obeylines\activeparens\spacesplit#3}
+
+\def\defmethparsebody #1#2#3#4 {\begingroup\inENV %
+\medbreak %
+% Define the end token that this defining construct specifies
+% so that it will exit this group.
+\def#1{\endgraf\endgroup\medbreak}%
+\def#2##1 {\begingroup\obeylines\activeparens\spacesplit{#3{##1}}}%
+\parindent=0in \leftskip=\defbodyindent \rightskip=\defbodyindent %
+\begingroup\obeylines\activeparens\spacesplit{#3{#4}}}
+
+\def\defopparsebody #1#2#3#4#5 {\begingroup\inENV %
+\medbreak %
+% Define the end token that this defining construct specifies
+% so that it will exit this group.
+\def#1{\endgraf\endgroup\medbreak}%
+\def#2##1 ##2 {\def#4{##1}%
+\begingroup\obeylines\activeparens\spacesplit{#3{##2}}}%
+\parindent=0in \leftskip=\defbodyindent %
+\begingroup\obeylines\activeparens\spacesplit{#3{#5}}}
+
+% Split up #2 at the first space token.
+% call #1 with two arguments:
+% the first is all of #2 before the space token,
+% the second is all of #2 after that space token.
+% If #2 contains no space token, all of it is passed as the first arg
+% and the second is passed as empty.
+
+{\obeylines
+\gdef\spacesplit#1#2^^M{\endgroup\spacesplitfoo{#1}#2 \relax\spacesplitfoo}%
+\long\gdef\spacesplitfoo#1#2 #3#4\spacesplitfoo{%
+\ifx\relax #3%
+#1{#2}{}\else #1{#2}{#3#4}\fi}}
+
+% So much for the things common to all kinds of definitions.
+
+% Define @defun.
+
+% First, define the processing that is wanted for arguments of \defun
+% Use this to expand the args and terminate the paragraph they make up
+
+\def\defunargs #1{\functionparens \sl
+% Expand, preventing hyphenation at `-' chars.
+% Note that groups don't affect changes in \hyphenchar.
+\hyphenchar\sl=0
+#1%
+\hyphenchar\sl=45
+\ifnum\parencount=0 \else \errmessage{unbalanced parens in @def arguments}\fi%
+\interlinepenalty=10000
+\endgraf\penalty10000\vskip -\parskip }
+
+% Do complete processing of one @defun or @defunx line already parsed.
+
+% @deffn Command forward-char nchars
+
+\def\deffn{\defmethparsebody\Edeffn\deffnx\deffnheader}
+
+\def\deffnheader #1#2#3{\doind {fn}{\code{#2}}%
+\begingroup\defname {#2}{#1}\defunargs{#3}\endgroup}
+
+% @defun == @deffn Function
+
+\def\defun{\defparsebody\Edefun\defunx\defunheader}
+
+\def\defunheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index
+\begingroup\defname {#1}{Function}%
+\defunargs {#2}\endgroup %
+}
+
+% @defmac == @deffn Macro
+
+\def\defmac{\defparsebody\Edefmac\defmacx\defmacheader}
+
+\def\defmacheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index
+\begingroup\defname {#1}{Macro}%
+\defunargs {#2}\endgroup %
+}
+
+% @defspec == @deffn Special Form
+
+\def\defspec{\defparsebody\Edefspec\defspecx\defspecheader}
+
+\def\defspecheader #1#2{\doind {fn}{\code{#1}}% Make entry in function index
+\begingroup\defname {#1}{Special form}%
+\defunargs {#2}\endgroup %
+}
+
+% This definition is run if you use @defunx
+% anywhere other than immediately after a @defun or @defunx.
+
+\def\deffnx #1 {\errmessage{@deffnx in invalid context}}
+\def\defunx #1 {\errmessage{@defunx in invalid context}}
+\def\defmacx #1 {\errmessage{@defmacx in invalid context}}
+\def\defspecx #1 {\errmessage{@defspecx in invalid context}}
+
+% @defmethod, and so on
+
+% @defop {Funny Method} foo-class frobnicate argument
+
+\def\defop #1 {\def\defoptype{#1}%
+\defopparsebody\Edefop\defopx\defopheader\defoptype}
+
+\def\defopheader #1#2#3{\dosubind {fn}{\code{#2}}{on #1}% Make entry in function index
+\begingroup\defname {#2}{\defoptype{} on #1}%
+\defunargs {#3}\endgroup %
+}
+
+% @defmethod == @defop Method
+
+\def\defmethod{\defmethparsebody\Edefmethod\defmethodx\defmethodheader}
+
+\def\defmethodheader #1#2#3{\dosubind {fn}{\code{#2}}{on #1}% entry in function index
+\begingroup\defname {#2}{Operation on #1}%
+\defunargs {#3}\endgroup %
+}
+
+% @defcv {Class Option} foo-class foo-flag
+
+\def\defcv #1 {\def\defcvtype{#1}%
+\defopparsebody\Edefcv\defcvx\defcvheader\defcvtype}
+
+\def\defcvarheader #1#2#3{%
+\dosubind {vr}{\code{#2}}{of #1}% Make entry in var index
+\begingroup\defname {#2}{\defcvtype of #1}%
+\defvarargs {#3}\endgroup %
+}
+
+% @defivar == @defcv {Instance Variable}
+
+\def\defivar{\defmethparsebody\Edefivar\defivarx\defivarheader}
+
+\def\defivarheader #1#2#3{%
+\dosubind {vr}{\code{#2}}{of #1}% Make entry in var index
+\begingroup\defname {#2}{Instance variable of #1}%
+\defvarargs {#3}\endgroup %
+}
+
+% These definitions are run if you use @defmethodx, etc.,
+% anywhere other than immediately after a @defmethod, etc.
+
+\def\defopx #1 {\errmessage{@defopx in invalid context}}
+\def\defmethodx #1 {\errmessage{@defmethodx in invalid context}}
+\def\defcvx #1 {\errmessage{@defcvx in invalid context}}
+\def\defivarx #1 {\errmessage{@defivarx in invalid context}}
+
+% Now @defvar
+
+% First, define the processing that is wanted for arguments of @defvar.
+% This is actually simple: just print them in roman.
+% This must expand the args and terminate the paragraph they make up
+\def\defvarargs #1{\normalparens #1%
+\interlinepenalty=10000
+\endgraf\penalty 10000\vskip -\parskip}
+
+% @defvr Counter foo-count
+
+\def\defvr{\defmethparsebody\Edefvr\defvrx\defvrheader}
+
+\def\defvrheader #1#2#3{\doind {vr}{\code{#2}}%
+\begingroup\defname {#2}{#1}\defvarargs{#3}\endgroup}
+
+% @defvar == @defvr Variable
+
+\def\defvar{\defparsebody\Edefvar\defvarx\defvarheader}
+
+\def\defvarheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index
+\begingroup\defname {#1}{Variable}%
+\defvarargs {#2}\endgroup %
+}
+
+% @defopt == @defvr {User Option}
+
+\def\defopt{\defparsebody\Edefopt\defoptx\defoptheader}
+
+\def\defoptheader #1#2{\doind {vr}{\code{#1}}% Make entry in var index
+\begingroup\defname {#1}{User Option}%
+\defvarargs {#2}\endgroup %
+}
+
+% This definition is run if you use @defvarx
+% anywhere other than immediately after a @defvar or @defvarx.
+
+\def\defvrx #1 {\errmessage{@defvrx in invalid context}}
+\def\defvarx #1 {\errmessage{@defvarx in invalid context}}
+\def\defoptx #1 {\errmessage{@defoptx in invalid context}}
+
+% Now define @deftp
+% Args are printed in bold, a slight difference from @defvar.
+
+\def\deftpargs #1{\bf \defvarargs{#1}}
+
+% @deftp Class window height width ...
+
+\def\deftp{\defmethparsebody\Edeftp\deftpx\deftpheader}
+
+\def\deftpheader #1#2#3{\doind {tp}{\code{#2}}%
+\begingroup\defname {#2}{#1}\deftpargs{#3}\endgroup}
+
+% This definition is run if you use @deftpx, etc
+% anywhere other than immediately after a @deftp, etc.
+
+\def\deftpx #1 {\errmessage{@deftpx in invalid context}}
+
+\message{cross reference,}
+% Define cross-reference macros
+\newwrite \auxfile
+
+% \setref{foo} defines a cross-reference point named foo.
+
+\def\setref#1{%
+\dosetq{#1-pg}{Ypagenumber}%
+\dosetq{#1-snt}{Ysectionnumberandtype}}
+
+\def\unnumbsetref#1{%
+\dosetq{#1-pg}{Ypagenumber}%
+\dosetq{#1-snt}{Ynothing}}
+
+\def\appendixsetref#1{%
+\dosetq{#1-pg}{Ypagenumber}%
+\dosetq{#1-snt}{Yappendixletterandtype}}
+
+% \xref and \pxref generate cross references to specified points.
+
+\def\pxref #1{see \xrefX [#1,,,,,,,]}
+\def\xref #1{See \xrefX [#1,,,,,,,]}
+\def\ref #1{\xrefX [#1,,,,,,,]}
+\def\xrefX [#1,#2,#3,#4,#5,#6]{%
+\setbox1=\hbox{\i{\losespace#5{}}}%
+\setbox0=\hbox{\losespace#3{}}%
+\ifdim \wd0 =0pt \setbox0=\hbox{\losespace#1{}}\fi%
+\ifdim \wd1 >0pt%
+section `\unhbox0' in \unhbox1%
+\else%
+\refx{#1-snt}{} [\unhbox0], page\tie \refx{#1-pg}{}%
+\fi }
+
+% \dosetq is the interface for calls from other macros
+
+\def\dosetq #1#2{{\let\folio=0%
+\edef\next{\write\auxfile{\internalsetq {#1}{#2}}}%
+\next}}
+
+% \internalsetq {foo}{page} expands into CHARACTERS 'xrdef {foo}{...expansion of \Ypage...}
+% When the aux file is read, ' is the escape character
+
+\def\internalsetq #1#2{'xrdef {#1}{\csname #2\endcsname}}
+
+% Things to be expanded by \internalsetq
+
+\def\Ypagenumber{\folio}
+
+\def\Ynothing{}
+
+\def\Ysectionnumberandtype{%
+\ifnum\secno=0 chapter\xreftie\the\chapno %
+\else \ifnum \subsecno=0 section\xreftie\the\chapno.\the\secno %
+\else \ifnum \subsubsecno=0 %
+section\xreftie\the\chapno.\the\secno.\the\subsecno %
+\else %
+section\xreftie\the\chapno.\the\secno.\the\subsecno.\the\subsubsecno %
+\fi \fi \fi }
+
+\def\Yappendixletterandtype{%
+\ifnum\secno=0 appendix\xreftie'char\the\appendixno %
+\else \ifnum \subsecno=0 section\xreftie'char\the\appendixno.\the\secno %
+\else \ifnum \subsubsecno=0 %
+section\xreftie'char\the\appendixno.\the\secno.\the\subsecno %
+\else %
+section\xreftie'char\the\appendixno.\the\secno.\the\subsecno.\the\subsubsecno %
+\fi \fi \fi }
+
+\gdef\xreftie{'tie}
+
+% Define \refx{NAME}{SUFFIX} to reference a cross-reference string named NAME.
+% If its value is nonempty, SUFFIX is output afterward.
+
+\def\refx#1#2{%
+{%
+\expandafter\ifx\csname X#1\endcsname\relax
+% If not defined, say something at least.
+\expandafter\gdef\csname X#1\endcsname {$\langle$un\-def\-in\-ed$\rangle$}#2%
+\message {WARNING: Cross-reference "#1" used but not yet defined}%
+\message {}%
+\fi %
+\setbox0=\hbox{\csname X#1\endcsname}%It's defined, so just use it.
+\ifdim\wd0>0pt \unhbox0{}#2\fi
+}}
+
+% Read the last existing aux file, if any. No error if none exists.
+
+% This is the macro invoked by entries in the aux file.
+\def\xrdef #1#2{
+{\catcode`\'=\other\expandafter \gdef \csname X#1\endcsname {#2}}}
+
+\def\readauxfile{%
+\begingroup
+\catcode `\^^@=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\^^C=\other
+\catcode `\^^D=\other
+\catcode `\^^E=\other
+\catcode `\^^F=\other
+\catcode `\^^G=\other
+\catcode `\^^H=\other
+\catcode `\ =\other
+\catcode `\^^L=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\=\other
+\catcode `\^^[=\other
+\catcode `\^^\=\other
+\catcode `\^^]=\other
+\catcode `\^^^=\other
+\catcode `\^^_=\other
+\catcode `\@=\other
+\catcode `\^=\other
+\catcode `\~=\other
+\catcode `\[=\other
+\catcode `\]=\other
+\catcode`\"=\other
+\catcode`\_=\other
+\catcode`\|=\other
+\catcode`\<=\other
+\catcode`\>=\other
+\catcode `\$=\other
+\catcode `\#=\other
+\catcode `\&=\other
+% the aux file uses ' as the escape.
+% Turn off \ as an escape so we do not lose on
+% entries which were dumped with control sequences in their names.
+% For example, 'xrdef {$\leq $-fun}{page ...} made by @defun ^^
+% Reference to such entries still does not work the way one would wish,
+% but at least they do not bomb out when the aux file is read in.
+\catcode `\{=1 \catcode `\}=2
+\catcode `\%=\other
+\catcode `\'=0
+\catcode `\\=\other
+\openin 1 \jobname.aux
+\ifeof 1 \else \closein 1 \input \jobname.aux
+\fi
+% Open the new aux file. Tex will close it automatically at exit.
+\openout \auxfile=\jobname.aux
+\endgroup}
+
+
+% Footnotes.
+
+\newcount \footnoteno
+
+\def\supereject{\par\penalty -20000\footnoteno =0 }
+
+\let\ptexfootnote=\footnote
+
+{\catcode `\@=11
+\gdef\footnote{\global\advance \footnoteno by \@ne
+\edef\thisfootno{$^{\the\footnoteno}$}%
+\let\@sf\empty
+\ifhmode\edef\@sf{\spacefactor\the\spacefactor}\/\fi
+\thisfootno\@sf\parsearg\footnotezzz}
+
+\gdef\footnotezzz #1{\insert\footins{
+\interlinepenalty\interfootnotelinepenalty
+\splittopskip\ht\strutbox % top baseline for broken footnotes
+\splitmaxdepth\dp\strutbox \floatingpenalty\@MM
+\leftskip\z@skip \rightskip\z@skip \spaceskip\z@skip \xspaceskip\z@skip
+\footstrut\hang\textindent{\thisfootno}#1\strut}}
+
+}%end \catcode `\@=11
+
+% End of control word definitions.
+
+\message{and turning on texinfo input format.}
+
+\def\openindices{%
+ \newindex{cp}%
+ \newcodeindex{fn}%
+ \newcodeindex{vr}%
+ \newcodeindex{tp}%
+ \newcodeindex{ky}%
+ \newcodeindex{pg}%
+}
+
+% Set some numeric style parameters, for 8.5 x 11 format.
+
+\hsize = 6.5in
+\parindent 15pt
+\parskip 18pt plus 1pt
+\baselineskip 15pt
+\advance\topskip by 1.2cm
+
+% Prevent underfull vbox error messages.
+\vbadness=10000
+
+% Use @smallbook to reset parameters for 7x9.5 format
+\def\smallbook{
+\global\lispnarrowing = 0.3in
+\global\baselineskip 12pt
+\global\parskip 3pt plus 1pt
+\global\hsize = 5in
+\global\doublecolumnhsize=2.4in \global\doublecolumnvsize=15.0in
+\global\vsize=7.5in
+\global\tolerance=700
+\global\hfuzz=1pt
+
+\global\pagewidth=\hsize
+\global\pageheight=\vsize
+\global\font\ninett=cmtt9
+
+\global\let\smalllisp=\smalllispx
+\global\let\smallexample=\smalllispx
+\global\def\Esmallexample{\Esmalllisp}
+}
+
+%% For a final copy, take out the rectangles
+%% that mark overfull boxes (in case you have decided
+%% that the text looks ok even though it passes the margin).
+\def\finalout{\overfullrule=0pt}
+
+% Turn off all special characters except @
+% (and those which the user can use as if they were ordinary)
+% Define certain chars to be always in tt font.
+
+\catcode`\"=\active
+\def\activedoublequote{{\tt \char '042}}
+\let"=\activedoublequote
+\catcode`\~=\active
+\def~{{\tt \char '176}}
+\chardef\hat=`\^
+\catcode`\^=\active
+\def^{{\tt \hat}}
+\catcode`\_=\active
+\def_{{\tt \char '137}}
+\catcode`\|=\active
+\def|{{\tt \char '174}}
+\chardef \less=`\<
+\catcode`\<=\active
+\def<{{\tt \less}}
+\chardef \gtr=`\>
+\catcode`\>=\active
+\def>{{\tt \gtr}}
+\catcode`\+=\active
+\def+{{\tt \char 43}}
+%\catcode 27=\active
+%\def^^[{$\diamondsuit$}
+
+\catcode`\@=0
+
+% \rawbackslashxx output one backslash character in current font
+{\catcode`\\=\other
+@gdef@rawbackslashxx{\}}
+
+% \rawbackslash redefines \ as input to do \rawbackslashxx.
+{\catcode`\\=\active
+@gdef@rawbackslash{@let\=@rawbackslashxx }}
+
+% \normalbackslash outputs one backslash in fixed width font.
+\def\normalbackslash{{\tt\rawbackslashxx}}
+
+% Say @foo, not \foo, in error messages.
+\escapechar=`\@
+
+@c \catcode 17=0 @c Define control-q
+\catcode`\\=\active
+
+% If a .fmt file is being used, we don't want the `\input texinfo' to show up.
+% That is what \eatinput is for; after that, the `\' should revert to printing
+% a backslash.
+%
+@gdef@eatinput input texinfo{@fixbackslash}
+@global@let\ = @eatinput
+
+% On the other hand, perhaps the file did not have a `\input texinfo'. Then
+% the first `\{ in the file would cause an error. This macro tries to fix
+% that, assuming it is called before the first `\' could plausibly occur.
+%
+@gdef@fixbackslash{@ifx\@eatinput @let\ = @normalbackslash @fi}
+
+%% These look ok in all fonts, so just make them not special. The @rm below
+%% makes sure that the current font starts out as the newly loaded cmr10
+@catcode`@$=@other @catcode`@%=@other @catcode`@&=@other @catcode`@#=@other
+
+@textfonts
+@rm
diff --git a/version.c b/version.sh
index 43d35d72..6a7e5d2f 100644
--- a/version.c
+++ b/version.sh
@@ -1,4 +1,17 @@
-char *version_string = "@(#)Gnu Awk (gawk) 2.10beta 07 Apr 1989\n" + 4;
+#! /bin/sh
+
+# version.sh --- create version.c
+
+if [ "x$1" = "x" ]
+then
+ echo you must specify a release number on the command line
+ exit 1
+fi
+
+RELEASE="$1"
+
+cat << EOF
+char *version_string = "@(#)Gnu Awk (gawk) ${RELEASE}-BETA" + 4;
/* 1.02 fixed /= += *= etc to return the new Left Hand Side instead
of the Right Hand Side */
@@ -29,3 +42,8 @@ char *version_string = "@(#)Gnu Awk (gawk) 2.10beta 07 Apr 1989\n" + 4;
A number of minor bug fixes and new features from Arnold.
Changes for MSDOS from Conrad Kwok and Scott Garfinkle.
The gawk.texinfo and info files included! */
+
+/* 2.11 Bug fix release to 2.10. Lots of changes for portability,
+ speed, and configurability. */
+EOF
+exit 0
diff --git a/y.tab.c b/y.tab.c
new file mode 100644
index 00000000..e9e1da72
--- /dev/null
+++ b/y.tab.c
@@ -0,0 +1,2282 @@
+
+# line 27 "awk.y"
+#ifdef DEBUG
+#define YYDEBUG 12
+#endif
+
+#include "awk.h"
+
+/*
+ * This line is necessary since the Bison parser skeleton uses bcopy.
+ * Systems without memcpy should use -DMEMCPY_MISSING, per the Makefile.
+ * It should not hurt anything if Yacc is being used instead of Bison.
+ */
+#define bcopy(s,d,n) memcpy((d),(s),(n))
+
+extern void msg();
+extern struct re_pattern_buffer *mk_re_parse();
+
+NODE *node();
+NODE *lookup();
+NODE *install();
+
+static NODE *snode();
+static NODE *mkrangenode();
+static FILE *pathopen();
+static NODE *make_for_loop();
+static NODE *append_right();
+static void func_install();
+static NODE *make_param();
+static int hashf();
+static void pop_params();
+static void pop_var();
+static int yylex ();
+static void yyerror();
+
+static int want_regexp; /* lexical scanning kludge */
+static int want_assign; /* lexical scanning kludge */
+static int can_return; /* lexical scanning kludge */
+static int io_allowed = 1; /* lexical scanning kludge */
+static int lineno = 1; /* for error msgs */
+static char *lexptr; /* pointer to next char during parsing */
+static char *lexptr_begin; /* keep track of where we were for error msgs */
+static int curinfile = -1; /* index into sourcefiles[] */
+static int param_counter;
+
+NODE *variables[HASHSIZE];
+
+extern int errcount;
+extern NODE *begin_block;
+extern NODE *end_block;
+
+# line 77 "awk.y"
+typedef union {
+ long lval;
+ AWKNUM fval;
+ NODE *nodeval;
+ NODETYPE nodetypeval;
+ char *sval;
+ NODE *(*ptrval)();
+} YYSTYPE;
+# define FUNC_CALL 257
+# define NAME 258
+# define REGEXP 259
+# define ERROR 260
+# define NUMBER 261
+# define YSTRING 262
+# define RELOP 263
+# define APPEND_OP 264
+# define ASSIGNOP 265
+# define MATCHOP 266
+# define NEWLINE 267
+# define CONCAT_OP 268
+# define LEX_BEGIN 269
+# define LEX_END 270
+# define LEX_IF 271
+# define LEX_ELSE 272
+# define LEX_RETURN 273
+# define LEX_DELETE 274
+# define LEX_WHILE 275
+# define LEX_DO 276
+# define LEX_FOR 277
+# define LEX_BREAK 278
+# define LEX_CONTINUE 279
+# define LEX_PRINT 280
+# define LEX_PRINTF 281
+# define LEX_NEXT 282
+# define LEX_EXIT 283
+# define LEX_FUNCTION 284
+# define LEX_GETLINE 285
+# define LEX_IN 286
+# define LEX_AND 287
+# define LEX_OR 288
+# define INCREMENT 289
+# define DECREMENT 290
+# define LEX_BUILTIN 291
+# define LEX_LENGTH 292
+# define UNARY 293
+#define yyclearin yychar = -1
+#define yyerrok yyerrflag = 0
+extern int yychar;
+extern short yyerrflag;
+#ifndef YYMAXDEPTH
+#define YYMAXDEPTH 150
+#endif
+YYSTYPE yylval, yyval;
+# define YYERRCODE 256
+
+# line 671 "awk.y"
+
+
+struct token {
+ char *operator; /* text to match */
+ NODETYPE value; /* node type */
+ int class; /* lexical class */
+ short nostrict; /* ignore if in strict compatibility mode */
+ NODE *(*ptr) (); /* function that implements this keyword */
+};
+
+extern NODE
+ *do_exp(), *do_getline(), *do_index(), *do_length(),
+ *do_sqrt(), *do_log(), *do_sprintf(), *do_substr(),
+ *do_split(), *do_system(), *do_int(), *do_close(),
+ *do_atan2(), *do_sin(), *do_cos(), *do_rand(),
+ *do_srand(), *do_match(), *do_tolower(), *do_toupper(),
+ *do_sub(), *do_gsub();
+
+/* Special functions for debugging */
+#ifdef DEBUG
+NODE *do_prvars(), *do_bp();
+#endif
+
+/* Tokentab is sorted ascii ascending order, so it can be binary searched. */
+
+static struct token tokentab[] = {
+ { "BEGIN", Node_illegal, LEX_BEGIN, 0, 0 },
+ { "END", Node_illegal, LEX_END, 0, 0 },
+ { "atan2", Node_builtin, LEX_BUILTIN, 0, do_atan2 },
+#ifdef DEBUG
+ { "bp", Node_builtin, LEX_BUILTIN, 0, do_bp },
+#endif
+ { "break", Node_K_break, LEX_BREAK, 0, 0 },
+ { "close", Node_builtin, LEX_BUILTIN, 0, do_close },
+ { "continue", Node_K_continue, LEX_CONTINUE, 0, 0 },
+ { "cos", Node_builtin, LEX_BUILTIN, 0, do_cos },
+ { "delete", Node_K_delete, LEX_DELETE, 0, 0 },
+ { "do", Node_K_do, LEX_DO, 0, 0 },
+ { "else", Node_illegal, LEX_ELSE, 0, 0 },
+ { "exit", Node_K_exit, LEX_EXIT, 0, 0 },
+ { "exp", Node_builtin, LEX_BUILTIN, 0, do_exp },
+ { "for", Node_K_for, LEX_FOR, 0, 0 },
+ { "func", Node_K_function, LEX_FUNCTION, 0, 0 },
+ { "function", Node_K_function, LEX_FUNCTION, 0, 0 },
+ { "getline", Node_K_getline, LEX_GETLINE, 0, 0 },
+ { "gsub", Node_builtin, LEX_BUILTIN, 0, do_gsub },
+ { "if", Node_K_if, LEX_IF, 0, 0 },
+ { "in", Node_illegal, LEX_IN, 0, 0 },
+ { "index", Node_builtin, LEX_BUILTIN, 0, do_index },
+ { "int", Node_builtin, LEX_BUILTIN, 0, do_int },
+ { "length", Node_builtin, LEX_LENGTH, 0, do_length },
+ { "log", Node_builtin, LEX_BUILTIN, 0, do_log },
+ { "match", Node_builtin, LEX_BUILTIN, 0, do_match },
+ { "next", Node_K_next, LEX_NEXT, 0, 0 },
+ { "print", Node_K_print, LEX_PRINT, 0, 0 },
+ { "printf", Node_K_printf, LEX_PRINTF, 0, 0 },
+#ifdef DEBUG
+ { "prvars", Node_builtin, LEX_BUILTIN, 0, do_prvars },
+#endif
+ { "rand", Node_builtin, LEX_BUILTIN, 0, do_rand },
+ { "return", Node_K_return, LEX_RETURN, 0, 0 },
+ { "sin", Node_builtin, LEX_BUILTIN, 0, do_sin },
+ { "split", Node_builtin, LEX_BUILTIN, 0, do_split },
+ { "sprintf", Node_builtin, LEX_BUILTIN, 0, do_sprintf },
+ { "sqrt", Node_builtin, LEX_BUILTIN, 0, do_sqrt },
+ { "srand", Node_builtin, LEX_BUILTIN, 0, do_srand },
+ { "sub", Node_builtin, LEX_BUILTIN, 0, do_sub },
+ { "substr", Node_builtin, LEX_BUILTIN, 0, do_substr },
+ { "system", Node_builtin, LEX_BUILTIN, 0, do_system },
+ { "tolower", Node_builtin, LEX_BUILTIN, 0, do_tolower },
+ { "toupper", Node_builtin, LEX_BUILTIN, 0, do_toupper },
+ { "while", Node_K_while, LEX_WHILE, 0, 0 },
+};
+
+static char *token_start;
+
+/* VARARGS0 */
+static void
+yyerror(va_alist)
+va_dcl
+{
+ va_list args;
+ char *mesg;
+ register char *ptr, *beg;
+ char *scan;
+
+ errcount++;
+ va_start(args);
+ mesg = va_arg(args, char *);
+ va_end(args);
+ /* Find the current line in the input file */
+ if (! lexptr) {
+ beg = "(END OF FILE)";
+ ptr = beg + 13;
+ } else {
+ if (*lexptr == '\n' && lexptr != lexptr_begin)
+ --lexptr;
+ for (beg = lexptr; beg != lexptr_begin && *beg != '\n'; --beg)
+ ;
+ /* NL isn't guaranteed */
+ for (ptr = lexptr; *ptr && *ptr != '\n'; ptr++)
+ ;
+ if (beg != lexptr_begin)
+ beg++;
+ }
+ msg("syntax error near line %d:\n%.*s", lineno, ptr - beg, beg);
+ scan = beg;
+ while (scan < token_start)
+ if (*scan++ == '\t')
+ putc('\t', stderr);
+ else
+ putc(' ', stderr);
+ putc('^', stderr);
+ putc(' ', stderr);
+ vfprintf(stderr, mesg, args);
+ putc('\n', stderr);
+ exit(1);
+}
+
+/*
+ * Parse a C escape sequence. STRING_PTR points to a variable containing a
+ * pointer to the string to parse. That pointer is updated past the
+ * characters we use. The value of the escape sequence is returned.
+ *
+ * A negative value means the sequence \ newline was seen, which is supposed to
+ * be equivalent to nothing at all.
+ *
+ * If \ is followed by a null character, we return a negative value and leave
+ * the string pointer pointing at the null character.
+ *
+ * If \ is followed by 000, we return 0 and leave the string pointer after the
+ * zeros. A value of 0 does not mean end of string.
+ */
+
+int
+parse_escape(string_ptr)
+char **string_ptr;
+{
+ register int c = *(*string_ptr)++;
+ register int i;
+ register int count = 0;
+
+ switch (c) {
+ case 'a':
+ return BELL;
+ case 'b':
+ return '\b';
+ case 'f':
+ return '\f';
+ case 'n':
+ return '\n';
+ case 'r':
+ return '\r';
+ case 't':
+ return '\t';
+ case 'v':
+ return '\v';
+ case '\n':
+ return -2;
+ case 0:
+ (*string_ptr)--;
+ return -1;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ i = c - '0';
+ count = 0;
+ while (++count < 3) {
+ if ((c = *(*string_ptr)++) >= '0' && c <= '7') {
+ i *= 8;
+ i += c - '0';
+ } else {
+ (*string_ptr)--;
+ break;
+ }
+ }
+ return i;
+ case 'x':
+ i = 0;
+ while (1) {
+ if (isxdigit((c = *(*string_ptr)++))) {
+ if (isdigit(c))
+ i += c - '0';
+ else if (isupper(c))
+ i += c - 'A' + 10;
+ else
+ i += c - 'a' + 10;
+ } else {
+ (*string_ptr)--;
+ break;
+ }
+ }
+ return i;
+ default:
+ return c;
+ }
+}
+
+/*
+ * Read the input and turn it into tokens. Input is now read from a file
+ * instead of from malloc'ed memory. The main program takes a program
+ * passed as a command line argument and writes it to a temp file. Otherwise
+ * the file name is made available in an external variable.
+ */
+
+static int
+yylex()
+{
+ register int c;
+ register int namelen;
+ register char *tokstart;
+ char *tokkey;
+ static did_newline = 0; /* the grammar insists that actions end
+ * with newlines. This was easier than
+ * hacking the grammar. */
+ int seen_e = 0; /* These are for numbers */
+ int seen_point = 0;
+ int esc_seen;
+ extern char **sourcefile;
+ extern int tempsource, numfiles;
+ static int file_opened = 0;
+ static FILE *fin;
+ static char cbuf[BUFSIZ];
+ int low, mid, high;
+#ifdef DEBUG
+ extern int debugging;
+#endif
+
+ if (! file_opened) {
+ file_opened = 1;
+#ifdef DEBUG
+ if (debugging) {
+ int i;
+
+ for (i = 0; i <= numfiles; i++)
+ fprintf (stderr, "sourcefile[%d] = %s\n", i,
+ sourcefile[i]);
+ }
+#endif
+ nextfile:
+ if ((fin = pathopen (sourcefile[++curinfile])) == NULL)
+ fatal("cannot open `%s' for reading (%s)",
+ sourcefile[curinfile],
+ strerror(errno));
+ *(lexptr = cbuf) = '\0';
+ /*
+ * immediately unlink the tempfile so that it will
+ * go away cleanly if we bomb.
+ */
+ if (tempsource && curinfile == 0)
+ (void) unlink (sourcefile[curinfile]);
+ }
+
+retry:
+ if (! *lexptr)
+ if (fgets (cbuf, sizeof cbuf, fin) == NULL) {
+ if (fin != NULL)
+ fclose (fin); /* be neat and clean */
+ if (curinfile < numfiles)
+ goto nextfile;
+ return 0;
+ } else
+ lexptr = lexptr_begin = cbuf;
+
+ if (want_regexp) {
+ int in_brack = 0;
+
+ want_regexp = 0;
+ token_start = tokstart = lexptr;
+ while (c = *lexptr++) {
+ switch (c) {
+ case '[':
+ in_brack = 1;
+ break;
+ case ']':
+ in_brack = 0;
+ break;
+ case '\\':
+ if (*lexptr++ == '\0') {
+ yyerror("unterminated regexp ends with \\");
+ return ERROR;
+ } else if (lexptr[-1] == '\n')
+ goto retry;
+ break;
+ case '/': /* end of the regexp */
+ if (in_brack)
+ break;
+
+ lexptr--;
+ yylval.sval = tokstart;
+ return REGEXP;
+ case '\n':
+ lineno++;
+ case '\0':
+ lexptr--; /* so error messages work */
+ yyerror("unterminated regexp");
+ return ERROR;
+ }
+ }
+ }
+
+ if (*lexptr == '\n') {
+ lexptr++;
+ lineno++;
+ return NEWLINE;
+ }
+
+ while (*lexptr == ' ' || *lexptr == '\t')
+ lexptr++;
+
+ token_start = tokstart = lexptr;
+
+ switch (c = *lexptr++) {
+ case 0:
+ return 0;
+
+ case '\n':
+ lineno++;
+ return NEWLINE;
+
+ case '#': /* it's a comment */
+ while (*lexptr != '\n' && *lexptr != '\0')
+ lexptr++;
+ goto retry;
+
+ case '\\':
+ if (*lexptr == '\n') {
+ lineno++;
+ lexptr++;
+ goto retry;
+ } else
+ break;
+ case ')':
+ case ']':
+ case '(':
+ case '[':
+ case '$':
+ case ';':
+ case ':':
+ case '?':
+
+ /*
+ * set node type to ILLEGAL because the action should set it
+ * to the right thing
+ */
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '{':
+ case ',':
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '*':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_assign_times;
+ lexptr++;
+ return ASSIGNOP;
+ } else if (*lexptr == '*') { /* make ** and **= aliases
+ * for ^ and ^= */
+ if (lexptr[1] == '=') {
+ yylval.nodetypeval = Node_assign_exp;
+ lexptr += 2;
+ return ASSIGNOP;
+ } else {
+ yylval.nodetypeval = Node_illegal;
+ lexptr++;
+ return '^';
+ }
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '/':
+ if (want_assign && *lexptr == '=') {
+ yylval.nodetypeval = Node_assign_quotient;
+ lexptr++;
+ return ASSIGNOP;
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '%':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_assign_mod;
+ lexptr++;
+ return ASSIGNOP;
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '^':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_assign_exp;
+ lexptr++;
+ return ASSIGNOP;
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '+':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_assign_plus;
+ lexptr++;
+ return ASSIGNOP;
+ }
+ if (*lexptr == '+') {
+ yylval.nodetypeval = Node_illegal;
+ lexptr++;
+ return INCREMENT;
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '!':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_notequal;
+ lexptr++;
+ return RELOP;
+ }
+ if (*lexptr == '~') {
+ yylval.nodetypeval = Node_nomatch;
+ lexptr++;
+ return MATCHOP;
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '<':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_leq;
+ lexptr++;
+ return RELOP;
+ }
+ yylval.nodetypeval = Node_less;
+ return c;
+
+ case '=':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_equal;
+ lexptr++;
+ return RELOP;
+ }
+ yylval.nodetypeval = Node_assign;
+ return ASSIGNOP;
+
+ case '>':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_geq;
+ lexptr++;
+ return RELOP;
+ } else if (*lexptr == '>') {
+ yylval.nodetypeval = Node_redirect_append;
+ lexptr++;
+ return APPEND_OP;
+ }
+ yylval.nodetypeval = Node_greater;
+ return c;
+
+ case '~':
+ yylval.nodetypeval = Node_match;
+ return MATCHOP;
+
+ case '}':
+ /*
+ * Added did newline stuff. Easier than
+ * hacking the grammar
+ */
+ if (did_newline) {
+ did_newline = 0;
+ return c;
+ }
+ did_newline++;
+ --lexptr;
+ return NEWLINE;
+
+ case '"':
+ esc_seen = 0;
+ while (*lexptr != '\0') {
+ switch (*lexptr++) {
+ case '\\':
+ esc_seen = 1;
+ if (*lexptr == '\n')
+ yyerror("newline in string");
+ if (*lexptr++ != '\0')
+ break;
+ /* fall through */
+ case '\n':
+ lexptr--;
+ yyerror("unterminated string");
+ return ERROR;
+ case '"':
+ yylval.nodeval = make_str_node(tokstart + 1,
+ lexptr-tokstart-2, esc_seen);
+ yylval.nodeval->flags |= PERM;
+ return YSTRING;
+ }
+ }
+ return ERROR;
+
+ case '-':
+ if (*lexptr == '=') {
+ yylval.nodetypeval = Node_assign_minus;
+ lexptr++;
+ return ASSIGNOP;
+ }
+ if (*lexptr == '-') {
+ yylval.nodetypeval = Node_illegal;
+ lexptr++;
+ return DECREMENT;
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '.':
+ /* It's a number */
+ for (namelen = 0; (c = tokstart[namelen]) != '\0'; namelen++) {
+ switch (c) {
+ case '.':
+ if (seen_point)
+ goto got_number;
+ ++seen_point;
+ break;
+ case 'e':
+ case 'E':
+ if (seen_e)
+ goto got_number;
+ ++seen_e;
+ if (tokstart[namelen + 1] == '-' ||
+ tokstart[namelen + 1] == '+')
+ namelen++;
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ break;
+ default:
+ goto got_number;
+ }
+ }
+
+got_number:
+ lexptr = tokstart + namelen;
+ /*
+ yylval.nodeval = make_string(tokstart, namelen);
+ (void) force_number(yylval.nodeval);
+ */
+ yylval.nodeval = make_number(atof(tokstart));
+ yylval.nodeval->flags |= PERM;
+ return NUMBER;
+
+ case '&':
+ if (*lexptr == '&') {
+ yylval.nodetypeval = Node_and;
+ while (c = *++lexptr) {
+ if (c == '#')
+ while ((c = *++lexptr) != '\n'
+ && c != '\0')
+ ;
+ if (c == '\n')
+ lineno++;
+ else if (! isspace(c))
+ break;
+ }
+ return LEX_AND;
+ }
+ return ERROR;
+
+ case '|':
+ if (*lexptr == '|') {
+ yylval.nodetypeval = Node_or;
+ while (c = *++lexptr) {
+ if (c == '#')
+ while ((c = *++lexptr) != '\n'
+ && c != '\0')
+ ;
+ if (c == '\n')
+ lineno++;
+ else if (! isspace(c))
+ break;
+ }
+ return LEX_OR;
+ }
+ yylval.nodetypeval = Node_illegal;
+ return c;
+ }
+
+ if (c != '_' && ! isalpha(c)) {
+ yyerror("Invalid char '%c' in expression\n", c);
+ return ERROR;
+ }
+
+ /* it's some type of name-type-thing. Find its length */
+ for (namelen = 0; is_identchar(tokstart[namelen]); namelen++)
+ /* null */ ;
+ emalloc(tokkey, char *, namelen+1, "yylex");
+ memcpy(tokkey, tokstart, namelen);
+ tokkey[namelen] = '\0';
+
+ /* See if it is a special token. */
+ low = 0;
+ high = (sizeof (tokentab) / sizeof (tokentab[0])) - 1;
+ while (low <= high) {
+ int i, c;
+
+ mid = (low + high) / 2;
+ c = *tokstart - tokentab[mid].operator[0];
+ i = c ? c : strcmp (tokkey, tokentab[mid].operator);
+
+ if (i < 0) { /* token < mid */
+ high = mid - 1;
+ } else if (i > 0) { /* token > mid */
+ low = mid + 1;
+ } else {
+ lexptr = tokstart + namelen;
+ if (strict && tokentab[mid].nostrict)
+ break;
+ if (tokentab[mid].class == LEX_BUILTIN
+ || tokentab[mid].class == LEX_LENGTH)
+ yylval.ptrval = tokentab[mid].ptr;
+ else
+ yylval.nodetypeval = tokentab[mid].value;
+ return tokentab[mid].class;
+ }
+ }
+
+ /* It's a name. See how long it is. */
+ yylval.sval = tokkey;
+ lexptr = tokstart + namelen;
+ if (*lexptr == '(')
+ return FUNC_CALL;
+ else
+ return NAME;
+}
+
+#ifndef DEFPATH
+#ifdef MSDOS
+#define DEFPATH "."
+#define ENVSEP ';'
+#else
+#define DEFPATH ".:/usr/lib/awk:/usr/local/lib/awk"
+#define ENVSEP ':'
+#endif
+#endif
+
+static FILE *
+pathopen (file)
+char *file;
+{
+ static char *savepath = DEFPATH;
+ static int first = 1;
+ char *awkpath, *cp;
+ char trypath[BUFSIZ];
+ FILE *fp;
+#ifdef DEBUG
+ extern int debugging;
+#endif
+ int fd;
+
+ if (strcmp (file, "-") == 0)
+ return (stdin);
+
+ if (strict)
+ return (fopen (file, "r"));
+
+ if (first) {
+ first = 0;
+ if ((awkpath = getenv ("AWKPATH")) != NULL && *awkpath)
+ savepath = awkpath; /* used for restarting */
+ }
+ awkpath = savepath;
+
+ /* some kind of path name, no search */
+#ifndef MSDOS
+ if (strchr (file, '/') != NULL)
+#else
+ if (strchr (file, '/') != NULL || strchr (file, '\\') != NULL
+ || strchr (file, ':') != NULL)
+#endif
+ return ( (fd = devopen (file, "r")) >= 0 ?
+ fdopen(fd, "r") :
+ NULL);
+
+ do {
+ trypath[0] = '\0';
+ /* this should take into account limits on size of trypath */
+ for (cp = trypath; *awkpath && *awkpath != ENVSEP; )
+ *cp++ = *awkpath++;
+
+ if (cp != trypath) { /* nun-null element in path */
+ *cp++ = '/';
+ strcpy (cp, file);
+ } else
+ strcpy (trypath, file);
+#ifdef DEBUG
+ if (debugging)
+ fprintf(stderr, "trying: %s\n", trypath);
+#endif
+ if ((fd = devopen (trypath, "r")) >= 0
+ && (fp = fdopen(fd, "r")) != NULL)
+ return (fp);
+
+ /* no luck, keep going */
+ if(*awkpath == ENVSEP && awkpath[1] != '\0')
+ awkpath++; /* skip colon */
+ } while (*awkpath);
+#ifdef MSDOS
+ /*
+ * Under DOS (and probably elsewhere) you might have one of the awk
+ * paths defined, WITHOUT the current working directory in it.
+ * Therefore you should try to open the file in the current directory.
+ */
+ return ( (fd = devopen(file, "r")) >= 0 ? fdopen(fd, "r") : NULL);
+#else
+ return (NULL);
+#endif
+}
+
+static NODE *
+node_common(op)
+NODETYPE op;
+{
+ register NODE *r;
+ extern int numfiles;
+ extern int tempsource;
+ extern char **sourcefile;
+
+ r = newnode(op);
+ r->source_line = lineno;
+ if (numfiles > -1 && ! tempsource)
+ r->source_file = sourcefile[curinfile];
+ else
+ r->source_file = NULL;
+ return r;
+}
+
+/*
+ * This allocates a node with defined lnode and rnode.
+ * This should only be used by yyparse+co while reading in the program
+ */
+NODE *
+node(left, op, right)
+NODE *left, *right;
+NODETYPE op;
+{
+ register NODE *r;
+
+ r = node_common(op);
+ r->lnode = left;
+ r->rnode = right;
+ return r;
+}
+
+/*
+ * This allocates a node with defined subnode and proc
+ * Otherwise like node()
+ */
+static NODE *
+snode(subn, op, procp)
+NODETYPE op;
+NODE *(*procp) ();
+NODE *subn;
+{
+ register NODE *r;
+
+ r = node_common(op);
+ r->subnode = subn;
+ r->proc = procp;
+ return r;
+}
+
+/*
+ * This allocates a Node_line_range node with defined condpair and
+ * zeroes the trigger word to avoid the temptation of assuming that calling
+ * 'node( foo, Node_line_range, 0)' will properly initialize 'triggered'.
+ */
+/* Otherwise like node() */
+static NODE *
+mkrangenode(cpair)
+NODE *cpair;
+{
+ register NODE *r;
+
+ r = newnode(Node_line_range);
+ r->condpair = cpair;
+ r->triggered = 0;
+ return r;
+}
+
+/* Build a for loop */
+static NODE *
+make_for_loop(init, cond, incr)
+NODE *init, *cond, *incr;
+{
+ register FOR_LOOP_HEADER *r;
+ NODE *n;
+
+ emalloc(r, FOR_LOOP_HEADER *, sizeof(FOR_LOOP_HEADER), "make_for_loop");
+ n = newnode(Node_illegal);
+ r->init = init;
+ r->cond = cond;
+ r->incr = incr;
+ n->sub.nodep.r.hd = r;
+ return n;
+}
+
+/*
+ * Install a name in the hash table specified, even if it is already there.
+ * Name stops with first non alphanumeric. Caller must check against
+ * redefinition if that is desired.
+ */
+NODE *
+install(table, name, value)
+NODE **table;
+char *name;
+NODE *value;
+{
+ register NODE *hp;
+ register int len, bucket;
+ register char *p;
+
+ len = 0;
+ p = name;
+ while (is_identchar(*p))
+ p++;
+ len = p - name;
+
+ hp = newnode(Node_hashnode);
+ bucket = hashf(name, len, HASHSIZE);
+ hp->hnext = table[bucket];
+ table[bucket] = hp;
+ hp->hlength = len;
+ hp->hvalue = value;
+ emalloc(hp->hname, char *, len + 1, "install");
+ memcpy(hp->hname, name, len);
+ hp->hname[len] = '\0';
+ return hp->hvalue;
+}
+
+/*
+ * find the most recent hash node for name name (ending with first
+ * non-identifier char) installed by install
+ */
+NODE *
+lookup(table, name)
+NODE **table;
+char *name;
+{
+ register char *bp;
+ register NODE *bucket;
+ register int len;
+
+ for (bp = name; is_identchar(*bp); bp++)
+ ;
+ len = bp - name;
+ bucket = table[hashf(name, len, HASHSIZE)];
+ while (bucket) {
+ if (bucket->hlength == len && STREQN(bucket->hname, name, len))
+ return bucket->hvalue;
+ bucket = bucket->hnext;
+ }
+ return NULL;
+}
+
+#define HASHSTEP(old, c) ((old << 1) + c)
+#define MAKE_POS(v) (v & ~0x80000000) /* make number positive */
+
+/*
+ * return hash function on name.
+ */
+static int
+hashf(name, len, hashsize)
+register char *name;
+register int len;
+int hashsize;
+{
+ register int r = 0;
+
+ while (len--)
+ r = HASHSTEP(r, *name++);
+
+ r = MAKE_POS(r) % hashsize;
+ return r;
+}
+
+/*
+ * Add new to the rightmost branch of LIST. This uses n^2 time, so we make
+ * a simple attempt at optimizing it.
+ */
+static NODE *
+append_right(list, new)
+NODE *list, *new;
+
+{
+ register NODE *oldlist;
+ static NODE *savefront = NULL, *savetail = NULL;
+
+ oldlist = list;
+ if (savefront == oldlist) {
+ savetail = savetail->rnode = new;
+ return oldlist;
+ } else
+ savefront = oldlist;
+ while (list->rnode != NULL)
+ list = list->rnode;
+ savetail = list->rnode = new;
+ return oldlist;
+}
+
+/*
+ * check if name is already installed; if so, it had better have Null value,
+ * in which case def is added as the value. Otherwise, install name with def
+ * as value.
+ */
+static void
+func_install(params, def)
+NODE *params;
+NODE *def;
+{
+ NODE *r;
+
+ pop_params(params->rnode);
+ pop_var(params, 0);
+ r = lookup(variables, params->param);
+ if (r != NULL) {
+ fatal("function name `%s' previously defined", params->param);
+ } else
+ (void) install(variables, params->param,
+ node(params, Node_func, def));
+}
+
+static void
+pop_var(np, freeit)
+NODE *np;
+int freeit;
+{
+ register char *bp;
+ register NODE *bucket, **save;
+ register int len;
+ char *name;
+
+ name = np->param;
+ for (bp = name; is_identchar(*bp); bp++)
+ ;
+ len = bp - name;
+ save = &(variables[hashf(name, len, HASHSIZE)]);
+ for (bucket = *save; bucket; bucket = bucket->hnext) {
+ if (len == bucket->hlength && STREQN(bucket->hname, name, len)) {
+ *save = bucket->hnext;
+ freenode(bucket);
+ free(bucket->hname);
+ if (freeit)
+ free(np->param);
+ return;
+ }
+ save = &(bucket->hnext);
+ }
+}
+
+static void
+pop_params(params)
+NODE *params;
+{
+ register NODE *np;
+
+ for (np = params; np != NULL; np = np->rnode)
+ pop_var(np, 1);
+}
+
+static NODE *
+make_param(name)
+char *name;
+{
+ NODE *r;
+
+ r = newnode(Node_param_list);
+ r->param = name;
+ r->rnode = NULL;
+ r->param_cnt = param_counter++;
+ return (install(variables, name, r));
+}
+
+/* Name points to a variable name. Make sure its in the symbol table */
+NODE *
+variable(name)
+char *name;
+{
+ register NODE *r;
+
+ if ((r = lookup(variables, name)) == NULL)
+ r = install(variables, name,
+ node(Nnull_string, Node_var, (NODE *) NULL));
+ return r;
+}
+short yyexca[] ={
+-1, 1,
+ 0, -1,
+ -2, 0,
+-1, 123,
+ 266, 0,
+ -2, 99,
+-1, 125,
+ 263, 0,
+ 60, 0,
+ 62, 0,
+ 124, 0,
+ -2, 103,
+-1, 126,
+ 263, 0,
+ 60, 0,
+ 62, 0,
+ 124, 0,
+ -2, 104,
+-1, 127,
+ 263, 0,
+ 60, 0,
+ 62, 0,
+ 124, 0,
+ -2, 105,
+-1, 244,
+ 266, 0,
+ -2, 116,
+-1, 246,
+ 263, 0,
+ -2, 118,
+ };
+# define YYNPROD 155
+# define YYLAST 1904
+short yyact[]={
+
+ 60, 86, 87, 13, 222, 120, 13, 231, 105, 287,
+ 4, 35, 43, 209, 20, 80, 181, 24, 89, 43,
+ 85, 17, 152, 24, 34, 24, 33, 197, 25, 96,
+ 260, 282, 34, 281, 33, 257, 25, 86, 87, 245,
+ 256, 57, 255, 58, 86, 87, 163, 162, 158, 124,
+ 80, 119, 61, 121, 122, 123, 170, 125, 126, 127,
+ 128, 22, 130, 196, 80, 98, 91, 168, 215, 80,
+ 61, 61, 20, 105, 61, 24, 22, 171, 156, 17,
+ 152, 182, 34, 24, 33, 225, 25, 96, 165, 199,
+ 34, 43, 33, 168, 25, 248, 259, 172, 43, 61,
+ 217, 266, 50, 63, 160, 51, 180, 141, 139, 180,
+ 180, 180, 110, 61, 109, 155, 108, 20, 164, 80,
+ 24, 157, 6, 95, 17, 154, 24, 34, 37, 33,
+ 96, 25, 107, 34, 84, 33, 44, 25, 39, 80,
+ 191, 80, 156, 43, 101, 89, 161, 75, 224, 99,
+ 102, 253, 103, 118, 100, 69, 145, 146, 156, 254,
+ 10, 216, 22, 5, 64, 218, 219, 221, 20, 1,
+ 48, 24, 138, 12, 0, 17, 20, 0, 34, 24,
+ 33, 0, 25, 17, 0, 0, 34, 187, 33, 229,
+ 25, 184, 185, 0, 43, 189, 0, 0, 236, 237,
+ 238, 98, 43, 232, 0, 0, 0, 22, 0, 64,
+ 0, 0, 20, 0, 0, 24, 180, 210, 95, 17,
+ 4, 24, 34, 0, 33, 96, 25, 4, 34, 198,
+ 33, 101, 0, 0, 261, 200, 99, 0, 43, 23,
+ 0, 100, 31, 32, 56, 23, 0, 23, 0, 0,
+ 31, 32, 206, 0, 0, 0, 0, 194, 22, 80,
+ 272, 0, 20, 156, 166, 24, 0, 249, 80, 17,
+ 29, 30, 34, 214, 33, 156, 25, 20, 29, 30,
+ 24, 0, 166, 270, 17, 80, 166, 34, 98, 33,
+ 0, 25, 80, 80, 80, 134, 28, 23, 263, 0,
+ 31, 32, 22, 43, 57, 23, 58, 59, 31, 32,
+ 81, 166, 78, 79, 70, 71, 72, 73, 74, 82,
+ 83, 76, 77, 0, 18, 201, 0, 0, 29, 30,
+ 26, 27, 0, 0, 0, 0, 29, 30, 183, 0,
+ 66, 28, 23, 269, 0, 31, 32, 28, 23, 0,
+ 0, 31, 32, 0, 0, 81, 88, 78, 79, 70,
+ 71, 72, 73, 74, 82, 83, 76, 77, 51, 18,
+ 0, 0, 0, 29, 30, 26, 27, 0, 275, 29,
+ 30, 26, 27, 0, 0, 65, 0, 0, 0, 0,
+ 285, 66, 28, 23, 0, 0, 31, 32, 0, 0,
+ 28, 23, 0, 62, 31, 32, 81, 0, 78, 79,
+ 70, 71, 72, 73, 74, 82, 83, 76, 77, 0,
+ 18, 0, 0, 0, 29, 30, 26, 27, 18, 0,
+ 0, 0, 29, 30, 26, 27, 28, 23, 0, 0,
+ 31, 32, 28, 23, 179, 0, 31, 32, 0, 133,
+ 81, 0, 78, 79, 70, 71, 72, 73, 74, 82,
+ 83, 76, 77, 0, 18, 0, 0, 132, 29, 30,
+ 26, 27, 137, 0, 29, 30, 26, 27, 0, 0,
+ 0, 0, 0, 195, 0, 20, 0, 23, 24, 0,
+ 31, 32, 17, 168, 0, 34, 0, 33, 11, 25,
+ 0, 28, 23, 0, 133, 31, 32, 56, 0, 46,
+ 54, 4, 57, 0, 58, 59, 0, 0, 29, 30,
+ 0, 0, 186, 0, 133, 0, 192, 0, 0, 18,
+ 55, 52, 53, 29, 30, 26, 27, 20, 115, 0,
+ 24, 0, 190, 117, 17, 0, 0, 34, 0, 33,
+ 0, 25, 0, 0, 251, 0, 0, 0, 20, 0,
+ 0, 24, 0, 43, 57, 17, 58, 59, 34, 0,
+ 33, 208, 25, 0, 20, 0, 51, 24, 0, 0,
+ 0, 17, 0, 0, 34, 0, 33, 68, 25, 0,
+ 14, 0, 0, 14, 0, 0, 0, 0, 14, 188,
+ 49, 57, 0, 58, 59, 0, 0, 0, 0, 0,
+ 20, 0, 0, 24, 0, 0, 0, 17, 0, 0,
+ 34, 61, 33, 0, 25, 0, 0, 14, 51, 0,
+ 0, 0, 14, 0, 0, 0, 0, 57, 0, 58,
+ 59, 0, 0, 0, 271, 0, 0, 147, 0, 0,
+ 0, 0, 0, 279, 20, 0, 0, 24, 0, 0,
+ 0, 17, 0, 2, 34, 51, 33, 0, 25, 36,
+ 289, 0, 0, 0, 0, 0, 0, 294, 295, 296,
+ 0, 57, 0, 58, 59, 0, 104, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 51, 0, 0, 0, 0, 116, 0, 0, 28,
+ 23, 0, 0, 31, 32, 56, 0, 0, 54, 0,
+ 0, 0, 0, 0, 0, 129, 0, 0, 135, 0,
+ 0, 136, 0, 0, 0, 140, 0, 18, 55, 52,
+ 53, 29, 30, 26, 27, 51, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 28, 23, 0, 0, 31, 32, 56, 0, 0,
+ 54, 0, 239, 241, 242, 243, 244, 0, 246, 247,
+ 0, 90, 28, 23, 0, 0, 31, 32, 0, 18,
+ 55, 52, 53, 29, 30, 26, 27, 0, 28, 23,
+ 0, 0, 31, 32, 56, 0, 0, 54, 0, 0,
+ 18, 0, 0, 0, 29, 30, 26, 27, 0, 0,
+ 265, 0, 0, 16, 0, 0, 18, 55, 52, 53,
+ 29, 30, 26, 27, 28, 23, 277, 0, 31, 32,
+ 56, 0, 92, 54, 97, 0, 0, 0, 97, 0,
+ 0, 0, 0, 111, 112, 0, 0, 97, 97, 0,
+ 0, 0, 18, 55, 52, 53, 29, 30, 26, 27,
+ 0, 0, 0, 0, 0, 0, 0, 0, 28, 23,
+ 0, 0, 31, 32, 56, 0, 0, 54, 0, 0,
+ 152, 0, 0, 24, 258, 0, 0, 96, 0, 149,
+ 34, 0, 33, 0, 25, 0, 18, 55, 52, 53,
+ 29, 30, 26, 27, 0, 264, 267, 0, 0, 97,
+ 207, 0, 97, 97, 97, 97, 97, 97, 20, 0,
+ 0, 24, 280, 0, 0, 17, 0, 284, 34, 0,
+ 33, 0, 25, 0, 92, 0, 0, 288, 0, 0,
+ 291, 292, 0, 0, 293, 57, 0, 58, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 152, 149, 0, 24, 92, 0, 97, 96, 0, 0,
+ 34, 0, 33, 0, 25, 0, 0, 20, 0, 0,
+ 24, 0, 0, 0, 17, 97, 0, 34, 0, 33,
+ 207, 25, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 57, 0, 58, 0, 0, 51,
+ 0, 0, 0, 0, 149, 149, 149, 149, 149, 0,
+ 149, 149, 149, 0, 20, 0, 0, 24, 0, 0,
+ 0, 17, 0, 0, 34, 0, 33, 0, 25, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 149, 0, 149, 149, 149, 149, 0,
+ 149, 149, 149, 20, 0, 0, 24, 0, 51, 0,
+ 17, 0, 0, 34, 0, 33, 0, 25, 149, 149,
+ 0, 0, 0, 152, 0, 0, 24, 0, 0, 0,
+ 96, 149, 0, 34, 0, 33, 0, 25, 0, 0,
+ 0, 0, 0, 0, 28, 23, 0, 0, 31, 32,
+ 206, 0, 0, 204, 22, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 21, 0, 0, 0, 0, 0,
+ 0, 0, 150, 205, 202, 203, 29, 30, 26, 27,
+ 0, 0, 28, 23, 0, 94, 31, 32, 56, 106,
+ 0, 54, 0, 22, 152, 0, 0, 24, 113, 114,
+ 0, 96, 0, 0, 34, 0, 33, 0, 25, 0,
+ 18, 55, 52, 0, 29, 30, 26, 27, 0, 0,
+ 0, 0, 0, 0, 28, 23, 0, 0, 31, 32,
+ 206, 0, 0, 204, 0, 0, 0, 0, 0, 0,
+ 153, 28, 23, 0, 0, 31, 32, 56, 0, 0,
+ 54, 0, 150, 205, 202, 203, 29, 30, 26, 27,
+ 94, 0, 0, 173, 174, 175, 176, 177, 178, 18,
+ 55, 0, 0, 29, 30, 26, 27, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 38, 28, 23,
+ 0, 0, 31, 32, 0, 0, 152, 0, 4, 24,
+ 8, 9, 0, 96, 0, 0, 34, 0, 33, 0,
+ 25, 169, 153, 0, 0, 15, 18, 94, 0, 0,
+ 29, 30, 26, 27, 0, 0, 7, 28, 23, 0,
+ 0, 31, 32, 0, 0, 0, 223, 0, 0, 8,
+ 9, 0, 0, 0, 0, 0, 0, 28, 23, 0,
+ 0, 31, 32, 206, 15, 18, 204, 0, 0, 29,
+ 30, 26, 27, 0, 0, 153, 153, 153, 153, 153,
+ 0, 153, 153, 153, 0, 150, 205, 202, 0, 29,
+ 30, 26, 27, 20, 0, 0, 24, 0, 0, 0,
+ 17, 152, 0, 34, 24, 33, 0, 25, 144, 0,
+ 167, 34, 0, 33, 153, 25, 153, 153, 153, 153,
+ 0, 153, 153, 153, 0, 0, 0, 0, 28, 23,
+ 0, 0, 31, 32, 206, 0, 0, 204, 0, 153,
+ 153, 20, 0, 0, 24, 0, 0, 0, 17, 0,
+ 0, 34, 153, 33, 0, 25, 150, 205, 0, 0,
+ 29, 30, 26, 27, 0, 0, 152, 0, 0, 24,
+ 0, 0, 0, 96, 0, 0, 34, 0, 33, 20,
+ 25, 0, 24, 0, 0, 0, 17, 0, 0, 34,
+ 0, 33, 0, 25, 0, 0, 0, 0, 0, 3,
+ 0, 0, 0, 0, 226, 0, 227, 228, 41, 41,
+ 41, 0, 0, 230, 0, 0, 0, 234, 0, 0,
+ 0, 0, 0, 0, 0, 19, 0, 0, 0, 240,
+ 28, 23, 0, 0, 31, 32, 0, 0, 252, 0,
+ 0, 0, 0, 0, 0, 0, 93, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 150, 0,
+ 0, 40, 29, 30, 26, 27, 0, 0, 0, 0,
+ 0, 45, 47, 41, 41, 268, 0, 0, 0, 0,
+ 41, 0, 273, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 283, 0, 0, 286, 0, 0,
+ 0, 151, 0, 0, 0, 0, 0, 290, 0, 0,
+ 0, 0, 0, 0, 0, 0, 220, 28, 23, 0,
+ 0, 31, 32, 0, 148, 28, 23, 0, 0, 31,
+ 32, 0, 0, 0, 0, 142, 143, 0, 0, 0,
+ 0, 0, 159, 0, 0, 18, 0, 0, 0, 29,
+ 30, 26, 27, 150, 41, 41, 0, 29, 30, 26,
+ 27, 0, 0, 0, 0, 28, 23, 0, 0, 31,
+ 32, 0, 0, 151, 0, 0, 67, 0, 211, 0,
+ 0, 0, 0, 0, 0, 42, 42, 42, 0, 0,
+ 28, 23, 0, 18, 31, 32, 41, 29, 30, 26,
+ 27, 0, 0, 28, 193, 0, 0, 31, 32, 0,
+ 0, 0, 0, 0, 41, 0, 212, 213, 150, 0,
+ 0, 0, 29, 30, 26, 27, 151, 151, 151, 151,
+ 151, 18, 151, 151, 151, 29, 30, 26, 27, 131,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 42, 42, 0, 0, 0, 0, 0, 42, 235, 0,
+ 0, 0, 0, 41, 0, 151, 41, 151, 151, 151,
+ 151, 0, 151, 151, 151, 0, 250, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 151, 151, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 151, 0, 0, 0, 0, 0, 131,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 276, 0, 0, 278, 0,
+ 0, 42, 42, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 233, 0, 42, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 42, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 262, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 274, 0,
+ 42, 0, 0, 42 };
+short yypact[]={
+
+-257,-1000,1040,-256,-1000,1001,-1000,-1000, -40, -40,
+ -47,-1000, -62, 577, 84,-1000,-245, 525, -13,-1000,
+ 90, 107,-257, -18, 185,-1000, 76, 74, 72, -13,
+ -13,-1000,-1000, 185, 185,-1000,-1000,-1000,-1000, -62,
+-1000,-256,-257,-1000, -62,-1000,-1000,-1000,-1000, 135,
+1368,-280,1368,1368,1368,-209,1368,1368,1368,1368,
+ 229,-257, 32, 39,-257,-1000,-1000,-257, 84,-1000,
+ 68,-257, 67, -40, -40,1328,-1000,1368,-1000,-210,
+ 244, 64,-1000,-1000,-211,-1000,-1000,-1000, 26, 452,
+-1000, 17,-1000,-1000, -29, 185,1368,-288, 185, 185,
+ 185, 185, 185, 185,-1000, 525,-1000,-243, 525, 525,
+ 525,-1000,-1000, -29, -29,-1000,-1000,-1000, 39, 621,
+ -13, 954, 895, -19,-1000, 229, 229, 229, 541,-1000,
+-1000,-1000, 32,-1000,-1000,-1000,-1000,-1000, 39,1368,
+ 179,1406,-1000,-1000, 525, -35, 69, 937,-1000,-252,
+ -13,-1000, 90, 107, -40, -40, 621,1368, -23,-1000,
+1368, 60,-1000,-1000,1368,1320,1368,-282,-1000,-1000,
+-1000, 185, 452, -29, -29, -29, -29, 194, 194, 55,
+ 621, 38, 52, 30, 52, 52,-1000,-1000,1368,-1000,
+-1000, 452,-268, -83, 32, 26, -40,1368,1368,1368,
+1233,1393,1393,1393,1393,-219,1393,1393, 47,-1000,
+ 17,-1000,-1000,-1000, -40, 525, 452,-216, 621, 621,
+-1000, 621,-223, 107,-1000,-1000,-1000,-1000,-1000, 621,
+-257, 56,-228, 143, -35,-1000, 621, 621, 621, 937,
+-1000, 937,1131,1060, -11,-1000, 47, 857,1393,-1000,
+-1000, 8,-257, 52, 27,-1000,-1000,-1000, 179,1368,
+ 52, 504,1368, -40,1393, 937, -40, 179,-257,-225,
+-1000,-1000, 452,-257,1368, 52,-1000, 937,-1000,-263,
+-1000,-1000,-1000,-257, 179, 52,-257,-257,-1000,-1000,
+-257, 179, 179, 179,-1000,-1000,-1000 };
+short yypgo[]={
+
+ 0, 173, 170, 571, 0, 169, 163, 122,1134, 160,
+ 498, 823, 159, 157, 156, 338, 81, 103, 385, 155,
+ 151, 115, 66,1485, 56, 63,1281, 88,1459, 663,
+ 147, 146, 138, 136,1521, 134, 587, 403, 132, 62,
+1636, 125, 121, 118, 95 };
+short yyr1[]={
+
+ 0, 5, 6, 6, 6, 6, 32, 7, 33, 7,
+ 7, 7, 7, 7, 7, 7, 31, 31, 35, 1,
+ 2, 9, 9, 38, 23, 10, 10, 17, 17, 17,
+ 17, 34, 34, 18, 18, 18, 18, 18, 18, 18,
+ 18, 18, 18, 18, 18, 18, 41, 18, 18, 42,
+ 18, 18, 18, 30, 30, 19, 19, 28, 28, 29,
+ 29, 24, 24, 25, 25, 25, 25, 20, 20, 12,
+ 12, 12, 12, 12, 21, 21, 14, 14, 13, 13,
+ 13, 13, 13, 13, 16, 16, 15, 15, 15, 15,
+ 15, 15, 43, 4, 4, 4, 4, 4, 4, 4,
+ 4, 4, 4, 4, 4, 4, 4, 4, 4, 44,
+ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
+ 3, 3, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
+ 8, 8, 8, 22, 22, 11, 11, 11, 36, 37,
+ 26, 39, 39, 40, 27 };
+short yyr2[]={
+
+ 0, 3, 1, 2, 1, 2, 0, 3, 0, 3,
+ 2, 2, 2, 1, 2, 2, 1, 1, 0, 7,
+ 3, 1, 3, 0, 4, 3, 4, 1, 2, 1,
+ 2, 1, 2, 2, 2, 3, 1, 6, 8, 8,
+ 10, 9, 2, 2, 6, 4, 0, 3, 3, 0,
+ 4, 6, 2, 1, 1, 6, 9, 1, 2, 0,
+ 1, 0, 2, 0, 2, 2, 2, 0, 1, 1,
+ 3, 1, 2, 3, 0, 1, 0, 1, 1, 3,
+ 1, 2, 3, 3, 0, 1, 1, 3, 1, 2,
+ 3, 3, 0, 4, 5, 4, 3, 3, 3, 3,
+ 1, 2, 3, 3, 3, 3, 5, 1, 2, 0,
+ 4, 3, 3, 3, 1, 2, 3, 3, 3, 5,
+ 1, 2, 2, 3, 4, 4, 1, 4, 2, 2,
+ 2, 2, 1, 1, 1, 3, 3, 3, 3, 3,
+ 3, 2, 2, 0, 1, 1, 4, 2, 2, 2,
+ 1, 0, 1, 1, 2 };
+short yychk[]={
+
+-1000, -5, -29, -28, 267, -6, -7, 256, 269, 270,
+ -9, -10, -1, -4, -36, 284, -11, 40, 285, -23,
+ 33, -8, 123, 258, 36, 47, 291, 292, 257, 289,
+ 290, 261, 262, 45, 43, 267, -29, -7, 256, -32,
+ -34, -28, -40, 59, -33, -34, -10, -34, -2, -36,
+ -27, 124, 287, 288, 266, 286, 263, 60, 62, 63,
+ -4, 44, -37, -17, 125, -18, 256, -40, -36, -19,
+ 275, 276, 277, 278, 279, -30, 282, 283, 273, 274,
+ -4, 271, 280, 281, -35, 265, 289, 290, -15, -4,
+ 256, -22, -11, -23, -8, 33, 40, -11, 94, 42,
+ 47, 37, 43, 45, -29, 91, -8, -38, 40, 40,
+ 40, -11, -11, -8, -8, -10, -29, -10, -17, -4,
+ 285, -4, -4, -4, 258, -4, -4, -4, -4, -29,
+ -39, -40, -37, -18, 256, -29, -29, -37, -17, 40,
+ -29, 40, -34, -34, 40, -14, -13, -3, 256, -11,
+ 285, -23, 33, -8, -41, -21, -4, -42, 258, -34,
+ 40, -31, 258, 257, -43, -27, 256, -26, 41, -26,
+ -24, 60, -4, -8, -8, -8, -8, -8, -8, -15,
+ -4, 259, -16, -15, -16, -16, -37, -22, 58, -39,
+ -37, -4, -18, 258, -21, -15, -25, 62, 264, 124,
+ -27, 256, 287, 288, 266, 286, 263, 63, -3, 265,
+ -22, -23, -34, -34, -21, 91, -4, 40, -4, -4,
+ 256, -4, 286, -8, 93, 47, -26, -26, -26, -4,
+ -26, 275, 286, -40, -26, -34, -4, -4, -4, -3,
+ 256, -3, -3, -3, -3, 258, -3, -3, -44, -24,
+ -34, -15, -26, -20, -12, 258, 256, 258, -29, 40,
+ 258, -4, -40, -25, 58, -3, 93, -29, -26, -27,
+ 256, -18, -4, -26, -40, -21, -34, -3, -34, -18,
+ -29, 258, 256, -26, -29, -21, -26, 272, -29, -18,
+ -26, -29, -29, -29, -18, -18, -18 };
+short yydef[]={
+
+ 59, -2, 0, 60, 57, 59, 2, 4, 6, 8,
+ 0, 13, 0, 21, 0, 18, 132, 0, 143, 100,
+ 0, 107, 59, 145, 0, 23, 0, 126, 0, 0,
+ 0, 133, 134, 0, 0, 58, 1, 3, 5, 0,
+ 10, 31, 59, 153, 0, 11, 12, 14, 15, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 108, 59, 151, 0, 59, 27, 29, 59, 0, 36,
+ 0, 59, 0, 0, 0, 76, 46, 74, 49, 0,
+ 0, 0, 53, 54, 0, 92, 130, 131, 0, 86,
+ 88, 61, 144, 101, 122, 0, 0, 132, 0, 0,
+ 0, 0, 0, 0, 148, 0, 147, 0, 84, 84,
+ 84, 128, 129, 141, 142, 7, 32, 9, 0, 22,
+ 143, 97, 98, -2, 102, -2, -2, -2, 0, 154,
+ 25, 152, 151, 28, 30, 149, 33, 34, 0, 0,
+ 0, 74, 42, 43, 0, 63, 77, 78, 80, 132,
+ 143, 114, 0, 120, 0, 0, 75, 74, 0, 52,
+ 0, 0, 16, 17, 0, 0, 89, 0, 150, 123,
+ 96, 0, 0, 135, 136, 137, 138, 139, 140, 0,
+ 86, 0, 0, 85, 0, 0, 20, 95, 0, 26,
+ 35, 0, 0, 145, 0, 0, 0, 0, 0, 0,
+ 0, 81, 0, 0, 0, 0, 0, 0, 121, 109,
+ 61, 115, 47, 48, 0, 0, 0, 67, 93, 87,
+ 91, 90, 0, 62, 146, 24, 124, 125, 127, 106,
+ 59, 0, 0, 0, 63, 45, 64, 65, 66, 79,
+ 83, 82, 111, 112, -2, 117, -2, 0, 0, 113,
+ 50, 0, 59, 0, 68, 69, 71, 94, 0, 0,
+ 0, 0, 74, 0, 0, 110, 0, 0, 59, 0,
+ 72, 37, 0, 59, 74, 0, 44, 119, 51, 55,
+ 19, 70, 73, 59, 0, 0, 59, 59, 38, 39,
+ 59, 0, 0, 0, 41, 56, 40 };
+#ifndef lint
+static char yaccpar_sccsid[] = "@(#)yaccpar 4.1 (Berkeley) 2/11/83";
+#endif not lint
+
+#
+# define YYFLAG -1000
+# define YYERROR goto yyerrlab
+# define YYACCEPT return(0)
+# define YYABORT return(1)
+
+/* parser for yacc output */
+
+#ifdef YYDEBUG
+int yydebug = 0; /* 1 for debugging */
+static char *yydisplay();
+#endif
+YYSTYPE yyv[YYMAXDEPTH]; /* where the values are stored */
+int yychar = -1; /* current input token number */
+int yynerrs = 0; /* number of errors */
+short yyerrflag = 0; /* error recovery flag */
+
+yyparse() {
+
+ short yys[YYMAXDEPTH];
+ short yyj, yym;
+ register YYSTYPE *yypvt;
+ register short yystate, *yyps, yyn;
+ register YYSTYPE *yypv;
+ register short *yyxi;
+
+ yystate = 0;
+ yychar = -1;
+ yynerrs = 0;
+ yyerrflag = 0;
+ yyps= &yys[-1];
+ yypv= &yyv[-1];
+
+ yystack: /* put a state and value onto the stack */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf( "[yydebug] push state %d\n", yystate);
+#endif
+ if( ++yyps> &yys[YYMAXDEPTH] ) { yyerror( "yacc stack overflow" ); return(1); }
+ *yyps = yystate;
+ ++yypv;
+ *yypv = yyval;
+
+ yynewstate:
+
+ yyn = yypact[yystate];
+
+ if( yyn<= YYFLAG ) goto yydefault; /* simple state */
+
+ yyyylex();
+ if( (yyn += yychar)<0 || yyn >= YYLAST ) goto yydefault;
+
+ if( yychk[ yyn=yyact[ yyn ] ] == yychar ){ /* valid shift */
+ yychar = -1;
+ yyval = yylval;
+ yystate = yyn;
+ if( yyerrflag > 0 ) --yyerrflag;
+ goto yystack;
+ }
+
+ yydefault:
+ /* default state action */
+
+ if( (yyn=yydef[yystate]) == -2 ) {
+ yyyylex();
+ /* look through exception table */
+
+ for( yyxi=yyexca; (*yyxi!= (-1)) || (yyxi[1]!=yystate) ; yyxi += 2 ) ; /* VOID */
+
+ while( *(yyxi+=2) >= 0 ){
+ if( *yyxi == yychar ) break;
+ }
+ if( (yyn = yyxi[1]) < 0 ) return(0); /* accept */
+ }
+
+ if( yyn == 0 ){ /* error */
+ /* error ... attempt to resume parsing */
+
+ switch( yyerrflag ){
+
+ case 0: /* brand new error */
+#ifdef YYIMPROVE
+ if ((yyn = yypact[yystate]) > YYFLAG && yyn < YYLAST) {
+ register int x;
+
+ for (x = yyn>0 ? yyn : 0; x < YYLAST; ++x)
+ if (yychk[yyact[x]] == x - yyn
+ && x - yyn != YYERRCODE)
+ yyerror(0, yydisplay(x - yyn));
+ }
+ yyerror(0,0);
+#else
+ yyerror( "syntax error" );
+#endif
+ yyerrlab:
+ ++yynerrs;
+
+ case 1:
+ case 2: /* incompletely recovered error ... try again */
+
+ yyerrflag = 3;
+
+ /* find a state where "error" is a legal shift action */
+
+ while ( yyps >= yys ) {
+ yyn = yypact[*yyps] + YYERRCODE;
+ if( yyn>= 0 && yyn < YYLAST && yychk[yyact[yyn]] == YYERRCODE ){
+ yystate = yyact[yyn]; /* simulate a shift of "error" */
+ goto yystack;
+ }
+ yyn = yypact[*yyps];
+
+ /* the current yyps has no shift onn "error", pop stack */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf( "[yydebug] recovery pops %d, uncovers %d\n", *yyps, yyps[-1] );
+#endif
+ --yyps;
+ --yypv;
+ }
+
+ /* there is no state on the stack with an error shift ... abort */
+
+ yyabort:
+ return(1);
+
+
+ case 3: /* no shift yet; clobber input char */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf( "[yydebug] recovery discards %s\n", yydisplay(yychar) );
+#endif
+
+ if( yychar == 0 ) goto yyabort; /* don't discard EOF, quit */
+ yychar = -1;
+ goto yynewstate; /* try again in the same state */
+
+ }
+
+ }
+
+ /* reduction by production yyn */
+
+#ifdef YYDEBUG
+ if( yydebug ) printf("[yydebug] reduce by (%d), uncover %d\n",yyn, yyr1[yyn]);
+#endif
+ yyps -= yyr2[yyn];
+ yypvt = yypv;
+ yypv -= yyr2[yyn];
+ yyval = yypv[1];
+ yym=yyn;
+ /* consult goto table to find next state */
+ yyn = yyr1[yyn];
+ yyj = yypgo[yyn] + *yyps + 1;
+ if( yyj>=YYLAST || yychk[ yystate = yyact[yyj] ] != -yyn ) yystate = yyact[yypgo[yyn]];
+ switch(yym){
+
+case 1:
+# line 137 "awk.y"
+{ expression_value = yypvt[-1].nodeval; } break;
+case 2:
+# line 142 "awk.y"
+{
+ if (yypvt[-0].nodeval != NULL)
+ yyval.nodeval = yypvt[-0].nodeval;
+ else
+ yyval.nodeval = NULL;
+ yyerrok;
+ } break;
+case 3:
+# line 151 "awk.y"
+{
+ if (yypvt[-0].nodeval == NULL)
+ yyval.nodeval = yypvt[-1].nodeval;
+ else if (yypvt[-1].nodeval == NULL)
+ yyval.nodeval = yypvt[-0].nodeval;
+ else {
+ if (yypvt[-1].nodeval->type != Node_rule_list)
+ yypvt[-1].nodeval = node(yypvt[-1].nodeval, Node_rule_list,
+ (NODE*)NULL);
+ yyval.nodeval = append_right (yypvt[-1].nodeval,
+ node(yypvt[-0].nodeval, Node_rule_list,(NODE *) NULL));
+ }
+ yyerrok;
+ } break;
+case 4:
+# line 165 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 5:
+# line 166 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 6:
+# line 170 "awk.y"
+{ io_allowed = 0; } break;
+case 7:
+# line 172 "awk.y"
+{
+ if (begin_block) {
+ if (begin_block->type != Node_rule_list)
+ begin_block = node(begin_block, Node_rule_list,
+ (NODE *)NULL);
+ append_right (begin_block, node(
+ node((NODE *)NULL, Node_rule_node, yypvt[-0].nodeval),
+ Node_rule_list, (NODE *)NULL) );
+ } else
+ begin_block = node((NODE *)NULL, Node_rule_node, yypvt[-0].nodeval);
+ yyval.nodeval = NULL;
+ io_allowed = 1;
+ yyerrok;
+ } break;
+case 8:
+# line 186 "awk.y"
+{ io_allowed = 0; } break;
+case 9:
+# line 188 "awk.y"
+{
+ if (end_block) {
+ if (end_block->type != Node_rule_list)
+ end_block = node(end_block, Node_rule_list,
+ (NODE *)NULL);
+ append_right (end_block, node(
+ node((NODE *)NULL, Node_rule_node, yypvt[-0].nodeval),
+ Node_rule_list, (NODE *)NULL));
+ } else
+ end_block = node((NODE *)NULL, Node_rule_node, yypvt[-0].nodeval);
+ yyval.nodeval = NULL;
+ io_allowed = 1;
+ yyerrok;
+ } break;
+case 10:
+# line 203 "awk.y"
+{
+ msg ("error near line %d: BEGIN blocks must have an action part", lineno);
+ errcount++;
+ yyerrok;
+ } break;
+case 11:
+# line 209 "awk.y"
+{
+ msg ("error near line %d: END blocks must have an action part", lineno);
+ errcount++;
+ yyerrok;
+ } break;
+case 12:
+# line 215 "awk.y"
+{ yyval.nodeval = node (yypvt[-1].nodeval, Node_rule_node, yypvt[-0].nodeval); yyerrok; } break;
+case 13:
+# line 217 "awk.y"
+{ yyval.nodeval = node ((NODE *)NULL, Node_rule_node, yypvt[-0].nodeval); yyerrok; } break;
+case 14:
+# line 219 "awk.y"
+{ if(yypvt[-1].nodeval) yyval.nodeval = node (yypvt[-1].nodeval, Node_rule_node, (NODE *)NULL); yyerrok; } break;
+case 15:
+# line 221 "awk.y"
+{
+ func_install(yypvt[-1].nodeval, yypvt[-0].nodeval);
+ yyval.nodeval = NULL;
+ yyerrok;
+ } break;
+case 16:
+# line 230 "awk.y"
+{ yyval.sval = yypvt[-0].sval; } break;
+case 17:
+# line 232 "awk.y"
+{ yyval.sval = yypvt[-0].sval; } break;
+case 18:
+# line 237 "awk.y"
+{
+ param_counter = 0;
+ } break;
+case 19:
+# line 241 "awk.y"
+{
+ yyval.nodeval = append_right(make_param(yypvt[-4].sval), yypvt[-2].nodeval);
+ can_return = 1;
+ } break;
+case 20:
+# line 249 "awk.y"
+{
+ yyval.nodeval = yypvt[-1].nodeval;
+ can_return = 0;
+ } break;
+case 21:
+# line 258 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 22:
+# line 260 "awk.y"
+{ yyval.nodeval = mkrangenode ( node(yypvt[-2].nodeval, Node_cond_pair, yypvt[-0].nodeval) ); } break;
+case 23:
+# line 269 "awk.y"
+{ ++want_regexp; } break;
+case 24:
+# line 271 "awk.y"
+{
+ want_regexp = 0;
+ yyval.nodeval = node((NODE *)NULL,Node_regex,(NODE *)mk_re_parse(yypvt[-1].sval, 0));
+ yyval.nodeval -> re_case = 0;
+ emalloc (yyval.nodeval -> re_text, char *, strlen(yypvt[-1].sval)+1, "regexp");
+ strcpy (yyval.nodeval -> re_text, yypvt[-1].sval);
+ } break;
+case 25:
+# line 282 "awk.y"
+{
+ /* empty actions are different from missing actions */
+ yyval.nodeval = node ((NODE *) NULL, Node_illegal, (NODE *) NULL);
+ } break;
+case 26:
+# line 287 "awk.y"
+{ yyval.nodeval = yypvt[-2].nodeval ; } break;
+case 27:
+# line 292 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 28:
+# line 294 "awk.y"
+{
+ if (yypvt[-1].nodeval == NULL || yypvt[-1].nodeval->type != Node_statement_list)
+ yypvt[-1].nodeval = node(yypvt[-1].nodeval, Node_statement_list,(NODE *)NULL);
+ yyval.nodeval = append_right(yypvt[-1].nodeval,
+ node( yypvt[-0].nodeval, Node_statement_list, (NODE *)NULL));
+ yyerrok;
+ } break;
+case 29:
+# line 302 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 30:
+# line 304 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 31:
+# line 309 "awk.y"
+{ yyval.nodetypeval = Node_illegal; } break;
+case 32:
+# line 311 "awk.y"
+{ yyval.nodetypeval = Node_illegal; } break;
+case 33:
+# line 317 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 34:
+# line 319 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 35:
+# line 321 "awk.y"
+{ yyval.nodeval = yypvt[-1].nodeval; } break;
+case 36:
+# line 323 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 37:
+# line 325 "awk.y"
+{ yyval.nodeval = node (yypvt[-3].nodeval, Node_K_while, yypvt[-0].nodeval); } break;
+case 38:
+# line 327 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_K_do, yypvt[-5].nodeval); } break;
+case 39:
+# line 329 "awk.y"
+{
+ yyval.nodeval = node (yypvt[-0].nodeval, Node_K_arrayfor, make_for_loop(variable(yypvt[-5].sval),
+ (NODE *)NULL, variable(yypvt[-3].sval)));
+ } break;
+case 40:
+# line 334 "awk.y"
+{
+ yyval.nodeval = node(yypvt[-0].nodeval, Node_K_for, (NODE *)make_for_loop(yypvt[-7].nodeval, yypvt[-5].nodeval, yypvt[-3].nodeval));
+ } break;
+case 41:
+# line 338 "awk.y"
+{
+ yyval.nodeval = node (yypvt[-0].nodeval, Node_K_for,
+ (NODE *)make_for_loop(yypvt[-6].nodeval, (NODE *)NULL, yypvt[-3].nodeval));
+ } break;
+case 42:
+# line 344 "awk.y"
+{ yyval.nodeval = node ((NODE *)NULL, Node_K_break, (NODE *)NULL); } break;
+case 43:
+# line 347 "awk.y"
+{ yyval.nodeval = node ((NODE *)NULL, Node_K_continue, (NODE *)NULL); } break;
+case 44:
+# line 349 "awk.y"
+{ yyval.nodeval = node (yypvt[-3].nodeval, yypvt[-5].nodetypeval, yypvt[-1].nodeval); } break;
+case 45:
+# line 351 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, yypvt[-3].nodetypeval, yypvt[-1].nodeval); } break;
+case 46:
+# line 353 "awk.y"
+{ if (! io_allowed) yyerror("next used in BEGIN or END action"); } break;
+case 47:
+# line 355 "awk.y"
+{ yyval.nodeval = node ((NODE *)NULL, Node_K_next, (NODE *)NULL); } break;
+case 48:
+# line 357 "awk.y"
+{ yyval.nodeval = node (yypvt[-1].nodeval, Node_K_exit, (NODE *)NULL); } break;
+case 49:
+# line 359 "awk.y"
+{ if (! can_return) yyerror("return used outside function context"); } break;
+case 50:
+# line 361 "awk.y"
+{ yyval.nodeval = node (yypvt[-1].nodeval, Node_K_return, (NODE *)NULL); } break;
+case 51:
+# line 363 "awk.y"
+{ yyval.nodeval = node (variable(yypvt[-4].sval), Node_K_delete, yypvt[-2].nodeval); } break;
+case 52:
+# line 365 "awk.y"
+{ yyval.nodeval = yypvt[-1].nodeval; } break;
+case 53:
+# line 370 "awk.y"
+{ yyval.nodetypeval = yypvt[-0].nodetypeval; } break;
+case 54:
+# line 372 "awk.y"
+{ yyval.nodetypeval = yypvt[-0].nodetypeval; } break;
+case 55:
+# line 377 "awk.y"
+{
+ yyval.nodeval = node(yypvt[-3].nodeval, Node_K_if,
+ node(yypvt[-0].nodeval, Node_if_branches, (NODE *)NULL));
+ } break;
+case 56:
+# line 383 "awk.y"
+{ yyval.nodeval = node (yypvt[-6].nodeval, Node_K_if,
+ node (yypvt[-3].nodeval, Node_if_branches, yypvt[-0].nodeval)); } break;
+case 57:
+# line 389 "awk.y"
+{ yyval.nodetypeval = NULL; } break;
+case 58:
+# line 391 "awk.y"
+{ yyval.nodetypeval = NULL; } break;
+case 59:
+# line 396 "awk.y"
+{ yyval.nodetypeval = NULL; } break;
+case 60:
+# line 398 "awk.y"
+{ yyval.nodetypeval = NULL; } break;
+case 61:
+# line 403 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 62:
+# line 405 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_redirect_input, (NODE *)NULL); } break;
+case 63:
+# line 410 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 64:
+# line 412 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_redirect_output, (NODE *)NULL); } break;
+case 65:
+# line 414 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_redirect_append, (NODE *)NULL); } break;
+case 66:
+# line 416 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_redirect_pipe, (NODE *)NULL); } break;
+case 67:
+# line 421 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 68:
+# line 423 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 69:
+# line 428 "awk.y"
+{ yyval.nodeval = make_param(yypvt[-0].sval); } break;
+case 70:
+# line 430 "awk.y"
+{ yyval.nodeval = append_right(yypvt[-2].nodeval, make_param(yypvt[-0].sval)); yyerrok; } break;
+case 71:
+# line 432 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 72:
+# line 434 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 73:
+# line 436 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 74:
+# line 442 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 75:
+# line 444 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 76:
+# line 449 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 77:
+# line 451 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 78:
+# line 456 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_expression_list, (NODE *)NULL); } break;
+case 79:
+# line 458 "awk.y"
+{
+ yyval.nodeval = append_right(yypvt[-2].nodeval,
+ node( yypvt[-0].nodeval, Node_expression_list, (NODE *)NULL));
+ yyerrok;
+ } break;
+case 80:
+# line 464 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 81:
+# line 466 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 82:
+# line 468 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 83:
+# line 470 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 84:
+# line 475 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 85:
+# line 477 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 86:
+# line 482 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_expression_list, (NODE *)NULL); } break;
+case 87:
+# line 484 "awk.y"
+{
+ yyval.nodeval = append_right(yypvt[-2].nodeval,
+ node( yypvt[-0].nodeval, Node_expression_list, (NODE *)NULL));
+ yyerrok;
+ } break;
+case 88:
+# line 490 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 89:
+# line 492 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 90:
+# line 494 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 91:
+# line 496 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 92:
+# line 501 "awk.y"
+{ want_assign = 0; } break;
+case 93:
+# line 503 "awk.y"
+{ yyval.nodeval = node (yypvt[-3].nodeval, yypvt[-2].nodetypeval, yypvt[-0].nodeval); } break;
+case 94:
+# line 505 "awk.y"
+{ yyval.nodeval = node (variable(yypvt[-0].sval), Node_in_array, yypvt[-3].nodeval); } break;
+case 95:
+# line 507 "awk.y"
+{
+ yyval.nodeval = node (yypvt[-0].nodeval, Node_K_getline,
+ node (yypvt[-3].nodeval, Node_redirect_pipein, (NODE *)NULL));
+ } break;
+case 96:
+# line 512 "awk.y"
+{
+ /* "too painful to do right" */
+ /*
+ if (! io_allowed && $3 == NULL)
+ yyerror("non-redirected getline illegal inside BEGIN or END action");
+ */
+ yyval.nodeval = node (yypvt[-1].nodeval, Node_K_getline, yypvt[-0].nodeval);
+ } break;
+case 97:
+# line 521 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_and, yypvt[-0].nodeval); } break;
+case 98:
+# line 523 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_or, yypvt[-0].nodeval); } break;
+case 99:
+# line 525 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, yypvt[-1].nodetypeval, yypvt[-0].nodeval); } break;
+case 100:
+# line 527 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 101:
+# line 529 "awk.y"
+{ yyval.nodeval = node((NODE *) NULL, Node_nomatch, yypvt[-0].nodeval); } break;
+case 102:
+# line 531 "awk.y"
+{ yyval.nodeval = node (variable(yypvt[-0].sval), Node_in_array, yypvt[-2].nodeval); } break;
+case 103:
+# line 533 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, yypvt[-1].nodetypeval, yypvt[-0].nodeval); } break;
+case 104:
+# line 535 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_less, yypvt[-0].nodeval); } break;
+case 105:
+# line 537 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_greater, yypvt[-0].nodeval); } break;
+case 106:
+# line 539 "awk.y"
+{ yyval.nodeval = node(yypvt[-4].nodeval, Node_cond_exp, node(yypvt[-2].nodeval, Node_if_branches, yypvt[-0].nodeval));} break;
+case 107:
+# line 541 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 108:
+# line 543 "awk.y"
+{ yyval.nodeval = node (yypvt[-1].nodeval, Node_concat, yypvt[-0].nodeval); } break;
+case 109:
+# line 548 "awk.y"
+{ want_assign = 0; } break;
+case 110:
+# line 550 "awk.y"
+{ yyval.nodeval = node (yypvt[-3].nodeval, yypvt[-2].nodetypeval, yypvt[-0].nodeval); } break;
+case 111:
+# line 552 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_and, yypvt[-0].nodeval); } break;
+case 112:
+# line 554 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_or, yypvt[-0].nodeval); } break;
+case 113:
+# line 556 "awk.y"
+{
+ /* "too painful to do right" */
+ /*
+ if (! io_allowed && $3 == NULL)
+ yyerror("non-redirected getline illegal inside BEGIN or END action");
+ */
+ yyval.nodeval = node (yypvt[-1].nodeval, Node_K_getline, yypvt[-0].nodeval);
+ } break;
+case 114:
+# line 565 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 115:
+# line 567 "awk.y"
+{ yyval.nodeval = node((NODE *) NULL, Node_nomatch, yypvt[-0].nodeval); } break;
+case 116:
+# line 569 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, yypvt[-1].nodetypeval, yypvt[-0].nodeval); } break;
+case 117:
+# line 571 "awk.y"
+{ yyval.nodeval = node (variable(yypvt[-0].sval), Node_in_array, yypvt[-2].nodeval); } break;
+case 118:
+# line 573 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, yypvt[-1].nodetypeval, yypvt[-0].nodeval); } break;
+case 119:
+# line 575 "awk.y"
+{ yyval.nodeval = node(yypvt[-4].nodeval, Node_cond_exp, node(yypvt[-2].nodeval, Node_if_branches, yypvt[-0].nodeval));} break;
+case 120:
+# line 577 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 121:
+# line 579 "awk.y"
+{ yyval.nodeval = node (yypvt[-1].nodeval, Node_concat, yypvt[-0].nodeval); } break;
+case 122:
+# line 584 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_not,(NODE *) NULL); } break;
+case 123:
+# line 586 "awk.y"
+{ yyval.nodeval = yypvt[-1].nodeval; } break;
+case 124:
+# line 588 "awk.y"
+{ yyval.nodeval = snode (yypvt[-1].nodeval, Node_builtin, yypvt[-3].ptrval); } break;
+case 125:
+# line 590 "awk.y"
+{ yyval.nodeval = snode (yypvt[-1].nodeval, Node_builtin, yypvt[-3].ptrval); } break;
+case 126:
+# line 592 "awk.y"
+{ yyval.nodeval = snode ((NODE *)NULL, Node_builtin, yypvt[-0].ptrval); } break;
+case 127:
+# line 594 "awk.y"
+{
+ yyval.nodeval = node (yypvt[-1].nodeval, Node_func_call, make_string(yypvt[-3].sval, strlen(yypvt[-3].sval)));
+ } break;
+case 128:
+# line 598 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_preincrement, (NODE *)NULL); } break;
+case 129:
+# line 600 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_predecrement, (NODE *)NULL); } break;
+case 130:
+# line 602 "awk.y"
+{ yyval.nodeval = node (yypvt[-1].nodeval, Node_postincrement, (NODE *)NULL); } break;
+case 131:
+# line 604 "awk.y"
+{ yyval.nodeval = node (yypvt[-1].nodeval, Node_postdecrement, (NODE *)NULL); } break;
+case 132:
+# line 606 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 133:
+# line 608 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 134:
+# line 610 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 135:
+# line 614 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_exp, yypvt[-0].nodeval); } break;
+case 136:
+# line 616 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_times, yypvt[-0].nodeval); } break;
+case 137:
+# line 618 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_quotient, yypvt[-0].nodeval); } break;
+case 138:
+# line 620 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_mod, yypvt[-0].nodeval); } break;
+case 139:
+# line 622 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_plus, yypvt[-0].nodeval); } break;
+case 140:
+# line 624 "awk.y"
+{ yyval.nodeval = node (yypvt[-2].nodeval, Node_minus, yypvt[-0].nodeval); } break;
+case 141:
+# line 626 "awk.y"
+{ yyval.nodeval = node (yypvt[-0].nodeval, Node_unary_minus, (NODE *)NULL); } break;
+case 142:
+# line 628 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 143:
+# line 633 "awk.y"
+{ yyval.nodeval = NULL; } break;
+case 144:
+# line 635 "awk.y"
+{ yyval.nodeval = yypvt[-0].nodeval; } break;
+case 145:
+# line 640 "awk.y"
+{ want_assign = 1; yyval.nodeval = variable (yypvt[-0].sval); } break;
+case 146:
+# line 642 "awk.y"
+{ want_assign = 1; yyval.nodeval = node (variable(yypvt[-3].sval), Node_subscript, yypvt[-1].nodeval); } break;
+case 147:
+# line 644 "awk.y"
+{ want_assign = 1; yyval.nodeval = node (yypvt[-0].nodeval, Node_field_spec, (NODE *)NULL); } break;
+case 149:
+# line 652 "awk.y"
+{ yyerrok; } break;
+case 150:
+# line 656 "awk.y"
+{ yyval.nodetypeval = Node_illegal; yyerrok; } break;
+case 153:
+# line 665 "awk.y"
+{ yyerrok; } break;
+case 154:
+# line 668 "awk.y"
+{ yyval.nodetypeval = Node_illegal; yyerrok; } break;
+ }
+ goto yystack; /* stack new state and value */
+
+ }
+
+#include <ctype.h>
+
+#define DIM(x) (sizeof(x) / sizeof x[0])
+
+static char *
+yydisplay(ch)
+register int ch;
+{
+ static char buf[15];
+ static char *token[] = {
+# include "y.tok.h" /* token names */
+ 0
+ };
+
+ switch (ch) {
+ case 0:
+ return "[end of file]";
+ case YYERRCODE:
+ return "[error]";
+ case '\b':
+ return "'\\b'";
+ case '\f':
+ return "'\\f'";
+ case '\n':
+ return "'\\n'";
+ case '\r':
+ return "'\\r'";
+ case '\t':
+ return "'\\t'";
+ }
+
+ if (ch > 256 && ch < 256 + DIM(token))
+ return token[ch - 257];
+ if (isascii(ch) && isprint(ch))
+ sprintf(buf, "'%c'", ch);
+ else if (ch < 256)
+ sprintf(buf, "'%04.3o'", ch);
+ else
+ sprintf(buf, "token %d", ch);
+ return buf;
+}
+
+static
+yyyylex()
+{
+ if (yychar < 0) {
+ if ((yychar = yylex()) < 0)
+ yychar = 0;
+#ifdef YYDEBUG
+ if (yydebug)
+ printf("[yydebug] reading %s\n", yydisplay(yychar));
+#endif
+ }
+}
diff --git a/y.tab.h b/y.tab.h
new file mode 100644
index 00000000..68405ec0
--- /dev/null
+++ b/y.tab.h
@@ -0,0 +1,47 @@
+
+typedef union {
+ long lval;
+ AWKNUM fval;
+ NODE *nodeval;
+ NODETYPE nodetypeval;
+ char *sval;
+ NODE *(*ptrval)();
+} YYSTYPE;
+extern YYSTYPE yylval;
+# define FUNC_CALL 257
+# define NAME 258
+# define REGEXP 259
+# define ERROR 260
+# define NUMBER 261
+# define YSTRING 262
+# define RELOP 263
+# define APPEND_OP 264
+# define ASSIGNOP 265
+# define MATCHOP 266
+# define NEWLINE 267
+# define CONCAT_OP 268
+# define LEX_BEGIN 269
+# define LEX_END 270
+# define LEX_IF 271
+# define LEX_ELSE 272
+# define LEX_RETURN 273
+# define LEX_DELETE 274
+# define LEX_WHILE 275
+# define LEX_DO 276
+# define LEX_FOR 277
+# define LEX_BREAK 278
+# define LEX_CONTINUE 279
+# define LEX_PRINT 280
+# define LEX_PRINTF 281
+# define LEX_NEXT 282
+# define LEX_EXIT 283
+# define LEX_FUNCTION 284
+# define LEX_GETLINE 285
+# define LEX_IN 286
+# define LEX_AND 287
+# define LEX_OR 288
+# define INCREMENT 289
+# define DECREMENT 290
+# define LEX_BUILTIN 291
+# define LEX_LENGTH 292
+# define UNARY 293