gawk

The GNU Awk User's Guide


Next:  ,Up:  (dir)

General Introduction

This file documents awk, a program that you can use to selectparticular records in a file and perform operations upon them.

Copyright © 1989, 1991, 1992, 1993, 1996, 1997, 1998, 1999,2000, 2001, 2002, 2003, 2004, 2005, 2007, 2009, 2010, 2011Free Software Foundation, Inc.


This is Edition 4 of GAWK: Effective AWK Programming: A User's Guide for GNU Awk,for the 4.0.0 (or later) version of the GNUimplementation of AWK.

Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.3 orany later version published by the Free Software Foundation; with theInvariant Sections being “GNU General Public License”, the Front-Covertexts being (a) (see below), and with the Back-Cover Texts being (b)(see below). A copy of the license is included in the section entitled“GNU Free Documentation License”.

  1. “A GNU Manual”
  2. “You have the freedom tocopy and modify this GNU manual. Buying copies from the FSFsupports it in developing GNU and promoting software freedom.”

Table of Contents


Next:  ,Previous:  Top,Up:  Top

Foreword

Arnold Robbins and I are good friends. We were introducedin 1990by circumstances—and our favorite programming language, AWK. The circumstances started a couple of yearsearlier. I was working at a new job and noticed an unpluggedUnix computer sitting in the corner. No one knew how to use it,and neither did I. However,a couple of days later it was running, andI wasroot and the one-and-only user. That day, I began the transition from statistician to Unix programmer.

On one of many trips to the library or bookstore in search ofbooks on Unix, I found the gray AWK book, a.k.a. Aho, Kernighan andWeinberger,The AWK Programming Language, Addison-Wesley,1988. AWK's simple programming paradigm—find a pattern in theinput and then perform an action—often reduced complex or tediousdata manipulations to few lines of code. I was excited to try myhand at programming in AWK.

Alas, the awk on my computer was a limited version of thelanguage described in the AWK book. I discovered that my computerhad “oldawk” and the AWK book described “new awk.”I learned that this was typical; the old version refused to stepaside or relinquish its name. If a system had a newawk, it wasinvariably called nawk, and few systems had it. The best way to get a newawk was to ftp the source code forgawk fromprep.ai.mit.edu. gawk was a version ofnewawk written by David Trueman and Arnold, and available underthe GNU General Public License.

(Incidentally,it's no longer difficult to find a new awk.gawk ships withGNU/Linux, and you can download binaries or source code for almostany system; my wife usesgawk on her VMS box.)

My Unix system started out unplugged from the wall; it certainly was notplugged into a network. So, oblivious to the existence ofgawkand the Unix community in general, and desiring a newawk, I wrotemy own, called mawk. Before I was finished I knew aboutgawk,but it was too late to stop, so I eventually postedto acomp.sources newsgroup.

A few days after my posting, I got a friendly emailfrom Arnold introducinghimself. He suggested we share design and algorithms andattached a draft of the POSIX standard sothat I could updatemawk to support language extensions addedafter publication of the AWK book.

Frankly, if our roles hadbeen reversed, I would not have been so open and we probably wouldhave never met. I'm glad we did meet. He is an AWK expert's AWK expert and a genuinely nice person. Arnold contributes significant amounts of hisexpertise and time to the Free Software Foundation.

This book is the gawk reference manual, but at its core itis a book about AWK programming thatwill appeal to a wide audience. It is a definitive reference to the AWK language as defined by the1987 Bell Laboratories release and codified in the 1992 POSIX Utilitiesstandard.

On the other hand, the novice AWK programmer can studya wealth of practical programs that emphasizethe power of AWK's basic idioms:data driven control-flow, pattern matching with regular expressions,and associative arrays. Those looking for something new can try out gawk'sinterface to network protocols via special/inet files.

The programs in this book make clear that an AWK program istypically much smaller and faster to develop thana counterpart written in C. Consequently, there is often a payoff to prototype analgorithm or design in AWK to get it running quickly and exposeproblems early. Often, the interpreted performance is adequateand the AWK prototype becomes the product.

The new pgawk (profiling gawk), producesprogram execution counts. I recently experimented with an algorithm that forn lines of input, exhibited~ C n^2performance, whiletheory predicted~ C n log nbehavior. A few minutes poringover the awkprof.out profile pinpointed the problem toa single line of code.pgawk is a welcome addition tomy programmer's toolbox.

Arnold has distilled over a decade of experience writing andusing AWK programs, and developinggawk, into this book. If you useAWK or want to learn how, then read this book.

     Michael Brennan
     Author of mawk
     March, 2001


Next:  ,Previous:  Foreword,Up:  Top

Preface

Several kinds of tasks occur repeatedlywhen working with text files. You might want to extract certain lines and discard the rest. Or you may need to make changes wherever certain patterns appear,but leave the rest of the file alone. Writing single-use programs for these tasks in languages such as C, C++,or Java is time-consuming and inconvenient. Such jobs are often easier withawk. The awk utility interprets a special-purpose programming languagethat makes it easy to handle simple data-reformatting jobs.

The GNU implementation of awk is calledgawk; it is fullycompatible withthe POSIX1specification of theawk languageand with the Unix version ofawk maintainedby Brian Kernighan. This means that allproperly writtenawk programs should work with gawk. Thus, we usually don't distinguish betweengawk and otherawk implementations.

Usingawk allows you to:

  • Manage small, personal databases
  • Generate reports
  • Validate data
  • Produce indexes and perform other document preparation tasks
  • Experiment with algorithms that you can adapt later to other computerlanguages

In addition,gawkprovides facilities that make it easy to:

  • Extract bits and pieces of data for processing
  • Sort data
  • Perform simple network communications

This Web page teaches you about the awk language andhow you can use it effectively. You should already be familiar with basicsystem commands, such ascat and ls,2 as well as basic shellfacilities, such as input/output (I/O) redirection and pipes.

Implementations of theawk language are available for manydifferent computing environments. This Web page, while describingtheawk language in general, also describes the particularimplementation ofawk called gawk (which stands for“GNU awk”).gawk runs on a broad range of Unix systems,ranging from Intel®-architecture PC-based computersup through large-scale systems,such as Crays.gawk has also been ported to Mac OS X,Microsoft Windows (all versions) and OS/2 PCs,and VMS. (Some other, obsolete systems to whichgawk was once portedare no longer supported and the code for those systemshas been removed.)


Next:  ,Up:  Preface

History of awk andgawk

Recipe For A Programming Language

 1 part egrep1 part snobol
 2 parts ed3 parts C

Blend all parts well using lex and yacc. Document minimally and release.

After eight years, add another part egrep and twomore parts C. Document very well and release.

The nameawk comes from the initials of its designers: Alfred V. Aho, Peter J. Weinberger and Brian W. Kernighan. The original version ofawk was written in 1977 at AT&T Bell Laboratories. In 1985, a new version made the programminglanguage more powerful, introducing user-defined functions, multiple inputstreams, and computed regular expressions. This new version became widely available with Unix System VRelease 3.1 (1987). The version in System V Release 4 (1989) added some new features and cleanedup the behavior in some of the “dark corners” of the language. The specification forawk in the POSIX Command Languageand Utilities standard further clarified the language. Both thegawk designers and the original Bell Laboratoriesawkdesigners provided feedback for the POSIX specification.

Paul Rubin wrote the GNU implementation,gawk, in 1986. Jay Fenlason completed it, with advice from Richard Stallman. John Woodscontributed parts of the code as well. In 1988 and 1989, David Trueman, withhelp from me, thoroughly reworkedgawk for compatibilitywith the newer awk. Circa 1994, I became the primary maintainer. Current development focuses on bug fixes,performance improvements, standards compliance, and occasionally, new features.

In May of 1997, Jürgen Kahrs felt the need for network accessfrom awk, and with a little help from me, set about addingfeatures to do this forgawk. At that time, he alsowrote the bulk ofTCP/IP Internetworking withgawk(a separate document, available as part of thegawk distribution). His code finally became part of the maingawk distributionwith gawk version 3.1.

John Haque rewrote the gawk internals, in the process providinganawk-level debugger. This version became available asgawk version 4.0, in 2011.

See Contributors,for a complete list of those who made important contributions togawk.


Next:  ,Previous:  History,Up:  Preface

A Rose by Any Other Name

Theawk language has evolved over the years. Full details areprovided inLanguage History. The language described in this Web pageis often referred to as “newawk” (nawk).

Because of this, there are systems with multipleversions ofawk. Some systems have an awk utility that implements theoriginal version of theawk language and a nawk utilityfor the new version. Others have anoawk version for the “old awk”language and plainawk for the new one. Still others onlyhave one version, which is usually the new one.3

All in all, this makes it difficult for you to know which version ofawk you should run when writing your programs. The best advicewe can give here is to check your local documentation. Look forawk,oawk, andnawk, as well as for gawk. It is likely that you alreadyhave some version of newawk on your system, which is whatyou should use when running your programs. (Of course, if you're readingthis Web page, chances are good that you havegawk!)

Throughout this Web page, whenever we refer to a language featurethat should be available in any complete implementation of POSIXawk,we simply use the term awk. When referring to a feature that isspecific to the GNU implementation, we use the termgawk.


Next:  ,Previous:  Names,Up:  Preface

Using This Book

The termawk refers to a particular program as well as to the language youuse to tell this program what to do. When we need to be careful, we callthe language “theawk language,”and the program “the awk utility.”This Web page explainsboth how to write programs in theawk language and how torun the awk utility. The termawk program refers to a program written by you intheawk programming language.

Primarily, this Web page explains the features of awkas defined in the POSIX standard. It does so in the context of thegawk implementation. While doing so, it alsoattempts to describe important differences between gawkand other awk implementations.4Finally, anygawk features that are not inthe POSIX standard forawk are noted.

This Web page has the difficult task of being both a tutorial and a reference. If you are a novice, feel free to skip over details that seem too complex. You should also ignore the many cross-references; they are for theexpert user and for the online Info and HTML versions of the document.

There aresubsections labeledas Advanced Notesscattered throughout the Web page. They add a more complete explanation of points that are relevant, but not likelyto be of interest on first reading. All appear in the index, under the heading “advanced features.”

Most of the time, the examples use complete awk programs. Some of the more advanced sections show only the part of theawkprogram that illustrates the concept currently being described.

While this Web page is aimed principally at people who have not beenexposedto awk, there is a lot of information here that even theawkexpert should find useful. In particular, the description of POSIXawk and the example programs inLibrary Functions, and inSample Programs,should be of interest.

Getting Started,provides the essentials you need to know to begin usingawk.

Invoking Gawk,describes how to run gawk, the meaning of itscommand-line options, and how it findsawkprogram source files.

Regexp,introduces regular expressions in general, and in particular the flavorssupported by POSIXawk and gawk.

Reading Files,describes how awk reads your data. It introduces the concepts of records and fields, as wellas thegetline command. I/O redirection is first described here. Network I/O is also briefly introduced here.

Printing,describes how awk programs can produce output withprint andprintf.

Expressions,describes expressions, which are the basic building blocksfor getting most things done in a program.

Patterns and Actions,describes how to write patterns for matching records, actions fordoing something when a record is matched, and the built-in variablesawk andgawk use.

Arrays,covers awk's one-and-only data structure: associative arrays. Deleting array elements and whole arrays is also described, as well assorting arrays ingawk. It also describes how gawkprovides arrays of arrays.

Functions,describes the built-in functions awk andgawk provide, as well as how to defineyour own functions.

Internationalization,describes special features ingawk for translating programmessages into different languages at runtime.

Advanced Features,describes a number of gawk-specific advanced features. Of particular noteare the abilities to have two-way communications with another process,perform TCP/IP networking, andprofile yourawk programs.

Library Functions, andSample Programs,provide many sampleawk programs. Reading them allows you to seeawksolving real problems.

Debugger, describes the awk debugger,dgawk.

Language History,describes how the awk language has evolved sinceits first release to present. It also describes howgawkhas acquired features over time.

Installation,describes how to get gawk, how to compile iton POSIX-compatible systems,and how to compile and use it on differentnon-POSIX systems. It also describes how to report bugsingawk and where to get other freelyavailableawk implementations.

Notes,describes how to disable gawk's extensions, aswell as how to contribute new code togawk,how to write extension libraries, and some possiblefuture directions forgawk development.

Basic Concepts,provides some very cursory background material for those whoare completely unfamiliar with computer programming. Also centralized there is a discussion of some of the issuessurrounding floating-point numbers.

TheGlossary,defines most, if not all, the significant terms usedthroughout the book. If you find terms that you aren't familiar with, try looking them up here.

Copying, andGNU Free Documentation License,present the licenses that cover thegawk source codeand this Web page, respectively.


Next:  ,Previous:  This Manual,Up:  Preface

Typographical Conventions

This Web page is written in Texinfo,the GNU documentation formatting language. A single Texinfo source file is used to produce both the printed and onlineversions of the documentation. Because of this, the typographical conventionsare slightly different than in other books you may have read.

Examples you would type at the command-line are preceded by the commonshell primary and secondary prompts, ‘$’ and ‘>’. Input that you type is shownlike this. Output from the command is preceded by the glyph “-|”. This typically represents the command's standard output. Error messages, and other output on the command's standard error, are precededby the glyph “error-->”. For example:

     $ echo hi on stdout
     -| hi on stdout
     $ echo hello on stderr 1>&2
     error--> hello on stderr

In the text, command names appear in this font, while code segmentsappear in the same font and quoted, ‘like this’. Options look like this:-f. Some things areemphasized like this, and if a point needs to be madestrongly, it is donelike this. The first occurrence ofa new term is usually its definition and appears in the samefont as the previous occurrence of “definition” in this sentence. Finally, file names are indicated like this:/path/to/ourfile.

Characters that you type at the keyboard look like this. In particular,there are special characters called “control characters.” These arecharacters that you type by holding down both theCONTROL key andanother key, at the same time. For example, a Ctrl-d is typedby first pressing and holding theCONTROL key, nextpressing the d key and finally releasing both keys.

Dark Corners

Dark corners are basically fractal — no matter how muchyou illuminate, there's always a smaller but darker one.
Brian Kernighan

Until the POSIX standard (andGAWK: Effective AWK Programming),many features of awk were either poorly documented or notdocumented at all. Descriptions of such features(often called “dark corners”) are noted in this Web page with“(d.c.)”. They also appear in the index under the heading “dark corner.”

As noted by the opening quote, though, anycoverage of dark cornersis, by definition, incomplete.

Extensions to the standard awk language that are supported bymore than oneawk implementation are marked“(c.e.),” and listed in the index under “common extensions”and “extensions, common.”


Next:  ,Previous:  Conventions,Up:  Preface

The GNU Project and This Book

The Free Software Foundation (FSF) is a nonprofit organization dedicatedto the production and distribution of freely distributable software. It was founded by Richard M. Stallman, the author of the originalEmacs editor. GNU Emacs is the most widely used version of Emacs today.

The GNU5Project is an ongoing effort on the part of the Free SoftwareFoundation to create a complete, freely distributable, POSIX-compliantcomputing environment. The FSF uses the “GNU General Public License” (GPL) to ensure thattheir software'ssource code is always available to the end user. Acopy of the GPL is includedin this Web pagefor your reference(seeCopying). The GPL applies to the C language source code forgawk. To find out more about the FSF and the GNU Project online,seethe GNU Project's home page. This Web page may also be read fromtheir web site.

A shell, an editor (Emacs), highly portable optimizing C, C++, andObjective-C compilers, a symbolic debugger and dozens of large andsmall utilities (such asgawk), have all been completed and arefreely available. The GNU operatingsystem kernel (the HURD), has been released but remains in an earlystage of development.

Until the GNU operating system is more fully developed, you shouldconsider using GNU/Linux, a freely distributable, Unix-like operatingsystem for Intel®,Power Architecture,Sun SPARC, IBM S/390, and othersystems.6Many GNU/Linux distributions areavailable for download from the Internet.

(There are numerous other freely available, Unix-like operating systemsbased on theBerkeley Software Distribution, and some of them use recent versionsofgawk for their versions of awk.NetBSD,FreeBSD,andOpenBSDare three of the most popular ones, but thereare others.)

The Web page you are reading is actually free—at least, theinformation in it is free to anyone. The machine-readablesource code for the Web page comes withgawk; anyonemay take this Web page to a copying machine and make as manycopies as they like. (Take a moment to check the Free DocumentationLicense inGNU Free Documentation License.)

The Web page itself has gone through a number of previous editions. Paul Rubin wrote the very first draft ofThe GAWK Manual;it was around 40 pages in size. Diane Close and Richard Stallman improved it, yielding aversion that wasaround 90 pages long and barely described the original, “old”version ofawk.

I started working with that version in the fall of 1988. As work on it progressed,the FSF published several preliminary versions (numbered 0.x). In 1996, Edition 1.0 was released withgawk 3.0.0. The FSF published the first two editions underthe titleThe GNU Awk User's Guide.

This edition maintains the basic structure of the previous editions. For Edition 4.0, the content has been thoroughly reviewedand updated. All references to versions prior to 4.0 have beenremoved. Of significant note for this edition isDebugger.

GAWK: Effective AWK Programming will undoubtedly continue to evolve. An electronic versioncomes with thegawk distribution from the FSF. If you find an error in this Web page, please report it! SeeBugs, for information on submittingproblem reports electronically.


Next:  ,Previous:  Manual History,Up:  Preface

How to Contribute

As the maintainer of GNU awk, I once thought that I would beable to manage a collection of publicly availableawk programsand I even solicited contributions. Making things available on the Internethelps keep thegawk distribution down to manageable size.

The initial collection of material, such as it is, is still availableat ftp://ftp.freefriends.org/arnold/Awkstuff. In the hopes ofdoing something more broad, I acquired theawk.info domain.

However, I found that I could not dedicate enough time to managingcontributed code: the archive did not grow and the domain went unusedfor several years.

Fortunately, late in 2008, a volunteer took on the task of setting upan awk-related web site—http://awk.info—and did a verynice job.

If you have written an interesting awk program, or have writtenagawk extension that you would like to share with the restof the world, please seehttp://awk.info/?contribute for how tocontribute it to the web site.


Previous:  How To Contribute,Up:  Preface

Acknowledgments

The initial draft of The GAWK Manual had the following acknowledgments:

Many people need to be thanked for their assistance in producing thismanual. Jay Fenlason contributed many ideas and sample programs. RichardMlynarik and Robert Chassell gave helpful comments on drafts of thismanual. The paper A Supplemental Document for awk by John W. Pierce of the Chemistry Department at UC San Diego, pinpointed severalissues relevant both to awk implementation and to this manual, thatwould otherwise have escaped us.

I would like to acknowledge Richard M. Stallman, for his vision of abetter world and for his courage in founding the FSF and starting theGNU Project.

Earlier editions of this Web page had the following acknowledgements:

The following people (in alphabetical order)provided helpful comments on variousversions of this book,Rick Adams,Dr. Nelson H.F. Beebe,Karl Berry,Dr. Michael Brennan,Rich Burridge,Claire Cloutier,Diane Close,Scott Deifik,Christopher (“Topher”) Eliot,Jeffrey Friedl,Dr. Darrel Hankerson,Michal Jaegermann,Dr. Richard J. LeBlanc,Michael Lijewski,Pat Rankin,Miriam Robbins,Mary Sheehan,andChuck Toporek.

Robert J. Chassell provided much valuable advice onthe use of Texinfo. He also deserves special thanks forconvincing menot to title this Web pageHow To Gawk Politely. Karl Berry helped significantly with the TeX part of Texinfo.

I would like to thank Marshall and Elaine Hartholz of Seattle andDr. Bert and Rita Schreiber of Detroit for large amounts of quiet vacationtime in their homes, which allowed me to make significant progress onthis Web page and ongawk itself.

Phil Hughes of SSCcontributed in a very important way by loaning me his laptop GNU/Linuxsystem, not once, but twice, which allowed me to do a lot of work whileaway from home.

David Trueman deserves special credit; he has done a yeoman jobof evolvinggawk so that it performs well and without bugs. Although he is no longer involved withgawk,working with him on this project was a significant pleasure.

The intrepid members of the GNITS mailing list, and most notably UlrichDrepper, provided invaluable help and feedback for the design of theinternationalization features.

Chuck Toporek, Mary Sheehan, and Claire Coutier of O'Reilly & Associates contributedsignificant editorial help for this Web page for the3.1 release ofgawk.

Dr. Nelson Beebe,Andreas Buening,Antonio Colombo,Stephen Davies,Scott Deifik,John H. DuBois III,Darrel Hankerson,Michal Jaegermann,Jürgen Kahrs,Dave Pitts,Stepan Kasal,Pat Rankin,Andrew Schorr,Corinna Vinschen,Anders Wallin,and Eli Zaretskii(in alphabetical order)make up the currentgawk “crack portability team.” Without their hard work andhelp,gawk would not be nearly the fine program it is today. Ithas been and continues to be a pleasure working with this team of finepeople.

John Haque contributed the modifications to convert gawkinto a byte-code interpreter, including the debugger. Stephen Daviescontributed to the effort to bring the byte-code changes into the mainstreamcode base. Efraim Yawitz contributed the initial text of Debugger.

I would like to thank Brian Kernighan for invaluable assistance during thetesting and debugging ofgawk, and for ongoinghelp and advice in clarifying numerous points about the language. We could not have done nearly as good a job on eithergawkor its documentation without his help.

I must thank my wonderful wife, Miriam, for her patience throughthe many versions of this project, for her proofreading,and for sharing me with the computer. I would like to thank my parents for their love, and for the grace withwhich they raised and educated me. Finally, I also must acknowledge my gratitude to G-d, for the many opportunitiesHe has sent my way, as well as for the gifts He has given me with which totake advantage of those opportunities.


Arnold Robbins
Nof Ayalon
ISRAEL
March, 2011


Next:  ,Previous:  Preface,Up:  Top

1 Getting Started with awk

The basic function ofawk is to search files for lines (or otherunits of text) that contain certain patterns. When a line matches oneof the patterns,awk performs specified actions on that line.awk keeps processing input lines in this way until it reachesthe end of the input files.

Programs inawk are different from programs in most other languages,becauseawk programs are data-driven; that is, you describethe data you want to work with and then what to do when you find it. Most other languages areprocedural; you have to describe, in greatdetail, every step the program is to take. When working with procedurallanguages, it is usually muchharder to clearly describe the data your program will process. For this reason,awk programs are often refreshingly easy toread and write.

When you runawk, you specify an awkprogram thattells awk what to do. The program consists of a series ofrules. (It may also containfunction definitions,an advanced feature that we will ignore for now. SeeUser-defined.) Each rule specifies onepattern to search for and one action to performupon finding the pattern.

Syntactically, a rule consists of a pattern followed by an action. Theaction is enclosed in curly braces to separate it from the pattern. Newlines usually separate rules. Therefore, anawkprogram looks like this:

     pattern { action }
     pattern { action }
     ...

1.1 How to Run awk Programs

There are several ways to run anawk program. If the program isshort, it is easiest to include it in the command that runsawk,like this:

     awk 'program' input-file1 input-file2 ...

When the program is long, it is usually more convenient to put it in a fileand run it with a command like this:

     awk -f program-file input-file1 input-file2 ...

This section discusses both mechanisms, along with severalvariations of each.


Next:  ,Up:  Running gawk

1.1.1 One-Shot Throwaway awk Programs

Once you are familiar with awk, you will often type in simpleprograms the moment you want to use them. Then you can write theprogram as the first argument of theawk command, like this:

     awk 'program' input-file1 input-file2 ...

where program consists of a series of patterns andactions, as described earlier.

This command format instructs theshell, or command interpreter,to start awk and use theprogram to process records in theinput file(s). There are single quotes aroundprogram sothe shell won't interpret any awk characters as special shellcharacters. The quotes also cause the shell to treat all ofprogram asa single argument for awk, and allowprogram to be morethan one line long.

This format is also useful for running short or medium-sizedawkprograms from shell scripts, because it avoids the need for a separatefile for theawk program. A self-contained shell script is morereliable because there are no other files to misplace.

Very Simple,later in this chapter,presents several short,self-contained programs.


Next:  ,Previous:  One-shot,Up:  Running gawk

1.1.2 Running awk Without Input Files

You can also runawk without any input files. If you type thefollowing command line:

     awk 'program'

awk applies the program to the standard input,which usually means whatever you type on the terminal. This continuesuntil you indicate end-of-file by typingCtrl-d. (On other operating systems, the end-of-file character may be different. For example, on OS/2, it isCtrl-z.)

As an example, the following program prints a friendly piece of advice(from Douglas Adams's The Hitchhiker's Guide to the Galaxy),to keep you from worrying about the complexities of computerprogramming7(BEGIN is a feature we haven't discussed yet):

     $ awk "BEGIN { print \"Don't Panic!\" }"
     -| Don't Panic!

This program does not read any input. The ‘\’ before each of theinner double quotes is necessary because of the shell's quotingrules—in particular because it mixes both single quotes anddouble quotes.8

This next simple awk programemulates thecat utility; it copies whatever you type on thekeyboard to its standard output (why this works is explained shortly).

     $ awk '{ print }'
     Now is the time for all good men
     -| Now is the time for all good men
     to come to the aid of their country.
     -| to come to the aid of their country.
     Four score and seven years ago, ...
     -| Four score and seven years ago, ...
     What, me worry?
     -| What, me worry?
     Ctrl-d


Next:  ,Previous:  Read Terminal,Up:  Running gawk

1.1.3 Running Long Programs

Sometimes yourawk programs can be very long. In this case, it ismore convenient to put the program into a separate file. In order to tellawk to use that file for its program, you type:

     awk -f source-file input-file1 input-file2 ...

The-f instructs the awk utility to get theawk programfrom the file source-file. Any file name can be used forsource-file. For example, you could put the program:

     BEGIN { print "Don't Panic!" }

into the file advice. Then this command:

     awk -f advice

does the same thing as this one:

     awk "BEGIN { print \"Don't Panic!\" }"

This was explained earlier(see Read Terminal). Note that you don't usually need single quotes around the file name that youspecify with-f, because most file names don't contain any of the shell'sspecial characters. Notice that inadvice, the awkprogram did not have single quotes around it. The quotes are only neededfor programs that are provided on theawk command line.

If you want to clearly identify yourawk program files as such,you can add the extension.awk to the file name. This doesn'taffect the execution of theawk program but it does make“housekeeping” easier.


Next:  ,Previous:  Long,Up:  Running gawk

1.1.4 Executable awk Programs

Once you have learned awk, you may want to write self-containedawk scripts, using the ‘#!’ script mechanism. You can dothis on many systems.9For example, you could update the file advice to look like this:

     #! /bin/awk -f
     
     BEGIN { print "Don't Panic!" }

After making this file executable (with the chmod utility),simply type ‘advice’at the shell and the system arranges to runawk10 as if you hadtyped ‘awk -f advice’:

     $ chmod +x advice
     $ advice
     -| Don't Panic!

(We assume you have the current directory in your shell's searchpath variable [typically$PATH]. If not, you may needto type ‘./advice’ at the shell.)

Self-contained awk scripts are useful when you want to write aprogram that users can invoke without their having to know that the program iswritten inawk.

Advanced Notes: Portability Issues with ‘#!

Some systems limit the length of the interpreter name to 32 characters. Often, this can be dealt with by using a symbolic link.

You should not put more than one argument on the ‘#!’line after the path toawk. It does not work. The operating systemtreats the rest of the line as a single argument and passes it toawk. Doing this leads to confusing behavior—most likely a usage diagnosticof some sort fromawk.

Finally,the value ofARGV[0](see Built-in Variables)varies depending upon your operating system. Some systems put ‘awk’ there, some put the full pathnameofawk (such as /bin/awk), and some put the nameof your script (‘advice’). (d.c.) Don't rely on the value ofARGV[0]to provide your script name.


Next:  ,Previous:  Executable Scripts,Up:  Running gawk

1.1.5 Comments in awk Programs

Acomment is some text that is included in a program for the sakeof human readers; it is not really an executable part of the program. Commentscan explain what the program does and how it works. Nearly allprogramming languages have provisions for comments, as programs aretypically hard to understand without them.

In the awk language, a comment starts with the sharp signcharacter (‘#’) and continues to the end of the line. The ‘#’ does not have to be the first character on the line. Theawk language ignores the rest of a line following a sharp sign. For example, we could have put the following intoadvice:

     # This program prints a nice friendly message.  It helps
     # keep novice users from being afraid of the computer.
     BEGIN    { print "Don't Panic!" }

You can put comment lines into keyboard-composed throwaway awkprograms, but this usually isn't very useful; the purpose of acomment is to help you or another person understand the programwhen reading it at a later time.

CAUTION: As mentioned in One-shot,you can enclose small to medium programs in single quotes, in order to keepyour shell scripts self-contained. When doing so, don't putan apostrophe (i.e., a single quote) into a comment (or anywhere elsein your program). The shell interprets the quote as the closingquote for the entire program. As a result, usually the shellprints a message about mismatched quotes, and if awk actuallyruns, it will probably print strange messages about syntax errors. For example, look at the following:
     $ awk '{ print "hello" } # let's be cute'
     >

The shell sees that the first two quotes match, and thata new quoted object begins at the end of the command line. It therefore prompts with the secondary prompt, waiting for more input. With Unixawk, closing the quoted string produces this result:

     $ awk '{ print "hello" } # let's be cute'
     > '
     error--> awk: can't open file be
     error-->  source line number 1

Putting a backslash before the single quote in ‘let's’ wouldn't help,since backslashes are not special inside single quotes. The next subsection describes the shell's quoting rules.


Previous:  Comments,Up:  Running gawk

1.1.6 Shell-Quoting Issues

For short to medium length awk programs, it is most convenientto enter the program on theawk command line. This is best done by enclosing the entire program in single quotes. This is true whether you are entering the program interactively atthe shell prompt, or writing it as part of a larger shell script:

     awk 'program text' input-file1 input-file2 ...

Once you are working with the shell, it is helpful to have a basicknowledge of shell quoting rules. The following rules apply only toPOSIX-compliant, Bourne-style shells (such as Bash, the GNU Bourne-AgainShell). If you use the C shell, you're on your own.

  • Quoted items can be concatenated with nonquoted items as well as with otherquoted items. The shell turns everything into one argument forthe command.
  • Preceding any single character with a backslash (‘\’) quotesthat character. The shell removes the backslash and passes the quotedcharacter on to the command.
  • Single quotes protect everything between the opening and closing quotes. The shell does no interpretation of the quoted text, passing it on verbatimto the command. It isimpossible to embed a single quote inside single-quoted text. Refer back toComments,for an example of what happens if you try.
  • Double quotes protect most things between the opening and closing quotes. The shell does at least variable and command substitution on the quoted text. Different shells may do additional kinds of processing on double-quoted text.

    Since certain characters within double-quoted text are processed by the shell,they must beescaped within the text. Of note are the characters‘$’, ‘`’, ‘\’, and ‘"’, all of which must be preceded bya backslash within double-quoted text if they are to be passed on literallyto the program. (The leading backslash is stripped first.) Thus, the example seenpreviouslyinRead Terminal,is applicable:

              $ awk "BEGIN { print \"Don't Panic!\" }"
              -| Don't Panic!
    

    Note that the single quote is not special within double quotes.

  • Null strings are removed when they occur as part of a non-nullcommand-line argument, while explicit non-null objects are kept. For example, to specify that the field separatorFS shouldbe set to the null string, use:
              awk -F "" 'program' files # correct
    

    Don't use this:

              awk -F"" 'program' files  # wrong!
    

    In the second case, awk will attempt to use the text of the programas the value ofFS, and the first file name as the text of the program! This results in syntax errors at best, and confusing behavior at worst.

Mixing single and double quotes is difficult. You have to resortto shell quoting tricks, like this:

     $ awk 'BEGIN { print "Here is a single quote <'"'"'>" }'
     -| Here is a single quote <'>

This program consists of three concatenated quoted strings. The first and thethird are single-quoted, the second is double-quoted.

This can be “simplified” to:

     $ awk 'BEGIN { print "Here is a single quote <'\''>" }'
     -| Here is a single quote <'>

Judge for yourself which of these two is the more readable.

Another option is to use double quotes, escaping the embedded, awk-leveldouble quotes:

     $ awk "BEGIN { print \"Here is a single quote <'>\" }"
     -| Here is a single quote <'>

This option is also painful, because double quotes, backslashes, and dollar signsare very common in more advancedawk programs.

A third option is to use the octal escape sequence equivalents(see Escape Sequences)for thesingle- and double-quote characters, like so:

     $ awk 'BEGIN { print "Here is a single quote <\47>" }'
     -| Here is a single quote <'>
     $ awk 'BEGIN { print "Here is a double quote <\42>" }'
     -| Here is a double quote <">

This works nicely, except that you should comment clearly what theescapes mean.

A fourth option is to use command-line variable assignment, like this:

     $ awk -v sq="'" 'BEGIN { print "Here is a single quote <" sq ">" }'
     -| Here is a single quote <'>

If you really need both single and double quotes in your awkprogram, it is probably best to move it into a separate file, wherethe shell won't be part of the picture, and you can say what you mean.


Up:  Quoting

1.1.6.1 Quoting in MS-Windows Batch Files

Although this Web page generally only worries about POSIX systems and thePOSIX shell, the following issue arises often enough for many users thatit is worth addressing.

The “shells” on Microsoft Windows systems use the double-quotecharacter for quoting, and make it difficult or impossible to include anescaped double-quote character in a command-line script. The following example, courtesy of Jeroen Brink, showshow to print all lines in a file surrounded by double quotes:

     gawk "{ print \"\042\" $0 \"\042\" }" file


Next:  ,Previous:  Running gawk,Up:  Getting Started

1.2 Data Files for the Examples

<!-- For gawk >= 4.0, update these data files. No-one has such slow modems! -->

Many of the examples in this Web page take their input from two sampledata files. The first,BBS-list, represents a list ofcomputer bulletin board systems together with information about those systems. The second data file, calledinventory-shipped, containsinformation about monthly shipments. In both files,each line is considered to be onerecord.

In the data file BBS-list, each record contains the name of a computerbulletin board, its phone number, the board's baud rate(s), and a code forthe number of hours it is operational. An ‘A’ in the last columnmeans the board operates 24 hours a day. A ‘B’ in the lastcolumn means the board only operates on evening and weekend hours. 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 data fileinventory-shipped representsinformation about shipments during the year. Each record contains the month, the numberof green crates shipped, the number of red boxes shipped, the number oforange bags shipped, and the number of blue packages shipped,respectively. There are 16 entries, covering the 12 months of last yearand the first four months of the current year.

     
     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
     


Next:  ,Previous:  Sample Data Files,Up:  Getting Started

1.3 Some Simple Examples

The following command runs a simple awk program that searches theinput fileBBS-list for the character string ‘foo’ (agrouping of characters is usually called astring;the term string is based on similar usage in English, suchas “a string of pearls,” or “a string of cars in a train”):

     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’ byitself means the same thing, so we could have written thatinstead.)

You will notice that slashes (‘/’) surround the string ‘foo’in theawk program. The slashes indicate that ‘foo’is the pattern to search for. This type of pattern is called aregular expression, which is covered in more detail later(seeRegexp). The pattern is allowed to match parts of words. There aresingle quotes around theawk program so that the shell won'tinterpret any of it as special shell characters.

Here is what this program prints:

     $ awk '/foo/ { print $0 }' BBS-list
     -| 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 anawk rule, either the pattern or the action can be omitted,but not both. If the pattern is omitted, then the action is performedforevery input line. If the action is omitted, the defaultaction is to print all lines that match the pattern.

Thus, we could leave out the action (theprint statement and the curlybraces) in the previous example and the result would be the same:awk prints all lines matching the pattern ‘foo’. By comparison,omitting the print statement but retaining the curly braces makes anempty action that does nothing (i.e., no lines are printed).

Many practicalawk programs are just a line or two. Following is acollection of useful, short programs to get you started. Some of theseprograms contain constructs that haven't been covered yet. (The descriptionof the program will give you a good idea of what is going on, but pleaseread the rest of the Web page to become anawk expert!) Most of the examples use a data file nameddata. This is just aplaceholder; if you use these programs yourself, substituteyour own file names fordata. For future reference, note that there is often more thanone way to do things inawk. At some point, you may wantto look back at these examples and see ifyou can come up with different ways to do the same things shown here:

  • Print the length of the longest input line:
              awk '{ if (length($0) > max) max = length($0) }
                   END { print max }' data
    
  • Print every line that is longer than 80 characters:
              awk 'length($0) > 80' data
    

    The sole rule has a relational expression as its pattern and it has noaction—so the default action, printing the record, is used.

  • Print the length of the longest line in data:
              expand data | awk '{ if (x < length()) x = length() }
                            END { print "maximum line length is " x }'
    

    The input is processed by the expand utility to change TABsinto spaces, so the widths compared are actually the right-margin columns.

  • Print every line that has at least one field:
              awk 'NF > 0' data
    

    This is an easy way to delete blank lines from a file (or rather, tocreate a new file similar to the old file but from which the blank lineshave been removed).

  • Print seven random numbers from 0 to 100, inclusive:
              awk 'BEGIN { for (i = 1; i <= 7; i++)
                               print int(101 * rand()) }'
    
  • Print the total number of bytes used by files:
              ls -l files | awk '{ x += $5 }
                                END { print "total bytes: " x }'
    
  • Print the total number of kilobytes used by files:
              ls -l files | awk '{ x += $5 }
                 END { print "total K-bytes:", x / 1024 }'
    
  • Print a sorted list of the login names of all users:
              awk -F: '{ print $1 }' /etc/passwd | sort
    
  • Count the lines in a file:
              awk 'END { print NR }' data
    
  • Print the even-numbered lines in the data file:
              awk 'NR % 2 == 0' data
    

    If you use the expression ‘NR % 2 == 1’ instead,the program would print the odd-numbered lines.


Next:  ,Previous:  Very Simple,Up:  Getting Started

1.4 An Example with Two Rules

The awk utility reads the input files one line at atime. For each line,awk tries the patterns of each of the rules. If several patterns match, then several actions are run in the order inwhich they appear in theawk program. If no patterns match, thenno actions are run.

After processing all the rules that match the line (and perhaps there are none),awk reads the next line. (However,seeNext Statement,and also see Nextfile Statement). This continues until the program reaches the end of the file. For example, the followingawk program contains two rules:

     /12/  { print $0 }
     /21/  { print $0 }

The first rule has the string ‘12’ as thepattern and ‘print $0’ as the action. The second rule has thestring ‘21’ as the pattern and also has ‘print $0’ as theaction. Each rule's action is enclosed in its own pair of braces.

This program prints every line that contains the string‘12or the string ‘21’. If a line contains bothstrings, it is printed twice, once by each rule.

This is what happens if we run this program on our two sample data files,BBS-list andinventory-shipped:

     $ awk '/12/ { print $0 }
     >      /21/ { print $0 }' BBS-list inventory-shipped
     -| 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 beginning with ‘sabafoo’inBBS-list was printed twice, once for each rule.


Next:  ,Previous:  Two Rules,Up:  Getting Started

1.5 A More Complex Example

Now that we've mastered some simple tasks, let's look atwhat typical awkprograms do. This example shows howawk can be used tosummarize, select, and rearrange the output of another utility. It usesfeatures that haven't been covered yet, so don't worry if you don'tunderstand all the details:

     LC_ALL=C ls -l | awk '$6 == "Nov" { sum += $5 }
                           END { print sum }'

This command prints the total number of bytes in all the files in thecurrent directory that were last modified in November (of any year). The ‘ls -l’ part of this example is a system command that givesyou a listing of the files in a directory, including each file's size and the datethe file was last modified. Its output looks like this:

     -rw-r--r--  1 arnold   user   1933 Nov  7 13:05 Makefile
     -rw-r--r--  1 arnold   user  10809 Nov  7 13:03 awk.h
     -rw-r--r--  1 arnold   user    983 Apr 13 12:14 awk.tab.h
     -rw-r--r--  1 arnold   user  31869 Jun 15 12:20 awkgram.y
     -rw-r--r--  1 arnold   user  22414 Nov  7 13:03 awk1.c
     -rw-r--r--  1 arnold   user  37455 Nov  7 13:03 awk2.c
     -rw-r--r--  1 arnold   user  27511 Dec  9 13:07 awk3.c
     -rw-r--r--  1 arnold   user   7989 Nov  7 13:03 awk4.c

The first field contains read-write permissions, the second field containsthe number of links to the file, and the third field identifies the owner ofthe file. The fourth field identifies the group of the file. The fifth field contains the size of the file in bytes. Thesixth, seventh, and eighth fields contain the month, day, and time,respectively, that the file was last modified. Finally, the ninth fieldcontains the file name.11

The ‘$6 == "Nov"’ in ourawk program is an expression thattests whether the sixth field of the output from ‘ls -l’matches the string ‘Nov’. Each time a line has the string‘Nov’ for its sixth field, the action ‘sum += $5’ isperformed. This adds the fifth field (the file's size) to the variablesum. As a result, whenawk has finished reading all theinput lines,sum is the total of the sizes of the files whoselines matched the pattern. (This works becauseawk variablesare automatically initialized to zero.)

After the last line of output from ls has been processed, theEND rule executes and prints the value ofsum. In this example, the value of sum is 80600.

These more advanced awk techniques are covered in later sections(seeAction Overview). Before you can move on to moreadvancedawk programming, you have to know how awk interpretsyour input and displays your output. By manipulating fields and usingprint statements, you can produce some very useful andimpressive-looking reports.


Next:  ,Previous:  More Complex,Up:  Getting Started

1.6 awk Statements Versus Lines

Most often, each line in anawk program is a separate statement orseparate rule, like this:

     awk '/12/  { print $0 }
          /21/  { print $0 }' BBS-list inventory-shipped

However,gawk ignores newlines after any of the followingsymbols and keywords:

     ,    {    ?    :    ||    &&    do    else

A newline at any other point is considered the end of thestatement.12

If you would like to split a single statement into two lines at a pointwhere a newline would terminate it, you can continue it by ending thefirst line with a backslash character (‘\’). The backslash must bethe final character on the line in order to be recognized as a continuationcharacter. A backslash is allowed anywhere in the statement, evenin the middle of a string or regular expression. For example:

     awk '/This regular expression is too long, so continue it\
      on the next line/ { print $1 }'

We have generally not used backslash continuation in our sample programs.gawk places no limit on thelength of a line, so backslash continuation is never strictly necessary;it just makes programs more readable. For this same reason, as well asfor clarity, we have kept most statements short in the sample programspresented throughout the Web page. Backslash continuation ismost useful when yourawk program is in a separate source fileinstead of entered from the command line. You should also note thatmanyawk implementations are more particular about where youmay use backslash continuation. For example, they may not allow you tosplit a string constant using backslash continuation. Thus, for maximumportability of yourawk programs, it is best not to split yourlines in the middle of a regular expression or a string.

CAUTION: Backslash continuation does not work as describedwith the C shell. It works for awk programs in files andfor one-shot programs, provided you are using a POSIX-compliantshell, such as the Unix Bourne shell or Bash. But the C shell behavesdifferently! There, you must use two backslashes in a row, followed bya newline. Note also that when using the C shell, every newlinein your awk program must be escaped with a backslash. To illustrate:
     % awk 'BEGIN { \
     ?   print \\
     ?       "hello, world" \
     ? }'
     -| hello, world

Here, the ‘%’ and ‘?’ are the C shell's primary and secondaryprompts, analogous to the standard shell's ‘$’ and ‘>’.

Compare the previous example to how it is done with a POSIX-compliant shell:

     $ awk 'BEGIN {
     >   print \
     >       "hello, world"
     > }'
     -| hello, world

awk is a line-oriented language. Each rule's action has tobegin on the same line as the pattern. To have the pattern and actionon separate lines, youmust use backslash continuation; thereis no other option.

Another thing to keep in mind is that backslash continuation andcomments do not mix. As soon asawk sees the ‘#’ thatstarts a comment, it ignoreseverything on the rest of theline. For example:

     $ gawk 'BEGIN { print "dont panic" # a friendly \
     >                                    BEGIN rule
     > }'
     error--> gawk: cmd. line:2:                BEGIN rule
     error--> gawk: cmd. line:2:                ^ parse error

In this case, it looks like the backslash would continue the comment onto thenext line. However, the backslash-newline combination is never evennoticed because it is “hidden” inside the comment. Thus, theBEGIN is noted as a syntax error.

Whenawk statements within one rule are short, you might want to putmore than one of them on a line. This is accomplished by separating the statementswith a semicolon (‘;’). This also applies to the rules themselves. Thus, the program shown at the start of this sectioncould also be written this way:

     /12/ { print $0 } ; /21/ { print $0 }
NOTE: The requirement that states that rules on the same line must beseparated with a semicolon was not in the original awklanguage; it was added for consistency with the treatment of statementswithin an action.


Next:  ,Previous:  Statements/Lines,Up:  Getting Started

1.7 Other Features of awk

The awk language provides a number of predefined, orbuilt-in, variables that your programs can use to get informationfromawk. There are other variables your program can setas well to control howawk processes your data.

In addition, awk provides a number of built-in functions for doingcommon computational and string-related operations.gawk provides built-in functions for working with timestamps,performing bit manipulation, for runtime string translation (internationalization),determining the type of a variable,and array sorting.

As we develop our presentation of the awk language, we introducemost of the variables and many of the functions. They are describedsystematically inBuilt-in Variables, andBuilt-in.


Previous:  Other Features,Up:  Getting Started

1.8 When to Use awk

Now that you've seen some of whatawk can do,you might wonder how awk could be useful for you. By usingutility programs, advanced patterns, field separators, arithmeticstatements, and other selection criteria, you can produce much morecomplex output. The awk language is very useful for producingreports from large amounts of raw data, such as summarizing informationfrom the output of other utility programs likels. (See More Complex.)

Programs written with awk are usually much smaller than they wouldbe in other languages. This makesawk programs easy to compose anduse. Often,awk programs can be quickly composed at your keyboard,used once, and thrown away. Becauseawk programs are interpreted, youcan avoid the (usually lengthy) compilation part of the typicaledit-compile-test-debug cycle of software development.

Complex programs have been written in awk, including a completeretargetable assembler for eight-bit microprocessors (seeGlossary, formore information), and a microcode assembler for a special-purpose Prologcomputer. While the originalawk's capabilities were strained by tasksof such complexity, modern versions are more capable. Even Brian Kernighan'sversion ofawk has fewer predefined limits, and thosethat it has are much larger than they used to be.

If you find yourself writingawk scripts of more than, say, a fewhundred lines, you might consider using a different programminglanguage. Emacs Lisp is a good choice if you need sophisticated stringor pattern matching capabilities. The shell is also good at string andpattern matching; in addition, it allows powerful use of the systemutilities. More conventional languages, such as C, C++, and Java, offerbetter facilities for system programming and for managing the complexityof large programs. Programs in these languages may require more linesof source code than the equivalent awk programs, but they areeasier to maintain and usually run more efficiently.


Next:  ,Previous:  Getting Started,Up:  Top

2 Running awk and gawk

This chapter covers how to run awk, both POSIX-standardand gawk-specific command-line options, and whatawk andgawk do with non-option arguments. It then proceeds to cover how gawk searches for source files,reading standard input along with other files,gawk'senvironment variables, gawk's exit status, using include files,and obsolete and undocumented options and/or features.

Many of the options and features described here are discussed inmore detail later in the Web page; feel free to skip overthings in this chapter that don't interest you right now.


Next:  ,Up:  Invoking Gawk

2.1 Invoking awk

There are two ways to run awk—with an explicit program or withone or more program files. Here are templates for both of them; itemsenclosed in [...] in these templates are optional:

     awk [options] -f progfile [--] file ...
     awk [options] [--] 'program' file ...

Besides traditional one-letter POSIX-style options,gawk alsosupports GNU long options.

It is possible to invokeawk with an empty program:

     awk '' datafile1 datafile2

Doing so makes little sense, though;awk exitssilently when given an empty program. (d.c.) If--lint hasbeen specified on the command line,gawk issues awarning that the program is empty.


Next:  ,Previous:  Command Line,Up:  Invoking Gawk

2.2 Command-Line Options

Options begin with a dash and consist of a single character. GNU-style long options consist of two dashes and a keyword. The keyword can be abbreviated, as long as the abbreviation allows the optionto be uniquely identified. If the option takes an argument, then thekeyword is either immediately followed by an equals sign (‘=’) and theargument's value, or the keyword and the argument's value are separatedby whitespace. If a particular option with a value is given more than once, it is thelast value that counts.

Each long option forgawk has a correspondingPOSIX-style short option. The long and short options areinterchangeable in all contexts. The following list describes options mandated by the POSIX standard:

-F fs --field-separator fs
Set the FS variable to fs(see Field Separators).
-f source-file --file source-file
Read awk program source from source-fileinstead of in the first non-option argument. This option may be given multiple times; the awkprogram consists of the concatenation the contents ofeach specified source-file.
-v var = val --assign var = val
Set the variable var to the value val beforeexecution of the program begins. Such variable values are availableinside the BEGIN rule(see Other Arguments).

The -v option can only set one variable, but it can be usedmore than once, setting another variable each time, like this:‘awk -v foo=1 -v bar=2 ...’.

CAUTION: Using -v to set the values of the built-invariables may lead to surprising results. awk will reset thevalues of those variables as it needs to, possibly ignoring anypredefined value you may have given.

-W gawk-opt
Provide an implementation-specific option. This is the POSIX convention for providing implementation-specific options. These optionsalso have corresponding GNU-style long options. Note that the long options may be abbreviated, as long asthe abbreviations remain unique. The full list of gawk-specific options is provided next.
--
Signal the end of the command-line options. The following argumentsare not treated as options even if they begin with ‘ -’. Thisinterpretation of -- follows the POSIX argument parsingconventions.

This is useful if you have file names that start with ‘-’,or in shell scripts, if you have file names that will be specifiedby the user that could start with ‘-’. It is also useful for passing options on to theawkprogram; see Getopt Function.

The following list describes gawk-specific options:

-b --characters-as-bytes
Cause gawk to treat all input data as single-byte characters. Normally, gawk follows the POSIX standard and attempts to processits input data according to the current locale. This can often involveconverting multibyte characters into wide characters (internally), andcan lead to problems or confusion if the input data does not contain validmultibyte characters. This option is an easy way to tell gawk:“hands off my data!”.
-c --traditional
Specify compatibility mode, in which the GNU extensions tothe awk language are disabled, so that gawk behaves justlike Brian Kernighan's version awk. See POSIX/GNU,which summarizes the extensions. Also see Compatibility Mode.
-C --copyright
Print the short version of the General Public License and then exit.
-d [ file ] --dump-variables [ = file ]
Print a sorted list of global variables, their types, and final valuesto file. If no file is provided, print thislist to the file named awkvars.out in the current directory. No space is allowed between the -d and file, if file is supplied.

Having a list of all global variables is a good way to look fortypographical errors in your programs. You would also use this option if you have a large program with a lot offunctions, and you want to be sure that your functions don'tinadvertently use global variables that you meant to be local. (This is a particularly easy mistake to make with simple variablenames likei, j, etc.)

-e program-text --source program-text
Provide program source code in the program-text. This option allows you to mix source code in files with sourcecode that you enter on the command line. This is particularly usefulwhen you have library functions that you want to use from your command-lineprograms (see AWKPATH Variable).
-E file --exec file
Similar to -f, read awk program text from file. There are two differences from -f:
  • This option terminates option processing; anythingelse on the command line is passed on directly to theawk program.
  • Command-line variable assignments of the form‘var=value’ are disallowed.

This option is particularly necessary for World Wide Web CGI applicationsthat pass arguments through the URL; using this option prevents a malicious(or other) user from passing in options, assignments, orawk sourcecode (via --source) to the CGI application. This option should be usedwith ‘#!’ scripts (seeExecutable Scripts), like so:

          #! /usr/local/bin/gawk -E
          
          awk program here ...

-g --gen-pot
Analyze the source program andgenerate a GNU gettext Portable Object Template file on standardoutput for all string constants that have been marked for translation. See Internationalization,for information about this option.
-h --help
Print a “usage” message summarizing the short and long style optionsthat gawk accepts and then exit.
-L [ value ] --lint [ =value ]
Warn about constructs that are dubious or nonportable toother awk implementations. Some warnings are issued when gawk first reads your program. Othersare issued at runtime, as your program executes. With an optional argument of ‘ fatal’,lint warnings become fatal errors. This may be drastic, but its use will certainly encourage thedevelopment of cleaner awk programs. With an optional argument of ‘ invalid’, only warnings about thingsthat are actually invalid are issued. (This is not fully implemented yet.)

Some warnings are only printed once, even if the dubious constructs theywarn about occur multiple times in yourawk program. Thus,when eliminating problems pointed out by--lint, you should takecare to search for all occurrences of each inappropriate construct. Asawk programs are usually short, doing so is not burdensome.

-n --non-decimal-data
Enable automatic interpretation of octal and hexadecimalvalues in input data(see Nondecimal Data).
CAUTION: This option can severely break old programs. Use with care.

-N --use-lc-numeric
Force the use of the locale's decimal point characterwhen parsing numeric input data (see Locales).
-O --optimize
Enable some optimizations on the internal representation of the program. At the moment this includes just simple constant folding. The gawkmaintainer hopes to add more optimizations over time.
-p [ file ] --profile [ = file ]
Enable profiling of awk programs(see Profiling). By default, profiles are created in a file named awkprof.out. The optional file argument allows you to specify a differentfile name for the profile file. No space is allowed between the -p and file, if file is supplied.

When run with gawk, the profile is just a “pretty printed” versionof the program. When run withpgawk, the profile contains executioncounts for each statement in the program in the left margin, and functioncall counts for each function.

-P --posix
Operate in strict POSIX mode. This disables all gawkextensions (just like --traditional) anddisables all extensions not allowed by POSIX. See Common Extensions, for a summary of the extensionsin gawk that are disabled by this option. Also,the following additionalrestrictions apply:
  • Newlines do not act as whitespace to separate fields when FS isequal to a single space(seeFields).
  • Newlines are not allowed after ‘?’ or ‘:’(seeConditional Exp).

  • Specifying ‘-Ft’ on the command-line does not set the valueofFS to be a single TAB character(see Field Separators).

  • The locale's decimal point character is used for parsing inputdata (see Locales).

If you supply both --traditional and --posix on thecommand line, --posix takes precedence.gawkalso issues a warning if both options are supplied.

-r --re-interval
Allow interval expressions(see Regexp Operators)in regexps. This is now gawk's default behavior. Nevertheless, this option remains both for backward compatibility,and for use in combination with the --traditional option.
-R file --command= file
dgawk only. Read dgawk debugger options and commands from file. See Dgawk Info, for more information.
-S --sandbox
Disable the system() function,input redirections with getline,output redirections with print and printf,and dynamic extensions. This is particularly useful when you want to run awk scriptsfrom questionable sources and need to make sure the scriptscan't access your system (other than the specified input data file).
-t --lint-old
Warn about constructs that are not available in the original version of awk from Version 7 Unix(see V7/SVR3.1).
-V --version
Print version information for this particular copy of gawk. This allows you to determine if your copy of gawk is up to datewith respect to whatever the Free Software Foundation is currentlydistributing. It is also useful for bug reports(see Bugs).

As long as program text has been supplied,any other options are flagged as invalid with a warning message butare otherwise ignored.

In compatibility mode, as a special case, if the value offs suppliedto the -F option is ‘t’, thenFS is set to the TABcharacter ("\t"). This is true only for--traditional and notfor --posix(seeField Separators).

The-f option may be used more than once on the command line. If it is,awk reads its program source from all of the named files, asif they had been concatenated together into one big file. This isuseful for creating libraries ofawk functions. These functionscan be written once and then retrieved from a standard place, insteadof having to be included into each individual program. (As mentioned inDefinition Syntax,function names must be unique.)

With standard awk, library functions can still be used, evenif the program is entered at the terminal,by specifying ‘-f /dev/tty’. After typing your program,typeCtrl-d (the end-of-file character) to terminate it. (You may also use ‘-f -’ to read program source from the standardinput but then you will not be able to also use the standard input as asource of data.)

Because it is clumsy using the standard awk mechanisms to mix sourcefile and command-lineawk programs, gawk provides the--source option. This does not require you to pre-empt the standardinput for your source code; it allows you to easily mix command-lineand library source code(see AWKPATH Variable). The --source option may also be used multiple times on the command line.

If no -f or --source option is specified, thengawkuses the first non-option command-line argument as the text of theprogram source code.

If the environment variablePOSIXLY_CORRECT exists,then gawk behaves in strict POSIX mode, exactly as ifyou had supplied the--posix command-line option. Many GNU programs look for this environment variable to turn onstrict POSIX mode. If--lint is supplied on the command lineandgawk turns on POSIX mode because of POSIXLY_CORRECT,then it issues a warning message indicating that POSIXmode is in effect. You would typically set this variable in your shell's startup file. For a Bourne-compatible shell (such as Bash), you would add theselines to the .profile file in your home directory:

     POSIXLY_CORRECT=true
     export POSIXLY_CORRECT

For a C shell-compatibleshell,13you would add this line to the.login file in your home directory:

     setenv POSIXLY_CORRECT true

HavingPOSIXLY_CORRECT set is not recommended for daily use,but it is good for testing the portability of your programs to otherenvironments.


Next:  ,Previous:  Options,Up:  Invoking Gawk

2.3 Other Command-Line Arguments

Any additional arguments on the command line are normally treated asinput files to be processed in the order specified. However, anargument that has the form var=value, assignsthe value value to the variablevar—it does not specify afile at all. (SeeAssignment Options.)

All these arguments are made available to your awk program in theARGV array (seeBuilt-in Variables). Command-line optionsand the program text (if present) are omitted fromARGV. All other arguments, including variable assignments, areincluded. As each element ofARGV is processed, gawksets the variableARGIND to the index in ARGV of thecurrent element.

The distinction between file name arguments and variable-assignmentarguments is made whenawk is about to open the next input file. At that point in execution, it checks the file name to see whetherit is really a variable assignment; if so,awk sets the variableinstead of reading a file.

Therefore, the variables actually receive the given values after allpreviously specified files have been read. In particular, the values ofvariables assigned in this fashion arenot available inside aBEGIN rule(see BEGIN/END),because such rules are run before awk begins scanning the argument list.

The variable values given on the command line are processed for escapesequences (seeEscape Sequences). (d.c.)

In some earlier implementations of awk, when a variable assignmentoccurred before any file names, the assignment would happenbeforethe BEGIN rule was executed. awk's behavior was thusinconsistent; some command-line assignments were available inside theBEGIN rule, while others were not. Unfortunately,some applications came to dependupon this “feature.” When awk was changed to be more consistent,the-v option was added to accommodate applications that dependedupon the old behavior.

The variable assignment feature is most useful for assigning to variablessuch asRS, OFS, and ORS, which control input andoutput formats before scanning the data files. It is also useful forcontrolling state if multiple passes are needed over a data file. Forexample:

     awk 'pass == 1  { pass 1 stuff }
          pass == 2  { pass 2 stuff }' pass=1 mydata pass=2 mydata

Given the variable assignment feature, the -F option for settingthe value ofFS is notstrictly necessary. It remains for historical compatibility.

2.4 Naming Standard Input

Often, you may wish to read standard input together with other files. For example, you may wish to read one file, read standard input comingfrom a pipe, and then read another file.

The way to name the standard input, with all versions of awk,is to use a single, standalone minus sign or dash, ‘-’. For example:

     some_command | awk -f myprog.awk file1 - file2

Here, awk first readsfile1, then it readsthe output of some_command, and finally it readsfile2.

You may also use "-" to name standard input when readingfiles withgetline (see Getline/File).

In addition, gawk allows you to specify the specialfile name/dev/stdin, both on the command line andwithgetline. Some other versions of awk also support this, but itis not standard. (Some operating systems provide a/dev/stdin filein the file system, however,gawk always processesthis file name itself.)


Next:  ,Previous:  Naming Standard Input,Up:  Invoking Gawk

2.5 The Environment Variables gawk Uses

A number of environment variables influence how gawkbehaves.

2.5.1 The AWKPATH Environment Variable

In most awkimplementations, you must supply a precise path name for each programfile, unless the file is in the current directory. But ingawk, if the file name supplied to the -f optiondoes not contain a ‘/’, thengawk searches a list ofdirectories (called thesearch path), one by one, looking for afile with the specified name.

The search path is a string consisting of directory namesseparated by colons. gawk gets its search path from theAWKPATH environment variable. If that variable does not exist,gawk uses a default path,‘.:/usr/local/share/awk’.14

The search path feature is particularly useful for building librariesof usefulawk functions. The library files can be placed in astandard directory in the default path and then specified onthe command line with a short file name. Otherwise, the full file namewould have to be typed for each file.

By using both the --source and -f options, your command-lineawk programs can use facilities inawk library files(see Library Functions). Path searching is not done if gawk is in compatibility mode. This is true for both--traditional and --posix. SeeOptions.

NOTE: To includethe current directory in the path, either place . explicitly in the path or write a null entry in thepath. (A null entry is indicated by starting or ending the path with acolon or by placing two colons next to each other (‘ ::’).) This path search mechanism is similarto the shell's.

However, gawk always looks in the current directorybeforesearching AWKPATH, so there is no real reason to includethe current directory in the search path.

If AWKPATH is not defined in theenvironment,gawk places its default search path intoENVIRON["AWKPATH"]. This makes it easy to determinethe actual search path thatgawk will usefrom within an awk program.

While you can change ENVIRON["AWKPATH"] within your awkprogram, this has no effect on the running program's behavior. This makessense: theAWKPATH environment variable is used to find the programsource files. Once your program is running, all the files have beenfound, andgawk no longer needs to use AWKPATH.

2.5.2 Other Environment Variables

A number of other environment variables affect gawk'sbehavior, but they are more specialized. Those in the followinglist are meant to be used by regular users.

POSIXLY_CORRECT
Causes gawk to switch POSIX compatibilitymode, disabling all traditional and GNU extensions. See Options.
GAWK_SOCK_RETRIES
Controls the number of time gawk will attempt toretry a two-way TCP/IP (socket) connection before giving up. See TCP/IP Networking.
GAWK_MSEC_SLEEP
Specifies the interval between connection retries,in milliseconds. On systems that do not supportthe usleep() system call,the value is rounded up to an integral number of seconds.

The environment variables in the following list are meantfor use by the gawk developers for testing and tuning. They are subject to change. The variables are:

AVG_CHAIN_MAX
The average number of items gawk will maintain on ahash chain for managing arrays.
AWK_HASH
If this variable exists with a value of ‘ gst’, gawkwill switch to using the hash function from GNU Smalltalk formanaging arrays. This function may be marginally faster than the standard function.
AWKREADFUNC
If this variable exists, gawk switches to reading sourcefiles one line at a time, instead of reading in blocks. This existsfor debugging problems on filesystems on non-POSIX operating systemswhere I/O is performed in records, not in blocks.
GAWK_NO_DFA
If this variable exists, gawk does not use the DFA regexp matcherfor “does it match” kinds of tests. This can cause gawkto be slower. Its purpose is to help isolate differences between thetwo regexp matchers that gawk uses internally. (There aren'tsupposed to be differences, but occasionally theory and practice don'tcoordinate with each other.)
GAWK_STACKSIZE
This specifies the amount by which gawk should grow itsinternal evaluation stack, when needed.
TIDYMEM
If this variable exists, gawk uses the mtrace() librarycalls from GNU LIBC to help track down possible memory leaks.

2.6 gawk's Exit Status

If the exit statement is used with a value(see Exit Statement), thengawk exits withthe numeric value given to it.

Otherwise, if there were no problems during execution,gawk exits with the value of the C constantEXIT_SUCCESS. This is usually zero.

If an error occurs, gawk exits with the value ofthe C constantEXIT_FAILURE. This is usually one.

If gawk exits because of a fatal error, the exitstatus is 2. On non-POSIX systems, this value may be mappedtoEXIT_FAILURE.


Next:  ,Previous:  Exit Status,Up:  Invoking Gawk

2.7 Including Other Files Into Your Program

<!-- Panos Papadopoulos contributed the original -->

This section describes a feature that is specific to gawk.

The ‘@include’ keyword can be used to read externalawk sourcefiles. This gives you the ability to split largeawk source filesinto smaller, more manageable pieces, and also lets you reuse commonawkcode from various awk scripts. In other words, you can grouptogetherawk functions, used to carry out specific tasks,into external files. These files can be used just like function libraries,using the ‘@include’ keyword in conjunction with theAWKPATHenvironment variable.

Let's see an example. We'll start with two (trivial) awk scripts, namelytest1 andtest2. Here is the test1 script:

     BEGIN {
         print "This is script test1."
     }

and here is test2:

     @include "test1"
     BEGIN {
         print "This is script test2."
     }

Running gawk with test2produces the following result:

     $ gawk -f test2
     -| This is file test1.
     -| This is file test2.

gawk runs the test2 script which includestest1using the ‘@include’keyword. So, to include externalawk source files you justuse ‘@include’ followed by the name of the file to be included,enclosed in double quotes.

NOTE: Keep in mind that this is a language construct and the file name cannotbe a string variable, but rather just a literal string in double quotes.

The files to be included may be nested; e.g., given a thirdscript, namely test3:

     @include "test2"
     BEGIN {
         print "This is script test3."
     }

Running gawk with thetest3 script produces thefollowing results:

     $ gawk -f test3
     -| This is file test1.
     -| This is file test2.
     -| This is file test3.

The file name can, of course, be a pathname. For example:

     @include "../io_funcs"

or:

     @include "/usr/awklib/network"

are valid. The AWKPATH environment variable can be of greatvalue when using ‘@include’. The same rules for the useof theAWKPATH variable in command-line file searches(see AWKPATH Variable) apply to‘@include’ also.

This is very helpful in constructing gawk function libraries. If you have a large script with useful, general purposeawkfunctions, you can break it down into library files and put those filesin a special directory. You can then include those “libraries,” usingeither the full pathnames of the files, or by setting theAWKPATHenvironment variable accordingly and then using ‘@include’ withjust the file part of the full pathname. Of course you can have morethan one directory to keep library files; the more complex the workingenvironment is, the more directories you may need to organize the filesto be included.

Given the ability to specify multiple -f options, the‘@include’ mechanism is not strictly necessary. However, the ‘@include’ keywordcan help you in constructing self-contained gawk programs,thus reducing the need for writing complex and tedious command lines. In particular, ‘@include’ is very useful for writing CGI scriptsto be run from web pages.

As mentioned in AWKPATH Variable, the current directory is alwayssearched first for source files, before searching inAWKPATH,and this also applies to files named with ‘@include’.


Next:  ,Previous:  Include Files,Up:  Invoking Gawk

2.8 Obsolete Options and/or Features

This section describes features and/or command-line options fromprevious releases of gawk that are either not available in thecurrent version or that are still supported but deprecated (meaning thatthey willnot be in the next release).

The process-related special files/dev/pid, /dev/ppid,/dev/pgrpid, and/dev/user were deprecated in gawk3.1, but still worked. As of version 4.0, they are no longerinterpreted specially bygawk. (Use PROCINFO instead;seeAuto-set.)


Previous:  Obsolete,Up:  Invoking Gawk

2.9 Undocumented Options and Features

Use the Source, Luke!
Obi-Wan

This section intentionally leftblank.


Next:  ,Previous:  Invoking Gawk,Up:  Top

3 Regular Expressions

Aregular expression, or regexp, is a way of describing aset of strings. Because regular expressions are such a fundamental part ofawkprogramming, their format and use deserve a separate chapter.

A regular expression enclosed in slashes (‘/’)is anawk pattern that matches every input record whose textbelongs to that set. The simplest regular expression is a sequence of letters, numbers, orboth. Such a regexp matches any string that contains that sequence. Thus, the regexp ‘foo’ matches any string containing ‘foo’. Therefore, the pattern/foo/ matches any input record containingthe three characters ‘fooanywhere in the record. Otherkinds of regexps let you specify more complicated classes of strings.

Initially, the examples in this chapter are simple. As we explain more about howregular expressions work, we present more complicated instances.


Next:  ,Up:  Regexp

3.1 How to Use Regular Expressions

A regular expression can be used as a pattern by enclosing it inslashes. Then the regular expression is tested against theentire text of each record. (Normally, it only needsto match some part of the text in order to succeed.) For example, thefollowing prints the second field of each record that contains the string‘foo’ anywhere in it:

     $ awk '/foo/ { print $2 }' BBS-list
     -| 555-1234
     -| 555-6699
     -| 555-6480
     -| 555-2127

Regular expressions can also be used in matching expressions. Theseexpressions allow you to specify the string to match against; it neednot be the entire current input record. The two operators ‘~’and ‘!~’ perform regular expression comparisons. Expressionsusing these operators can be used as patterns, or inif,while, for, and do statements. (SeeStatements.) For example:

     exp ~ /regexp/

is true if the expression exp (taken as a string)matchesregexp. The following example matches, or selects,all input records with the uppercase letter ‘J’ somewhere in thefirst field:

     $ awk '$1 ~ /J/' inventory-shipped
     -| Jan  13  25  15 115
     -| Jun  31  42  75 492
     -| Jul  24  34  67 436
     -| Jan  21  36  64 620

So does this:

     awk '{ if ($1 ~ /J/) print }' inventory-shipped

This next example is true if the expression exp(taken as a character string)doesnot match regexp:

     exp !~ /regexp/

The following example matches,or selects, all input records whose first field does not containthe uppercase letter ‘J’:

     $ awk '$1 !~ /J/' inventory-shipped
     -| Feb  15  32  24 226
     -| Mar  15  24  34 228
     -| Apr  31  52  63 420
     -| May  16  34  29 208
     ...

When a regexp is enclosed in slashes, such as/foo/, we call ita regexp constant, much like 5.27 is a numeric constant and"foo" is a string constant.


Next:  ,Previous:  Regexp Usage,Up:  Regexp

3.2 Escape Sequences

Some characters cannot be included literally in string constants("foo") or regexp constants (/foo/). Instead, they should be represented withescape sequences,which are character sequences beginning with a backslash (‘\’). One use of an escape sequence is to include a double-quote character ina string constant. Because a plain double quote ends the string, youmust use ‘\"’ to represent an actual double-quote character as apart of the string. For example:

     $ awk 'BEGIN { print "He said \"hi!\" to her." }'
     -| He said "hi!" to her.

The backslash character itself is another character that cannot beincluded normally; you must write ‘\\’ to put one backslash in thestring or regexp. Thus, the string whose contents are the two characters‘"’ and ‘\’ must be written "\"\\".

Other escape sequences represent unprintable characterssuch as TAB or newline. While there is nothing to stop you from entering mostunprintable characters directly in a string constant or regexp constant,they may look ugly.

The following table listsall the escape sequences used in awk andwhat they represent. Unless noted otherwise, all these escapesequences apply to both string constants and regexp constants:

\\
A literal backslash, ‘ \’.


\a
The “alert” character, Ctrl-g, ASCII code 7 (BEL). (This usually makes some sort of audible noise.)


\b
Backspace, Ctrl-h, ASCII code 8 (BS).


\f
Formfeed, Ctrl-l, ASCII code 12 (FF).


\n
Newline, Ctrl-j, ASCII code 10 (LF).


\r
Carriage return, Ctrl-m, ASCII code 13 (CR).


\t
Horizontal TAB, Ctrl-i, ASCII code 9 (HT).


\v
Vertical tab, Ctrl-k, ASCII code 11 (VT).


\ nnn
The octal value nnn, where nnn stands for 1 to 3 digitsbetween ‘ 0’ and ‘ 7’. For example, the code for the ASCII ESC(escape) character is ‘ \033’.


\x hh ...
The hexadecimal value hh, where hh stands for a sequenceof hexadecimal digits (‘ 0’–‘ 9’, and either ‘ A’–‘ F’or ‘ a’–‘ f’). Like the same constructin ISO C, the escape sequence continues until the first nonhexadecimaldigit is seen. (c.e.) However, using more than two hexadecimal digits producesundefined results. (The ‘ \x’ escape sequence is not allowed inPOSIX awk.)


\/
A literal slash (necessary for regexp constants only). This sequence is used when you want to write a regexpconstant that contains a slash. Because the regexp is delimited byslashes, you need to escape the slash that is part of the pattern,in order to tell awk to keep processing the rest of the regexp.


\"
A literal double quote (necessary for string constants only). This sequence is used when you want to write a stringconstant that contains a double quote. Because the string is delimited bydouble quotes, you need to escape the quote that is part of the string,in order to tell awk to keep processing the rest of the string.

In gawk, a number of additional two-character sequences that beginwith a backslash have special meaning in regexps. SeeGNU Regexp Operators.

In a regexp, a backslash before any character that is not in the previous listand not listed inGNU Regexp Operators,means that the next character should be taken literally, even if it wouldnormally be a regexp operator. For example, /a\+b/ matches the threecharacters ‘a+b’.

For complete portability, do not use a backslash before any character notshown in the previous list.

To summarize:

  • The escape sequences in the table above are always processed first,for both string constants and regexp constants. This happens very early,as soon asawk reads your program.
  • gawk processes both regexp constants and dynamic regexps(seeComputed Regexps),for the special operators listed inGNU Regexp Operators.
  • A backslash before any other character means to treat that characterliterally.
Advanced Notes: Backslash Before Regular Characters

If you place a backslash in a string constant before something that isnot one of the characters previously listed, POSIXawk purposelyleaves what happens as undefined. There are two choices:

Strip the backslash out
This is what Brian Kernighan's awk and gawk both do. For example, "a\qc" is the same as "aqc". (Because this is such an easy bug both to introduce and to miss, gawk warns you about it.) Consider ‘ FS = "[ \t]+\|[ \t]+"’ to use vertical barssurrounded by whitespace as the field separator. There should betwo backslashes in the string: ‘ FS = "[ \t]+\\|[ \t]+"’.)


Leave the backslash alone
Some other awk implementations do this. In such implementations, typing "a\qc" is the same as typing "a\\qc".

Advanced Notes: Escape Sequences for Metacharacters

Suppose you use an octal or hexadecimalescape to represent a regexp metacharacter. (SeeRegexp Operators.) Does awk treat the character as a literal character or as a regexpoperator?

Historically, such characters were taken literally. (d.c.) However, the POSIX standard indicates that they should be treatedas real metacharacters, which is whatgawk does. In compatibility mode (see Options),gawk treats the characters represented by octal and hexadecimalescape sequences literally when used in regexp constants. Thus,/a\52b/ is equivalent to/a\*b/.


Next:  ,Previous:  Escape Sequences,Up:  Regexp

3.3 Regular Expression Operators

You can combine regular expressions with special characters,calledregular expression operators or metacharacters, toincrease the power and versatility of regular expressions.

The escape sequences describedearlierin Escape Sequences,are valid inside a regexp. They are introduced by a ‘\’ andare recognized and converted into corresponding real characters asthe very first step in processing regexps.

Here is a list of metacharacters. All characters that are not escapesequences and that are not listed in the table stand for themselves:

\
This is used to suppress the special meaning of a character whenmatching. For example, ‘ \$’matches the character ‘ $’.


^
This matches the beginning of a string. For example, ‘ ^@chapter’matches ‘ @chapter’ at the beginning of a string and can be usedto identify chapter beginnings in Texinfo source files. The ‘ ^’ is known as an anchor, because it anchors the pattern tomatch only at the beginning of the string.

It is important to realize that ‘^’ does not match the beginning ofa line embedded in a string. The condition is not true in the following example:

          if ("line1\nLINE 2" ~ /^L/) ...


$
This is similar to ‘ ^’, but it matches only at the end of a string. For example, ‘ p$’matches a record that ends with a ‘ p’. The ‘ $’ is an anchorand does not match the end of a line embedded in a string. The condition in the following example is not true:
          if ("line1\nLINE 2" ~ /1$/) ...


. (period)
This matches any single character, including the newline character. For example, ‘ .P’matches any single character followed by a ‘ P’ in a string. Usingconcatenation, we can make a regular expression such as ‘ U.A’, whichmatches any three-character sequence that begins with ‘ U’ and endswith ‘ A’.

In strict POSIX mode (seeOptions),‘.’ does not match thenulcharacter, which is a character with all bits equal to zero. Otherwise,nul is just another character. Other versions of awkmay not be able to match thenul character.


[...]
This is called a bracket expression. 15It matches any one of the characters that are enclosed inthe square brackets. For example, ‘ [MVX]’ matches any one ofthe characters ‘ M’, ‘ V’, or ‘ X’ in a string. A fulldiscussion of what can be inside the square brackets of a bracket expressionis given in Bracket Expressions.


[^ ...]
This is a complemented bracket expression. The first character afterthe ‘ [must be a ‘ ^’. It matches any characters except those in the square brackets. For example, ‘ [^awk]’matches any character that is not an ‘ a’, ‘ w’,or ‘ k’.


|
This is the alternation operator and it is used to specifyalternatives. The ‘ |’ has the lowest precedence of all the regularexpression operators. For example, ‘ ^P|[[:digit:]]’matches any string that matches either ‘ ^P’ or ‘ [[:digit:]]’. Thismeans it matches any string that starts with ‘ P’ or contains a digit.

The alternation applies to the largest possible regexps on either side.


(...)
Parentheses are used for grouping in regular expressions, as inarithmetic. They can be used to concatenate regular expressionscontaining the alternation operator, ‘ |’. For example,‘ @(samp|code)\{[^}]+\}’ matches both ‘ @code{foo}’ and‘ @samp{bar}’. (These are Texinfo formatting control sequences. The ‘ +’ isexplained further on in this list.)


*
This symbol means that the preceding regular expression should berepeated as many times as necessary to find a match. For example, ‘ ph*’applies the ‘ *’ symbol to the preceding ‘ h’ and looks for matchesof one ‘ p’ followed by any number of ‘ h’s. This also matchesjust ‘ p’ if no ‘ h’s are present.

The ‘*’ repeats the smallest possible preceding expression. (Use parentheses if you want to repeat a larger expression.) It findsas many repetitions as possible. For example,‘awk '/\(c[ad][ad]*r x\)/ { print }' sample’prints every record in sample containing a string of the form‘(car x)’, ‘(cdr x)’, ‘(cadr x)’, and so on. Notice the escaping of the parentheses by preceding themwith backslashes.


+
This symbol is similar to ‘ *’, except that the preceding expression must bematched 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. The following is a simplerway of writing the last ‘ *’ example:
          awk '/\(c[ad]+r x\)/ { print }' sample


?
This symbol is similar to ‘ *’, except that the preceding expression can bematched either once or not at all. For example, ‘ fe?d’matches ‘ fed’ and ‘ fd’, but nothing else.


{ n } { n ,} { n , m }
One or two numbers inside braces denote an interval expression. If there is one number in the braces, the preceding regexp is repeated n times. If there are two numbers separated by a comma, the preceding regexp isrepeated n to m times. If there is one number followed by a comma, then the preceding regexpis repeated at least n times:
wh{3}y
Matches ‘ whhhy’, but not ‘ why’ or ‘ whhhhy’.
wh{3,5}y
Matches ‘ whhhy’, ‘ whhhhy’, or ‘ whhhhhy’, only.
wh{2,}y
Matches ‘ whhy’ or ‘ whhhy’, and so on.

Interval expressions were not traditionally available inawk. They were added as part of the POSIX standard to makeawkand egrep consistent with each other.

Initially, because old programs may use ‘{’ and ‘}’ in regexpconstants,gawk did not match interval expressionsin regexps.

However, beginning with version 4.0,gawk does match interval expressions by default. This is because compatibility with POSIX has become moreimportant to mostgawk users than compatibility withold programs.

For programs that use ‘{’ and ‘}’ in regexp constants,it is good practice to always escape them with a backslash. Then theregexp constants are valid and work the way you want them to, usingany version of awk.16

In regular expressions, the ‘*’, ‘+’, and ‘?’ operators,as well as the braces ‘{’ and ‘}’,havethe highest precedence, followed by concatenation, and finally by ‘|’. As in arithmetic, parentheses can change how operators are grouped.

In POSIXawk and gawk, the ‘*’, ‘+’, and‘?’ operators stand for themselves when there is nothing in theregexp that precedes them. For example, /+/ matches a literalplus sign. However, many other versions ofawk treat such ausage as a syntax error.

If gawk is in compatibility mode (seeOptions), intervalexpressions are not available in regular expressions.


Next:  ,Previous:  Regexp Operators,Up:  Regexp

3.4 Using Bracket Expressions

As mentioned earlier, a bracket expression matches any character amongstthose listed between the opening and closing square brackets.

Within a bracket expression, a range expression consists of twocharacters separated by a hyphen. It matches any single character thatsorts between the two characters, based upon the system's native characterset. For example, ‘[0-9]’ is equivalent to ‘[0123456789]’. (See Ranges and Locales, for an explanation of how the POSIXstandard and gawk have changed over time. This is mainlyof historical interest.)

To include one of the characters ‘\’, ‘]’, ‘-’, or ‘^’ in abracket expression, put a ‘\’ in front of it. For example:

     [d\]]

matches either ‘d’ or ‘]’.

This treatment of ‘\’ in bracket expressionsis compatible with otherawkimplementations and is also mandated by POSIX. The regular expressions inawk are a supersetof the POSIX specification for Extended Regular Expressions (EREs). POSIX EREs are based on the regular expressions accepted by thetraditionalegrep utility.

Character classes are a feature introduced in the POSIX standard. A character class is a special notation for describinglists of characters that have a specific attribute, but theactual characters can vary from country to country and/orfrom character set to character set. For example, the notion of whatis an alphabetic character differs between the United States and France.

A character class is only valid in a regexp inside thebrackets of a bracket expression. Character classes consist of ‘[:’,a keyword denoting the class, and ‘:]’.table-char-classes lists the character classes defined by thePOSIX standard.

ClassMeaning
[:alnum:]Alphanumeric characters.
[:alpha:]Alphabetic characters.
[:blank:]Space and TAB characters.
[:cntrl:]Control characters.
[:digit:]Numeric characters.
[:graph:]Characters that are both printable and visible. (A space is printable but not visible, whereas an ‘a’ is both.)
[:lower:]Lowercase alphabetic characters.
[:print:]Printable characters (characters that are not control characters).
[:punct:]Punctuation characters (characters that are not letters, digits,control characters, or space characters).
[:space:]Space characters (such as space, TAB, and formfeed, to name a few).
[:upper:]Uppercase alphabetic characters.
[:xdigit:]Characters that are hexadecimal digits.

Table 3.1: POSIX Character Classes

For example, before the POSIX standard, you had to write /[A-Za-z0-9]/to match alphanumeric characters. If yourcharacter set had other alphabetic characters in it, this would notmatch them. With the POSIX character classes, you can write/[[:alnum:]]/ to match the alphabeticand numeric characters in your character set.

Two additional special sequences can appear in bracket expressions. These apply to non-ASCII character sets, which can have single symbols(called collating elements) that are represented with more than onecharacter. They can also have several characters that are equivalent forcollating, or sorting, purposes. (For example, in French, a plain “e”and a grave-accented “è” are equivalent.) These sequences are:

Collating symbols
Multicharacter collating elements enclosed between‘ [.’ and ‘ .]’. For example, if ‘ ch’ is a collating element,then [[.ch.]] is a regexp that matches this collating element, whereas [ch] is a regexp that matches either ‘ c’ or ‘ h’.


Equivalence classes
Locale-specific names for a list ofcharacters that are equal. The name is enclosed between‘ [=’ and ‘ =]’. For example, the name ‘ e’ might be used to represent all of“e,” “è,” and “é.” In this case, [[=e=]] is a regexpthat matches any of ‘ e’, ‘ é’, or ‘ è’.

These features are very valuable in non-English-speaking locales.

CAUTION: The library functions that gawk uses for regularexpression matching currently recognize only POSIX character classes;they do not recognize collating symbols or equivalence classes.


Next:  ,Previous:  Bracket Expressions,Up:  Regexp

3.5 gawk-Specific Regexp Operators

GNU software that deals with regular expressions provides a number ofadditional regexp operators. These operators are described in thissection and are specific togawk;they are not available in other awk implementations. Most of the additional operators deal with word matching. For our purposes, aword is a sequence of one or more letters, digits,or underscores (‘_’):

\s
Matches any whitespace character. Think of it as shorthand for [[:space:]].


\S
Matches any character that is not whitespace. Think of it as shorthand for [^[:space:]].


\w
Matches any word-constituent character—that is, it matches anyletter, digit, or underscore. Think of it as shorthand for [[:alnum:]_].


\W
Matches any character that is not word-constituent. Think of it as shorthand for [^[:alnum:]_].


\<
Matches the empty string at the beginning of a word. For example, /\<away/ matches ‘ away’ but not‘ stowaway’. <!-- @cindex operators, @code{\>} (@command{gawk}) -->


\>
Matches the empty string at the end of a word. For example, /stow\>/ matches ‘ stow’ but not ‘ stowaway’.


\y
Matches the empty string at either the beginning or theend of a word (i.e., the word boundar y). For example, ‘ \yballs?\y’matches either ‘ ball’ or ‘ balls’, as a separate word.


\B
Matches the empty string that occurs between twoword-constituent characters. For example, /\Brat\B/ matches ‘ crate’ but it does not match ‘ dirty rat’. ‘ \B’ is essentially the opposite of ‘ \y’.

There are two other operators that work on buffers. In Emacs, abuffer is, naturally, an Emacs buffer. For other programs,gawk's regexp library routines consider the entirestring to match as the buffer. The operators are:

\`
Matches the empty string at thebeginning of a buffer (string).


\'
Matches the empty string at theend of a buffer (string).

Because ‘^’ and ‘$’ always work in terms of the beginningand end of strings, these operators don't add any new capabilitiesforawk. They are provided for compatibility with otherGNU software.

In other GNU software, the word-boundary operator is ‘\b’. However,that conflicts with theawk language's definition of ‘\b’as backspace, sogawk uses a different letter. An alternative method would have been to require two backslashes in theGNU operators, but this was deemed too confusing. The currentmethod of using ‘\y’ for the GNU ‘\b’ appears to be thelesser of two evils.

The various command-line options(seeOptions)control how gawk interprets characters in regexps:

No options
In the default case, gawk provides all the facilities ofPOSIX regexps and thepreviously describedGNU regexp operators. GNU regexp operators describedin Regexp Operators.
--posix
Only POSIX regexps are supported; the GNU operators are not special(e.g., ‘ \w’ matches a literal ‘ w’). Interval expressionsare allowed.
--traditional
Traditional Unix awk regexps are matched. The GNU operatorsare not special, and interval expressions are not available. The POSIX character classes ( [[:alnum:]], etc.) are supported,as Brian Kernighan's awk does support them. Characters described by octal and hexadecimal escape sequences aretreated literally, even if they represent regexp metacharacters.
--re-interval
Allow interval expressions in regexps, if --traditionalhas been provided. Otherwise, interval expressions are available by default.


Next:  ,Previous:  GNU Regexp Operators,Up:  Regexp

3.6 Case Sensitivity in Matching

Case is normally significant in regular expressions, both when matchingordinary characters (i.e., not metacharacters) and inside bracketexpressions. Thus, a ‘w’ in a regular expression matches only a lowercase‘w’ and not an uppercase ‘W’.

The simplest way to do a case-independent match is to use a bracketexpression—for example, ‘[Ww]’. However, this can be cumbersome ifyou need to use it often, and it can make the regular expressions harderto read. There are two alternatives that you might prefer.

One way to perform a case-insensitive match at a particular point in theprogram is to convert the data to a single case, using thetolower() ortoupper() built-in string functions (which wehaven't discussed yet;seeString Functions). For example:

     tolower($1) ~ /foo/  { ... }

converts the first field to lowercase before matching against it. This works in any POSIX-compliantawk.

Another method, specific to gawk, is to set the variableIGNORECASE to a nonzero value (seeBuilt-in Variables). When IGNORECASE is not zero,all regexp and stringoperations ignore case. Changing the value ofIGNORECASE dynamically controls the case-sensitivity of theprogram as it runs. Case is significant by default becauseIGNORECASE (like most variables) is initialized to zero:

     x = "aB"
     if (x ~ /ab/) ...   # this test will fail
     
     IGNORECASE = 1
     if (x ~ /ab/) ...   # now it will succeed

In general, you cannot use IGNORECASE to make certain rulescase-insensitive and other rules case-sensitive, because there is nostraightforward wayto setIGNORECASE just for the pattern ofa particular rule.17To do this, use either bracket expressions ortolower(). However, onething you can do with IGNORECASE only is dynamically turncase-sensitivity on or off for all the rules at once.

IGNORECASE can be set on the command line or in a BEGIN rule(seeOther Arguments; alsosee Using BEGIN/END). Setting IGNORECASE from the command line is a way to makea program case-insensitive without having to edit it.

Both regexp and string comparisonoperations are affected by IGNORECASE.

In multibyte locales,the equivalences between upper-and lowercase characters are tested based on the wide-character values ofthe locale's character set. Otherwise, the characters are tested basedon the ISO-8859-1 (ISO Latin-1)character set. This character set is a superset of the traditional 128ASCII characters, which also provides a number of characters suitablefor use with European languages.18

The value of IGNORECASE has no effect if gawk is incompatibility mode (seeOptions). Case is always significant in compatibility mode.


Next:  ,Previous:  Case-sensitivity,Up:  Regexp

3.7 How Much Text Matches?

Consider the following:

     echo aaaabcd | awk '{ sub(/a+/, "<A>"); print }'

This example uses the sub() function (which we haven't discussed yet;seeString Functions)to make a change to the input record. Here, the regexp/a+/indicates “one or more ‘a’ characters,” and the replacementtext is ‘<A>’.

The input contains four ‘a’ characters.awk (and POSIX) regular expressions always matchthe leftmost,longest sequence of input characters that canmatch. Thus, all four ‘a’ characters arereplaced with ‘<A>’ in this example:

     $ echo aaaabcd | awk '{ sub(/a+/, "<A>"); print }'
     -| <A>bcd

For simple match/no-match tests, this is not so important. But when doingtext matching and substitutions with thematch(), sub(), gsub(),and gensub() functions, it is very important. Understanding this principle is also important for regexp-based recordand field splitting (seeRecords,and also see Field Separators).


Previous:  Leftmost Longest,Up:  Regexp

3.8 Using Dynamic Regexps

The righthand side of a ‘~’ or ‘!~’ operator need not be aregexp constant (i.e., a string of characters between slashes). It maybe any expression. The expression is evaluated and converted to a stringif necessary; the contents of the string are then used as theregexp. A regexp computed in this way is called adynamicregexp:

     BEGIN { digits_regexp = "[[:digit:]]+" }
     $0 ~ digits_regexp    { print }

This sets digits_regexp to a regexp that describes one or more digits,and tests whether the input record matches this regexp.

NOTE: When using the ‘ ~’ and ‘ !~’operators, there is a difference between a regexp constantenclosed in slashes and a string constant enclosed in double quotes. If you are going to use a string constant, you have to understand thatthe string is, in essence, scanned twice: the first time when awk reads your program, and the second time when it goes tomatch the string on the lefthand side of the operator with the patternon the right. This is true of any string-valued expression (such as digits_regexp, shown previously), not just string constants.

What difference does it make if the string isscanned twice? The answer has to do with escape sequences, and particularlywith backslashes. To get a backslash into a regular expression inside astring, you have to type two backslashes.

For example, /\*/ is a regexp constant for a literal ‘*’. Only one backslash is needed. To do the same thing with a string,you have to type"\\*". The first backslash escapes thesecond one so that the string actually contains thetwo characters ‘\’ and ‘*’.

Given that you can use both regexp and string constants to describeregular expressions, which should you use? The answer is “regexpconstants,” for several reasons:

  • String constants are more complicated to write andmore difficult to read. Using regexp constants makes your programsless error-prone. Not understanding the difference between the twokinds of constants is a common source of errors.
  • It is more efficient to use regexp constants. awk can notethat you have supplied a regexp and store it internally in a form thatmakes pattern matching more efficient. When using a string constant,awk must first convert the string into this internal form andthen perform the pattern matching.
  • Using regexp constants is better form; it shows clearly that youintend a regexp match.
Advanced Notes: Using \n in Bracket Expressions of Dynamic Regexps

Some commercial versions ofawk do not allow the newlinecharacter to be used inside a bracket expression for a dynamic regexp:

     $ awk '$0 ~ "[ \t\n]"'
     error--> awk: newline in character class [
     error--> ]...
     error-->  source line number 1
     error-->  context is
     error-->          >>>  <<<

But a newline in a regexp constant works with no problem:

     $ awk '$0 ~ /[ \t\n]/'
     here is a sample line
     -| here is a sample line
     Ctrl-d

gawk does not have this problem, and it isn't likely tooccur often in practice, but it's worth noting for future reference.


Next:  ,Previous:  Regexp,Up:  Top

4 Reading Input Files

In the typicalawk program,awk reads all input either from thestandard input (by default, this is the keyboard, but often it is a pipe from anothercommand) or from files whose names you specify on the awkcommand line. If you specify input files,awk reads themin order, processing all the data from one before going on to the next. The name of the current input file can be found in the built-in variableFILENAME(seeBuilt-in Variables).

The input is read in units calledrecords, and is processed by therules of your program one record at a time. By default, each record is one line. Eachrecord is automatically split into chunks calledfields. This makes it more convenient for programs to work on the parts of a record.

On rare occasions, you may need to use thegetline command. The getline command is valuable, both because itcan do explicit input from any number of files, and because the filesused with it do not have to be named on theawk command line(see Getline).


Next:  ,Up:  Reading Files

4.1 How Input Is Split into Records

Theawk utility divides the input for your awkprogram into records and fields. awk keeps track of the number of records that havebeen readso farfrom the current input file. This value is stored in abuilt-in variable calledFNR. It is reset to zero when a newfile is started. Another built-in variable,NR, records the totalnumber of input records read so far from all data files. It starts at zero,but is never automatically reset to zero.

Records are separated by a character called therecord separator. By default, the record separator is the newline character. This is why records are, by default, single lines. A different character can be used for the record separator byassigning the character to the built-in variableRS.

Like any other variable,the value ofRS can be changed in the awk programwith the assignment operator, ‘=’(seeAssignment Ops). The new record-separator character should be enclosed in quotation marks,which indicate a string constant. Often the right time to do this isat the beginning of execution, before any input is processed,so that the very first record is read with the proper separator. To do this, use the specialBEGIN pattern(see BEGIN/END). For example:

     awk 'BEGIN { RS = "/" }
          { print $0 }' BBS-list

changes the value of RS to "/", before reading any input. This is a string whose first character is a slash; as a result, recordsare separated by slashes. Then the input file is read, and the secondrule in theawk program (the action with no pattern) prints eachrecord. Because eachprint statement adds a newline at the end ofits output, this awk program copies the inputwith each slash changed to a newline. Here are the results of runningthe program onBBS-list:

     $ awk 'BEGIN { RS = "/" }
     >      { print $0 }' BBS-list
     -| 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
     -|

Note that the entry for the ‘camelot’ BBS is not split. In the original data file(seeSample Data Files),the line looks like this:

     camelot      555-0542     300               C

It has one baud rate only, so there are no slashes in the record,unlike the others which have two or more baud rates. In fact, this record is treated as part of the recordfor the ‘core’ BBS; the newline separating them in the outputis the original newline in the data file, not the one added byawk when it printed the record!

Another way to change the record separator is on the command line,using the variable-assignment feature(seeOther Arguments):

     awk '{ print $0 }' RS="/" BBS-list

This sets RS to ‘/’ before processingBBS-list.

Using an unusual character such as ‘/’ for the record separatorproduces correct behavior in the vast majority of cases. However,the following (extreme) pipeline prints a surprising ‘1’:

     $ echo | awk 'BEGIN { RS = "a" } ; { print NF }'
     -| 1

There is one field, consisting of a newline. The value of the built-invariableNF is the number of fields in the current record.

Reaching the end of an input file terminates the current input record,even if the last character in the file is not the character inRS. (d.c.)

The empty string"" (a string without any characters)has a special meaningas the value ofRS. It means that records are separatedby one or more blank lines and nothing else. SeeMultiple Line, for more details.

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 recordcurrently being processed, as well as records already processed, are notaffected.

After the end of the record has been determined, gawksets the variableRT to the text in the input that matchedRS.

When usinggawk,the value of RS is not limited to a one-characterstring. It can be any regular expression(seeRegexp). (c.e.) In general, each recordends at the next string that matches the regular expression; the nextrecord starts at the end of the matching string. This general rule isactually at work in the usual case, whereRS contains just anewline: a record ends at the beginning of the next matching string (thenext newline in the input), and the following record starts just afterthe end of this string (at the first character of the following line). The newline, because it matches RS, is not part of either record.

When RS is a single character, RTcontains the same single character. However, whenRS is aregular expression, RT containsthe actual input text that matched the regular expression.

If the input file ended without any text that matches RS,gawk setsRT to the null string.

The following example illustrates both of these features. It sets RS equal to a regular expression thatmatches either a newline or a series of one or more uppercase letterswith optional leading and/or trailing whitespace:

     $ echo record 1 AAAA record 2 BBBB record 3 |
     > gawk 'BEGIN { RS = "\n|( *[[:upper:]]+ *)" }
     >             { print "Record =", $0, "and RT =", RT }'
     -| Record = record 1 and RT =  AAAA
     -| Record = record 2 and RT =  BBBB
     -| Record = record 3 and RT =
     -|

The final line of output has an extra blank line. This is because thevalue ofRT is a newline, and the print statementsupplies its own terminating newline. SeeSimple Sed, for a more useful exampleof RS as a regexp andRT.

If you set RS to a regular expression that allows optionaltrailing text, such as ‘RS = "abc(XYZ)?"’ it is possible, dueto implementation constraints, thatgawk may match the leadingpart of the regular expression, but not the trailing part, particularlyif the input text that could match the trailing part is fairly long.gawk attempts to avoid this problem, but currently, there'sno guarantee that this will never happen.

NOTE: Remember that in awk, the ‘ ^’ and ‘ $’ anchormetacharacters match the beginning and end of a string, and notthe beginning and end of a line. As a result, something like‘ RS = "^[[:upper:]]"’ can only match at the beginning of a file. This is because gawk views the input file as one long stringthat happens to contain newline characters in it. It is thus best to avoid anchor characters in the value of RS.

The use ofRS as a regular expression and the RTvariable are gawk extensions; they are not available incompatibility mode(seeOptions). In compatibility mode, only the first character of the value ofRS is used to determine the end of the record.

Advanced Notes: RS = "\0" Is Not Portable

There are times when you might want to treat an entire data file as asingle record. The only way to make this happen is to give RSa value that you know doesn't occur in the input file. This is hardto do in a general way, such that a program always works for arbitraryinput files.

You might think that for text files, the nul character, whichconsists of a character with all bits equal to zero, is a goodvalue to use forRS in this case:

     BEGIN { RS = "\0" }  # whole file becomes one record?

gawk in fact accepts this, and uses thenulcharacter for the record separator. However, this usage isnot portableto other awk implementations.

All other awk implementations19 store strings internally as C-style strings. C strings use thenul character as the string terminator. In effect, this means that‘RS = "\0"’ is the same as ‘RS = ""’. (d.c.)

The best way to treat a whole file as a single record is tosimply read the file in, one record at a time, concatenating eachrecord onto the end of the previous ones.


Next:  ,Previous:  Records,Up:  Reading Files

4.2 Examining Fields

Whenawk reads an input record, the record isautomaticallyparsed or separated by the awk utility into chunkscalledfields. By default, fields are separated by whitespace,like words in a line. Whitespace inawk means any string of one or more spaces,TABs, or newlines;20 other characters, such asformfeed, vertical tab, etc., that areconsidered whitespace by other languages, are not consideredwhitespace by awk.

The purpose of fields is to make it more convenient for you to refer tothese pieces of the record. You don't have to use them—you canoperate on the whole record if you want—but fields are what makesimpleawk programs so powerful.

A dollar-sign (‘$’) is usedto refer to a field in anawk program,followed by the number of the field you want. Thus,$1refers to the first field, $2 to the second, and so on. (Unlike the Unix shells, the field numbers are not limited to single digits.$127 is the one hundred twenty-seventh field in the record.) 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 seventhfield.

NF is a built-in variable whose value is the number of fieldsin the current record.awk automatically updates the valueof NF each time it reads a record. No matter how many fieldsthere are, the last field in a record can be represented by$NF. So, $NF is the same as $7, which is ‘example.’. If you try to reference a field beyond the lastone (such as$8 when the record has only seven fields), you getthe empty string. (If used in a numeric operation, you get zero.)

The use of $0, which looks like a reference to the “zero-th” field, isa special case: it represents the whole input recordwhen you are not interested in specific fields. Here are some more examples:

     $ awk '$1 ~ /foo/ { print $0 }' BBS-list
     -| 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

This example prints each record in the file BBS-list whose firstfield contains the string ‘foo’. The operator ‘~’ is called amatching operator(see Regexp Usage);it tests whether a string (here, the field$1) matches a given regularexpression.

By contrast, the following examplelooks for ‘foo’ inthe entire record and prints the firstfield and the last field for each matching input record:

     $ awk '/foo/ { print $1, $NF }' BBS-list
     -| fooey B
     -| foot B
     -| macfoo A
     -| sabafoo C


Next:  ,Previous:  Fields,Up:  Reading Files

4.3 Nonconstant Field Numbers

The number of a field does not need to be a constant. Any expression intheawk language can be used after a ‘$’ to refer to afield. The value of the expression specifies the field number. If thevalue is a string, rather than a number, it is converted to a number. Consider this example:

     awk '{ print $NR }'

Recall that NR is the number of records read so far: one in thefirst record, two in the second, etc. So this example prints the firstfield of the first record, the second field of the second record, and soon. 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:

     awk '{ print $(2*2) }' BBS-list

awk evaluates the expression ‘(2*2)’ and usesits value as the number of the field to print. The ‘*’ signrepresents multiplication, so the expression ‘2*2’ evaluates to four. The parentheses are used so that the multiplication is done before the‘$’ operation; they are necessary whenever there is a binaryoperator in the field-number expression. This example, then, prints thehours of operation (the fourth field) for every line of the fileBBS-list. (All of theawk operators are listed, inorder of decreasing precedence, inPrecedence.)

If the field number you compute is zero, you get the entire record. Thus, ‘$(2-2)’ has the same value as$0. Negative fieldnumbers are not allowed; trying to reference one usually terminatesthe program. (The POSIX standard does not definewhat happens when you reference a negative field number.gawknotices this and terminates your program. Otherawkimplementations may behave differently.)

As mentioned in Fields,awk stores the current record's number of fields in the built-invariableNF (also see Built-in Variables). The expression$NF is not a special feature—it is the direct consequence ofevaluatingNF and using its value as a field number.

4.4 Changing the Contents of a Field

The contents of a field, as seen byawk, can be changed within anawk program; this changes whatawk perceives as thecurrent input record. (The actual input is untouched;awk nevermodifies the input file.) Consider the following example and its output:

     $ awk '{ nboxes = $3 ; $3 = $3 - 10
     >        print nboxes, $3 }' inventory-shipped
     -| 25 15
     -| 32 22
     -| 24 14
     ...

The program first saves the original value of field three in the variablenboxes. The ‘-’ sign represents subtraction, so this program reassignsfield three,$3, as the original value of field three minus ten:‘$3 - 10’. (SeeArithmetic Ops.) Then it prints the original and new values for field three. (Someone in the warehouse made a consistent mistake while inventoryingthe red boxes.)

For this to work, the text in field $3 must make senseas a number; the string of characters must be converted to a numberfor the computer to do arithmetic on it. The number resultingfrom the subtraction is converted back to a string of characters thatthen becomes field three. See Conversion.

When the value of a field is changed (as perceived by awk), thetext of the input record is recalculated to contain the new field wherethe old one was. In other words,$0 changes to reflect the alteredfield. Thus, this programprints a copy of the input file, with 10 subtracted from the secondfield of each line:

     $ awk '{ $2 = $2 - 10; print $0 }' inventory-shipped
     -| Jan 3 25 15 115
     -| Feb 5 32 24 226
     -| Mar 5 24 34 228
     ...

It is also possible to also assign contents to fields that are outof range. For example:

     $ awk '{ $6 = ($5 + $4 + $3 + $2)
     >        print $6 }' inventory-shipped
     -| 168
     -| 297
     -| 301
     ...

We've just created$6, whose value is the sum of fields$2, $3,$4, and $5. The ‘+’ signrepresents addition. For the fileinventory-shipped, $6represents the total number of parcels shipped for a particular month.

Creating a new field changes awk's internal copy of the currentinput record, which is the value of$0. Thus, if you do ‘print $0’after adding a field, the record printed includes the new field, withthe appropriate number of field separators between it and the previouslyexisting fields.

This recomputation affects and is affected byNF (the number of fields; see Fields). For example, the value ofNF is set to the number of the highestfield you create. The exact format of$0 is also affected by a feature that has not been discussed yet:theoutput field separator, OFS,used to separate the fields (seeOutput Separators).

Note, however, that merely referencing an out-of-range fielddoes not change the value of either $0 or NF. Referencing an out-of-range field only produces an empty string. Forexample:

     if ($(NF+1) != "")
         print "can't happen"
     else
         print "everything is normal"

should print ‘everything is normal’, becauseNF+1 is certainto be out of range. (See If Statement,for more information aboutawk's if-else statements. SeeTyping and Comparison,for more information about the ‘!=’ operator.)

It is important to note that making an assignment to an existing fieldchanges thevalue of$0 but does not change the value of NF,even when you assign the empty string to a field. For example:

     $ echo a b c d | awk '{ OFS = ":"; $2 = ""
     >                       print $0; print NF }'
     -| a::c:d
     -| 4

The field is still there; it just has an empty value, denoted bythe two colons between ‘a’ and ‘c’. This example shows what happens if you create a new field:

     $ echo a b c d | awk '{ OFS = ":"; $2 = ""; $6 = "new"
     >                       print $0; print NF }'
     -| a::c:d::new
     -| 6

The intervening field, $5, is created with an empty value(indicated by the second pair of adjacent colons),andNF is updated with the value six.

DecrementingNF throws away the values of the fieldsafter the new value of NF and recomputes $0. (d.c.) Here is an example:

     $ echo a b c d e f | awk '{ print "NF =", NF;
     >                            NF = 3; print $0 }'
     -| NF = 6
     -| a b c

CAUTION: Some versions of awk don'trebuild $0 when NF is decremented. Caveat emptor.

Finally, there are times when it is convenient to forceawk to rebuild the entire record, using the currentvalue of the fields andOFS. To do this, use theseemingly innocuous assignment:

     $1 = $1   # force record to be reconstituted
     print $0  # or whatever else with $0

This forces awk rebuild the record. It does helpto add a comment, as we've shown here.

There is a flip side to the relationship between $0 andthe fields. Any assignment to$0 causes the record to bereparsed into fields using the current value ofFS. This also applies to any built-in function that updates $0,such assub() and gsub()(see String Functions).

Advanced Notes: Understanding $0

It is important to remember that $0 is the fullrecord, exactly as it was read from the input. This includesany leading or trailing whitespace, and the exact whitespace (or othercharacters) that separate the fields.

It is a not-uncommon error to try to change the field separatorsin a record simply by settingFS and OFS, and thenexpecting a plain ‘print’ or ‘print $0’ to print themodified record.

But this does not work, since nothing was done to change the recorditself. Instead, you must force the record to be rebuilt, typicallywith a statement such as ‘$1 = $1’, as described earlier.


Next:  ,Previous:  Changing Fields,Up:  Reading Files

4.5 Specifying How Fields Are Separated

Thefield separator, which is either a single character or a regularexpression, controls the wayawk splits an input record into fields.awk scans the input record for character sequences thatmatch the separator; the fields themselves are the text between the matches.

In the examples that follow, we use the bullet symbol (•) torepresent spaces in the output. If the field separator is ‘oo’, then the following line:

     moo goo gai pan

is split into three fields: ‘m’, ‘•g’, and‘•gai•pan’. Note the leading spaces in the values of the second and third fields.

The field separator is represented by the built-in variableFS. Shell programmers take note: awk doesnot use thename IFS that is used by the POSIX-compliant shells (such asthe Unix Bourne shell,sh, or Bash).

The value ofFS can be changed in the awk program with theassignment operator, ‘=’ (seeAssignment Ops). Often the right time to do this is at the beginning of executionbefore any input has been processed, so that the very first recordis read with the proper separator. To do this, use the specialBEGIN pattern(see BEGIN/END). For example, here we set the value ofFS to the string",":

     awk 'BEGIN { FS = "," } ; { print $2 }'

Given the input line:

     John Q. Smith, 29 Oak St., Walamazoo, MI 42139

this awk program extracts and prints the string‘•29•Oak•St.’.

Sometimes the input data contains separator characters that don'tseparate fields the way you thought they would. For instance, theperson's name in the example we just used might have a title orsuffix attached, such as:

     John Q. Smith, LXIX, 29 Oak St., Walamazoo, MI 42139

The same program would extract ‘•LXIX’, instead of‘•29•Oak•St.’. If you were expecting the program to print theaddress, you would be surprised. The moral is to choose your data layout andseparator characters carefully to prevent such problems. (If the data is not in a form that is easy to process, perhaps youcan massage it first with a separateawk program.)

4.5.1 Whitespace Normally Separates Fields

Fields are normally separated by whitespace sequences(spaces, TABs, and newlines), not by single spaces. Two spaces in a row do notdelimit an empty field. The default value of the field separator FSis a string containing a single space," ". If awkinterpreted this value in the usual way, each space character would separatefields, 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 ofFS is a special case—it is taken to specify the default mannerof delimiting fields.

If FS is any other single character, such as ",", theneach occurrence of that character separates two fields. Two consecutiveoccurrences delimit an empty field. If the character occurs at thebeginning or the end of the line, that too delimits an empty field. Thespace character is the only single character that does not follow theserules.

4.5.2 Using Regular Expressions to Separate Fields

The previous subsectiondiscussed the use of single characters or simple strings as thevalue ofFS. More generally, the value of FS may be a string containing anyregular expression. In this case, each match in the record for the regularexpression separates fields. For example, the assignment:

     FS = ", \t"

makes every area of an input line that consists of a comma followed by aspace and a TAB into a field separator.

For a less trivial example of a regular expression, try usingsingle spaces to separate fields the way single commas are used.FS can be set to "[ ]" (left bracket, space, rightbracket). This regular expression matches a single space and nothing else(seeRegexp).

There is an important difference between the two cases of ‘FS = " "’(a single space) and ‘FS = "[ \t\n]+"’(a regular expression matching one or more spaces, TABs, or newlines). For both values of FS, fields are separated by runs(multiple adjacent occurrences) of spaces, TABs,and/or newlines. However, when the value ofFS is " ",awk first strips leading and trailing whitespace fromthe record and then decides where the fields are. For example, the following pipeline prints ‘b’:

     $ echo ' a b c d ' | awk '{ print $2 }'
     -| b

However, this pipeline prints ‘a’ (note the extra spaces aroundeach letter):

     $ echo ' a  b  c  d ' | awk 'BEGIN { FS = "[ \t\n]+" }
     >                                  { print $2 }'
     -| a

In this case, the first field isnull or empty.

The stripping of leading and trailing whitespace also comes intoplay whenever $0 is recomputed. For instance, study this pipeline:

     $ echo '   a b c d' | awk '{ print; $2 = $2; print }'
     -|    a b c d
     -| a b c d

The first print statement prints the record as it was read,with leading whitespace intact. The assignment to$2 rebuilds$0 by concatenating $1 through $NF together,separated by the value of OFS. Because the leading whitespacewas ignored when finding$1, it is not part of the new $0. Finally, the last print statement prints the new $0.

There is an additional subtlety to be aware of when using regular expressionsfor field splitting. It is not well-specified in the POSIX standard, or anywhere else, what ‘^’means when splitting fields. Does the ‘^’ match only at the beginning ofthe entire record? Or is each field separator a new string? It turns out thatdifferentawk versions answer this question differently, and youshould not rely on any specific behavior in your programs. (d.c.)

As a point of information, Brian Kernighan's awk allows ‘^’to match only at the beginning of the record.gawkalso works this way. For example:

     $ echo 'xxAA  xxBxx  C' |
     > gawk -F '(^x+)|( +)' '{ for (i = 1; i <= NF; i++)
     >                                   printf "-->%s<--\n", $i }'
     -| --><--
     -| -->AA<--
     -| -->xxBxx<--
     -| -->C<--
4.5.3 Making Each Character a Separate Field

There are times when you may want to examine each characterof a record separately. This can be done ingawk bysimply assigning the null string ("") toFS. (c.e.) In this case,each individual character in the record becomes a separate field. For example:

     $ echo a b | gawk 'BEGIN { FS = "" }
     >                  {
     >                      for (i = 1; i <= NF; i = i + 1)
     >                          print "Field", i, "is", $i
     >                  }'
     -| Field 1 is a
     -| Field 2 is
     -| Field 3 is b

Traditionally, the behavior ofFS equal to "" was not defined. In this case, most versions of Unixawk simply treat the entire recordas only having one field. (d.c.) In compatibility mode(seeOptions),if FS is the null string, then gawk alsobehaves this way.

4.5.4 Setting FS from the Command Line

FS can be set on the command line. Use the -F option todo so. For example:

     awk -F, 'program' input-files

sets FS to the ‘,’ character. Notice that the option usesan uppercase ‘F’ instead of a lowercase ‘f’. The latteroption (-f) specifies a filecontaining an awk program. Case is significant in command-lineoptions:the-F and -f options have nothing to do with each other. You can use both options at the same time to set theFS variableand get an awk program from a file.

The value used for the argument to -F is processed in exactly thesame way as assignments to the built-in variableFS. Any special characters in the field separator must be escapedappropriately. For example, to use a ‘\’ as the field separatoron the command line, you would have to type:

     # same as FS = "\\"
     awk -F\\\\ '...' files ...

Because ‘\’ is used for quoting in the shell, awk sees‘-F\\’. Thenawk processes the ‘\\’ for escapecharacters (seeEscape Sequences), finally yieldinga single ‘\’ to use for the field separator.

As a special case, in compatibility mode(see Options),if the argument to-F is ‘t’, thenFS is set tothe TAB character. If you type ‘-F\t’ at theshell, without any quotes, the ‘\’ gets deleted, soawkfigures that you really want your fields to be separated with TABs andnot ‘t’s. Use ‘-v FS="t"’ or ‘-F"[t]"’ on the command lineif you really do want to separate your fields with ‘t’s.

As an example, let's use an awk program file calledbaud.awkthat contains the pattern /300/ and the action ‘print $1’:

     /300/   { print $1 }

Let's also set FS to be the ‘-’ character and run theprogram on the fileBBS-list. The following command prints alist of the names of the bulletin boards that operate at 300 baud andthe first three digits of their phone numbers:

     $ awk -F- -f baud.awk BBS-list
     -| 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. The second linein the original file looked like this:

     alpo-net     555-3412     2400/1200/300     A

The ‘-’ as part of the system's name was used as the fieldseparator, instead of the ‘-’ in the phone number that wasoriginally intended. This demonstrates why you have to be careful inchoosing your field and record separators.

Perhaps the most common use of a single character as the fieldseparator occurs when processing the Unix system password file. On many Unix systems, each user has a separate entry in the system passwordfile, one line per user. The information in these lines is separatedby colons. The first field is the user's login name and the second isthe user's (encrypted or shadow) password. A password file entry might looklike this:

     arnold:xyzzy:2076:10:Arnold Robbins:/home/arnold:/bin/bash

The following program searches the system password file and printsthe entries for users who have no password:

     awk -F: '$2 == ""' /etc/passwd
4.5.5 Field-Splitting Summary

It is important to remember that when you assign a string constantas the value ofFS, it undergoes normal awk stringprocessing. For example, with Unixawk and gawk,the assignment ‘FS = "\.."’ assigns the character string".."to FS (the backslash is stripped). This creates a regexp meaning“fields are separated by occurrences of any two characters.”If instead you want fields to be separated by a literal period followedby any single character, use ‘FS = "\\.."’.

The following table summarizes how fields are split, based on the valueof FS (‘==’ means “is equal to”):

FS == " "
Fields are separated by runs of whitespace. Leading and trailingwhitespace are ignored. This is the default.
FS == any other single character
Fields are separated by each occurrence of the character. Multiplesuccessive occurrences delimit empty fields, as do leading andtrailing occurrences. The character can even be a regexp metacharacter; it does not needto be escaped.
FS == regexp
Fields are separated by occurrences of characters that match regexp. Leading and trailing matches of regexp delimit empty fields.
FS == ""
Each individual character in the record becomes a separate field. (This is a gawk extension; it is not specified by thePOSIX standard.)
Advanced Notes: Changing FS Does Not Affect the Fields

According to the POSIX standard,awk is supposed to behaveas if each record is split into fields at the time it is read. In particular, this means that if you change the value ofFSafter a record is read, the value of the fields (i.e., how they were split)should reflect the old value ofFS, not the new one.

However, many older implementations ofawk do not work this way. Instead,they defer splitting the fields until a field is actuallyreferenced. The fields are splitusing thecurrent value of FS! (d.c.) This behavior can be difficultto diagnose. The following example illustrates the differencebetween the two methods. (Thesed21command prints just the first line of/etc/passwd.)

     sed 1q /etc/passwd | awk '{ FS = ":" ; print $1 }'

which usually prints:

     root

on an incorrect implementation of awk, whilegawkprints something like:

     root:nSijPlPhZZwgE:0:0:Root:/:
Advanced Notes: FS and IGNORECASE

The IGNORECASE variable(see User-modified)affects field splittingonly when the value of FS is a regexp. It has no effect whenFS is a single character, even ifthat character is a letter. Thus, in the following code:

     FS = "c"
     IGNORECASE = 1
     $0 = "aCa"
     print $1

The output is ‘aCa’. If you really want to split fields on analphabetic character while ignoring case, use a regexp that willdo it for you. E.g., ‘FS = "[c]"’. In this case, IGNORECASEwill take effect.

4.6 Reading Fixed-Width Data

NOTE: This section discusses an advancedfeature of gawk. If you are a novice awk user,you might want to skip it on the first reading.

gawk provides a facility for dealing withfixed-width fields with no distinctive field separator. For example,data of this nature arises in the input for old Fortran programs wherenumbers are run together, or in the output of programs that did notanticipate the use of their output as input for other programs.

An example of the latter is a table where all the columns are lined up bythe use of a variable number of spaces andempty fields are justspaces. Clearly, awk's normal field splitting based onFSdoes not work well in this case. Although a portable awk programcan use a series ofsubstr() calls on $0(see String Functions),this is awkward and inefficient for a large number of fields.

The splitting of an input record into fixed-width fields is specified byassigning a string containing space-separated numbers to the built-invariableFIELDWIDTHS. Each number specifies the width of the field,including columns between fields. If you want to ignore the columnsbetween fields, you can specify the width as a separate field that issubsequently ignored. It is a fatal error to supply a field width that is not a positive number. The following data is the output of the Unixw utility. It is usefulto illustrate the use ofFIELDWIDTHS:

      10:06pm  up 21 days, 14:04,  23 users
     User     tty       login  idle   JCPU   PCPU  what
     hzuo     ttyV0     8:58pm            9      5  vi p24.tex
     hzang    ttyV3     6:37pm    50                -csh
     eklye    ttyV5     9:53pm            7      1  em thes.tex
     dportein ttyV6     8:17pm  1:47                -csh
     gierd    ttyD3    10:00pm     1                elm
     dave     ttyD4     9:47pm            4      4  w
     brent    ttyp0    26Jun91  4:46  26:46   4:41  bash
     dave     ttyq4    26Jun9115days     46     46  wnewmail

The following program takes the above input, converts the idle time tonumber of seconds, and prints out the first two fields and the calculatedidle time:

NOTE: This program uses a number of awk features thathaven't been introduced yet.
     BEGIN  { FIELDWIDTHS = "9 6 10 6 7 7 35" }
     NR > 2 {
         idle = $4
         sub(/^  */, "", idle)   # strip leading spaces
         if (idle == "")
             idle = 0
         if (idle ~ /:/) {
             split(idle, t, ":")
             idle = t[1] * 60 + t[2]
         }
         if (idle ~ /days/)
             idle *= 24 * 60 * 60
     
         print $1, $2, idle
     }

Running the program on the data produces the following results:

     hzuo      ttyV0  0
     hzang     ttyV3  50
     eklye     ttyV5  0
     dportein  ttyV6  107
     gierd     ttyD3  1
     dave      ttyD4  0
     brent     ttyp0  286
     dave      ttyq4  1296000

Another (possibly more practical) example of fixed-width input datais the input from a deck of balloting cards. In some parts ofthe United States, voters mark their choices by punching holes in computercards. These cards are then processed to count the votes for any particularcandidate or on any particular issue. Because a voter may choose not tovote on some issue, any column on the card may be empty. Anawkprogram for processing such data could use theFIELDWIDTHS featureto simplify reading the data. (Of course, gettinggawk to run ona system with card readers is another story!)

Assigning a value toFS causes gawk to useFS for field splitting again. Use ‘FS = FS’ to make this happen,without having to know the current value ofFS. In order to tell which kind of field splitting is in effect,use PROCINFO["FS"](see Auto-set). The value is "FS" if regular field splitting is being used,or it is "FIELDWIDTHS" if fixed-width field splitting is being used:

     if (PROCINFO["FS"] == "FS")
         regular field splitting ...
     else if  (PROCINFO["FS"] == "FIELDWIDTHS")
         fixed-width field splitting ...
     else
         content-based field splitting ... (see next section)

This information is useful when writing a functionthat needs to temporarily changeFS or FIELDWIDTHS,read some records, and then restore the original settings(seePasswd Functions,for an example of such a function).


Next:  ,Previous:  Constant Size,Up:  Reading Files

4.7 Defining Fields By Content

NOTE: This section discusses an advancedfeature of gawk. If you are a novice awk user,you might want to skip it on the first reading.

Normally, when usingFS, gawk defines the fields as theparts of the record that occur in between each field separator. In otherwords,FS defines what a field is not, instead of what a fieldis. However, there are times when you really want to define the fields bywhat they are, and not by what they are not.

The most notorious such caseis so-called comma separated value (CSV) data. Many spreadsheet programs,for example, can export their data into text files, where each record isterminated with a newline, and fields are separated by commas. If onlycommas separated the data, there wouldn't be an issue. The problem comes whenone of the fields contains anembedded comma. While there is noformal standard specification for CSV data22,in such cases, most programs embed the field in double quotes. So we mighthave data like this:

     
     Robbins,Arnold,"1234 A Pretty Street, NE",MyTown,MyState,12345-6789,USA
     

TheFPAT variable offers a solution for cases like this. The value of FPAT should be a string that provides a regular expression. This regular expression describes the contents of each field.

In the case of CSV data as presented above, each field is either “anything thatis not a comma,” or “a double quote, anything that is not a double quote, and aclosing double quote.” If written as a regular expression constant(seeRegexp),we would have /([^,]+)|("[^"]+")/. Writing this as a string requires us to escape the double quotes, leading to:

     FPAT = "([^,]+)|(\"[^\"]+\")"

Putting this to use, here is a simple program to parse the data:

     
     BEGIN {
         FPAT = "([^,]+)|(\"[^\"]+\")"
     }
     
     {
         print "NF = ", NF
         for (i = 1; i <= NF; i++) {
             printf("$%d = <%s>\n", i, $i)
         }
     }
     

When run, we get the following:

     $ gawk -f simple-csv.awk addresses.csv
     NF =  7
     $1 = <Robbins>
     $2 = <Arnold>
     $3 = <"1234 A Pretty Street, NE">
     $4 = <MyTown>
     $5 = <MyState>
     $6 = <12345-6789>
     $7 = <USA>

Note the embedded comma in the value of $3.

A straightforward improvement when processing CSV data of this sortwould be to remove the quotes when they occur, with something like this:

     if (substr($i, 1, 1) == "\"") {
         len = length($i)
         $i = substr($i, 2, len - 2)    # Get text within the two quotes
     }

As with FS, the IGNORECASE variable (see User-modified)affects field splitting with FPAT.

Similar to FIELDWIDTHS, the value of PROCINFO["FS"]will be"FPAT" if content-based field splitting is being used.

NOTE: Some programs export CSV data that contains embedded newlines betweenthe double quotes. gawk provides no way to deal with this. Since there is no formal specification for CSV data, there isn't muchmore to be done;the FPAT mechanism provides an elegant solution for the majorityof cases, and the gawk maintainer is satisfied with that.

As written, the regexp used for FPAT requires that each fieldhave a least one character. A straightforward modification(changing changed the first ‘+’ to ‘*’) allows fields to be empty:

     FPAT = "([^,]*)|(\"[^\"]+\")"

Finally, the patsplit() function makes the same functionalityavailable for splitting regular strings (seeString Functions).


Next:  ,Previous:  Splitting By Content,Up:  Reading Files

4.8 Multiple-Line Records

In some databases, a single line cannot conveniently hold all theinformation in one entry. In such cases, you can use multilinerecords. The first step in doing this is to choose your data format.

One technique is to use an unusual character or string to separaterecords. For example, you could use the formfeed character (written‘\f’ inawk, as in C) to separate them, making each recorda page of the file. To do this, just set the variableRS to"\f" (a string containing the formfeed character). Anyother character could equally well be used, as long as it won't be partof the data in a record.

Another technique is to have blank lines separate records. By a specialdispensation, an empty string as the value ofRS indicates thatrecords are separated by one or more blank lines. WhenRS is setto the empty string, each record always ends at the first blank lineencountered. The next record doesn't start until the first nonblankline that follows. No matter how many blank lines appear in a row, theyall act as one record separator. (Blank lines must be completely empty; lines that contain onlywhitespace do not count.)

You can achieve the same effect as ‘RS = ""’ by assigning thestring"\n\n+" to RS. This regexp matches the newlineat the end of the record and one or more blank lines after the record. In addition, a regular expression always matches the longest possiblesequence when there is a choice(seeLeftmost Longest). So the next record doesn't start untilthe first nonblank line that follows—no matter how many blank linesappear in a row, they are considered one record separator.

There is an important difference between ‘RS = ""’ and‘RS = "\n\n+"’. In the first case, leading newlines in the inputdata file are ignored, and if a file ends without extra blank linesafter the last record, the final newline is removed from the record. In the second case, this special processing is not done. (d.c.)

Now that the input is separated into records, the second step is toseparate the fields in the record. One way to do this is to divide eachof the lines into fields in the normal manner. This happens by defaultas the result of a special feature. When RS is set to the emptystring,and FS is set to a single character,the newline character always acts as a field separator. This is in addition to whatever field separations result fromFS.23

The original motivation for this special exception was probably to provideuseful behavior in the default case (i.e.,FS is equalto " "). This feature can be a problem if you really don'twant the newline character to separate fields, because there is no way toprevent it. However, you can work around this by using thesplit()function to break up the record manually(see String Functions). If you have a single character field separator, you can work aroundthe special feature in a different way, by makingFS into aregexp for that single character. For example, if the fieldseparator is a percent character, instead of‘FS = "%"’, use ‘FS = "[%]"’.

Another way to separate fields is toput each field on a separate line: to do this, just set thevariableFS to the string "\n". (This singlecharacter separator matches a single newline.) A practical example of a data file organized this way might be a mailinglist, where each entry is separated by blank lines. Consider a mailinglist in a file named addresses, which looks like this:

     Jane Doe
     123 Main Street
     Anywhere, SE 12345-6789
     
     John Smith
     456 Tree-lined Avenue
     Smallville, MW 98765-4321
     ...

A simple program to process this file is as follows:

     # addrs.awk --- simple mailing list program
     
     # Records are separated by blank lines.
     # Each line is one field.
     BEGIN { RS = "" ; FS = "\n" }
     
     {
           print "Name is:", $1
           print "Address is:", $2
           print "City and State are:", $3
           print ""
     }

Running the program produces the following output:

     $ awk -f addrs.awk addresses
     -| Name is: Jane Doe
     -| Address is: 123 Main Street
     -| City and State are: Anywhere, SE 12345-6789
     -|
     -| Name is: John Smith
     -| Address is: 456 Tree-lined Avenue
     -| City and State are: Smallville, MW 98765-4321
     -|
     ...

See Labels Program, for a more realisticprogram that deals with address lists. The followingtablesummarizes how records are split, based on thevalue ofRS:

RS == "\n"
Records are separated by the newline character (‘ \n’). In effect,every line in the data file is a separate record, including blank lines. This is the default.
RS == any single character
Records are separated by each occurrence of the character. Multiplesuccessive occurrences delimit empty records.
RS == ""
Records are separated by runs of blank lines. When FS is a single character, thenthe newline characteralways serves as a field separator, in addition to whatever value FS may have. Leading and trailing newlines in a file are ignored.
RS == regexp
Records are separated by occurrences of characters that match regexp. Leading and trailing matches of regexp delimit empty records. (This is a gawk extension; it is not specified by thePOSIX standard.)

In all cases,gawk sets RT to the input text that matched thevalue specified byRS. But if the input file ended without any text that matches RS,then gawk sets RT to the null string.

4.9 Explicit Input with getline

So far we have been getting our input data fromawk's maininput stream—either the standard input (usually your terminal, sometimesthe output from another program) or from thefiles specified on the command line. Theawk language has aspecial built-in command calledgetline thatcan be used to read input under your explicit control.

The getline command is used in several different ways and shouldnot be used by beginners. The examples that follow the explanation of thegetline commandinclude material that has not been covered yet. Therefore, come backand study thegetline command after you have reviewed therest of this Web page and have a good knowledge of howawk works.

Thegetline command returns one if it finds a record and zero ifit encounters the end of the file. If there is some error in gettinga record, such as a file that cannot be opened, thengetlinereturns −1. In this case, gawk sets the variableERRNO to a string describing the error that occurred.

In the following examples, command stands for a string value thatrepresents a shell command.

NOTE: When --sandbox is specified (see Options),reading lines from files, pipes and coprocesses is disabled.


Next:  ,Up:  Getline

4.9.1 Using getline with No Arguments

The getline command can be used without arguments to read inputfrom the current input file. All it does in this case is read the nextinput record and split it up into fields. This is useful if you'vefinished processing the current record, but want to do some specialprocessing on the next record right now. For example:

     {
          if ((t = index($0, "/*")) != 0) {
               # value of `tmp' will be "" if t is 1
               tmp = substr($0, 1, t - 1)
               u = index(substr($0, t + 2), "*/")
               offset = t + 2
               while (u == 0) {
                    if (getline <= 0) {
                         m = "unexpected EOF or error"
                         m = (m ": " ERRNO)
                         print m > "/dev/stderr"
                         exit
                    }
                    u = index($0, "*/")
                    offset = 0
               }
               # substr() expression will be "" if */
               # occurred at end of line
               $0 = tmp substr($0, offset + u + 2)
          }
          print $0
     }

This awk program deletes C-style comments (‘/* ... */’) from the input. By replacing the ‘print $0’ with otherstatements, you could perform more complicated processing on thedecommented input, such as searching for matches of a regularexpression. (This program has a subtle problem—it does not work if onecomment ends and another begins on the same line.)

This form of the getline command sets NF,NR,FNR, and the value of $0.

NOTE: The new value of $0 is used to testthe patterns of any subsequent rules. The original valueof $0 that triggered the rule that executed getlineis lost. By contrast, the next statement reads a new recordbut immediately begins processing it normally, starting with the firstrule in the program. See Next Statement.


Next:  ,Previous:  Plain Getline,Up:  Getline

4.9.2 Using getline into a Variable

You can use ‘getlinevar’ to read the next record fromawk's input into the variablevar. No other processing isdone. For example, suppose the next line is a comment or a special string,and you want to read it without triggeringany rules. This form ofgetline allows you to read that lineand store it in a variable so that the mainread-a-line-and-check-each-rule loop ofawk never sees it. The following example swaps every two lines of input:

     {
          if ((getline tmp) > 0) {
               print tmp
               print $0
          } else
               print $0
     }

It takes the following list:

     wan
     tew
     free
     phore

and produces these results:

     tew
     wan
     phore
     free

The getline command used in this way sets only the variablesNR andFNR (and of course, var). The record is notsplit into fields, so the values of the fields (including$0) andthe value of NF do not change.


Next:  ,Previous:  Getline/Variable,Up:  Getline

4.9.3 Using getline from a File

Use ‘getline < file’ to read the next record fromfile. Here file is a string-valued expression thatspecifies the file name. ‘<file’ is called a redirectionbecause it directs input to come from a different place. For example, the followingprogram reads its input record from the filesecondary.input when itencounters a first field with a value equal to 10 in the current inputfile:

     {
         if ($1 == 10) {
              getline < "secondary.input"
              print
         } else
              print
     }

Because the main input stream is not used, the values of NR andFNR are not changed. However, the record it reads is split into fields inthe normal manner, so the values of$0 and the other fields arechanged, resulting in a new value of NF.

According to POSIX, ‘getline <expression’ is ambiguous ifexpression contains unparenthesized operators other than‘$’; for example, ‘getline < dir "/" file’ is ambiguousbecause the concatenation operator is not parenthesized. You shouldwrite it as ‘getline < (dir "/" file)’ if you want your programto be portable to allawk implementations.


Next:  ,Previous:  Getline/File,Up:  Getline

4.9.4 Using getline into a Variable from a File

Use ‘getlinevar < file’ to read inputfrom the filefile, and put it in the variablevar. As above, fileis a string-valued expression that specifies the file from which to read.

In this version ofgetline, none of the built-in variables arechanged and the record is not split into fields. The only variablechanged isvar.24For example, the following program copies all the input files to theoutput, except for records that say ‘@include filename’. Such a record is replaced by the contents of the filefilename:

     {
          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 intothe program; it is taken directly from the data, specifically from the second field onthe ‘@include’ line.

The close() function is called to ensure that if two identical‘@include’ lines appear in the input, the entire specified file isincluded twice. SeeClose Files And Pipes.

One deficiency of this program is that it does not process nested‘@include’ statements(i.e., ‘@include’ statements in included files)the way a true macro preprocessor would. SeeIgawk Program, for a programthat does handle nested ‘@include’ statements.

4.9.5 Using getline from a Pipe

The output of a command can also be piped into getline, using‘command | getline’. Inthis case, the stringcommand is run as a shell command and its outputis piped into awk to be used as input. This form ofgetlinereads one record at a time from the pipe. For example, the following program copies its input to its output, except forlines that begin with ‘@execute’, which are replaced by the outputproduced by running the rest of the line as a shell command:

     {
          if ($1 == "@execute") {
               tmp = substr($0, 10)        # Remove "@execute"
               while ((tmp | getline) > 0)
                    print
               close(tmp)
          } else
               print
     }

Theclose() function is called to ensure that if two identical‘@execute’ lines appear in the input, the command is run foreach one. SeeClose Files And Pipes. Given the input:

     foo
     bar
     baz
     @execute who
     bletch

the program might produce:

     foo
     bar
     baz
     arnold     ttyv0   Jul 13 14:22
     miriam     ttyp0   Jul 13 14:23     (murphy:0)
     bill       ttyp1   Jul 13 14:23     (murphy:0)
     bletch

Notice that this program ran the command who and printed the previous result. (If you try this program yourself, you will of course get different results,depending upon who is logged in on your system.)

This variation of getline splits the record into fields, sets thevalue ofNF, and recomputes the value of $0. The values ofNR andFNR are not changed.

According to POSIX, ‘expression | getline’ is ambiguous ifexpression contains unparenthesized operators other than‘$’—for example, ‘"echo " "date" | getline’ is ambiguousbecause the concatenation operator is not parenthesized. You shouldwrite it as ‘("echo " "date") | getline’ if you want your programto be portable to all awk implementations.

NOTE: Unfortunately, gawk has not been consistent in its treatmentof a construct like ‘ "echo " "date" | getline’. Most versions, including the current version, treat it at as‘ ("echo " "date") | getline’. (This how Brian Kernighan's awk behaves.) Some versions changed and treated it as‘ "echo " ("date" | getline)’. (This is how mawk behaves.) In short, always use explicit parentheses, and then you won'thave to worry.


Next:  ,Previous:  Getline/Pipe,Up:  Getline

4.9.6 Using getline into a Variable from a Pipe

When you use ‘command | getlinevar’, theoutput of command is sent through a pipe togetline and into the variablevar. For example, thefollowing program reads the current date and time into the variablecurrent_time, using thedate utility, and thenprints it:

     BEGIN {
          "date" | getline current_time
          close("date")
          print "Report printed on " current_time
     }

In this version of getline, none of the built-in variables arechanged and the record is not split into fields.

4.9.7 Using getline from a Coprocess

Input into getline from a pipe is a one-way operation. The command that is started with ‘command | getline’ onlysends datato your awk program.

On occasion, you might want to send data to another programfor processing and then read the results back.gawk allows you to start a coprocess, with which two-waycommunications are possible. This is done with the ‘|&’operator. Typically, you write data to the coprocess first and thenread results back, as shown in the following:

     print "some query" |& "db_server"
     "db_server" |& getline

which sends a query to db_server and then reads the results.

The values of NR andFNR are not changed,because the main input stream is not used. However, the record is split into fields inthe normal manner, thus changing the values of$0, of the other fields,and of NF.

Coprocesses are an advanced feature. They are discussed here only becausethis is the section ongetline. See Two-way I/O,where coprocesses are discussed in more detail.


Next:  ,Previous:  Getline/Coprocess,Up:  Getline

4.9.8 Using getline into a Variable from a Coprocess

When you use ‘command |& getlinevar’, the output fromthe coprocess command is sent through a two-way pipe togetlineand into the variable var.

In this version of getline, none of the built-in variables arechanged and the record is not split into fields. The only variablechanged isvar.

4.9.9 Points to Remember About getline

Here are some miscellaneous points about getline thatyou should bear in mind:

  • When getline changes the value of $0 and NF,awk doesnot automatically jump to the start of theprogram and start testing the new record against every pattern. However, the new record is tested against any subsequent rules.

  • Many awk implementations limit the number of pipelines that anawkprogram may have open to just one. Ingawk, there is no such limit. You can open as many pipelines (and coprocesses) as the underlying operatingsystem permits.

  • An interesting side effect occurs if you use getline without aredirection inside aBEGIN rule. Because an unredirected getlinereads from the command-line data files, the firstgetline commandcauses awk to set the value ofFILENAME. Normally,FILENAME does not have a value insideBEGIN rules, because youhave not yet started to process the command-line data files. (d.c.) (SeeBEGIN/END,also see Auto-set.)
  • Using FILENAME with getline(‘getline < FILENAME’)is likely to be a source forconfusion.awk opens a separate input stream from thecurrent input file. However, by not using a variable,$0and NR are still updated. If you're doing this, it'sprobably by accident, and you should reconsider what it is you'retrying to accomplish.
  • Getline Summary, presents a table summarizing thegetline variants and which variables they can affect. It is worth noting that those variants which do not use redirectioncan causeFILENAME to be updated if they causeawk to start reading a new input file.


Previous:  Getline Notes,Up:  Getline

4.9.10 Summary of getline Variants

table-getline-variantssummarizes the eight variants ofgetline,listing which built-in variables are set by each one,and whether the variant is standard or agawk extension.

VariantEffectStandard / Extension
getlineSets $0, NF, FNR, andNRStandard
getline varSets var, FNR, and NRStandard
getline < fileSets $0 and NFStandard
getline var < fileSets varStandard
command | getlineSets $0 and NFStandard
command | getline varSets varStandard
command |& getlineSets $0 and NFExtension
command |& getline varSets varExtension

Table 4.1: getline Variants and What They Set


Previous:  Getline,Up:  Reading Files

4.10 Directories On The Command Line

According to the POSIX standard, files named on theawkcommand line must be text files. It is a fatal error if they are not. Most versions ofawk treat a directory on the command line asa fatal error.

By default, gawk produces a warning for a directory on thecommand line, but otherwise ignores it. If either of the--posixor --traditional options is given, thengawk revertsto treating a directory on the command line as a fatal error.


Next:  ,Previous:  Reading Files,Up:  Top

5 Printing Output

One of the most common programming actions is toprint, or output,some or all of the input. Use the print statementfor simple output, and theprintf statementfor fancier formatting. The print statement is not limited whencomputingwhich values to print. However, with two exceptions,you cannot specify how to print them—how manycolumns, whether to use exponential notation or not, and so on. (For the exceptions, seeOutput Separators, andOFMT.) For printing with specifications, you need theprintf statement(see Printf).

Besides basic and formatted printing, this chapteralso covers I/O redirections to files and pipes, introducesthe special file names that gawk processes internally,and discusses theclose() built-in function.


Next:  ,Up:  Printing

5.1 The print Statement

The print statement is used for producing output with simple, standardizedformatting. Specify only the strings or numbers to print, in alist 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 be optionally enclosed in parentheses. Theparentheses are necessary if any of the item expressions uses the ‘>’relational operator; otherwise it could be confused with an output redirection(see Redirection).

The items to print can be constant strings or numbers, fields of thecurrent record (such as$1), variables, or any awkexpression. Numeric values are converted to strings and then printed.

The simple statement ‘print’ with no items is equivalent to‘print $0’: it prints the entire current record. To print a blankline, use ‘print ""’, where"" is the empty string. To print a fixed piece of text, use a string constant, such as"Don't Panic", as one item. If you forget to use thedouble-quote characters, your text is taken as anawkexpression, and you will probably get an error. Keep in mind that aspace is printed between any two items.


Next:  ,Previous:  Print,Up:  Printing

5.2 print Statement Examples

Each print statement makes at least one line of output. However, itisn't limited to only one line. If an item value is a string containing anewline, the newline is output along with the rest of the string. Asingleprint statement can make any number of lines this way.

The following is an example of printing a string that contains embedded newlines(the ‘\n’ is an escape sequence, used to represent the newlinecharacter; seeEscape Sequences):

     $ awk 'BEGIN { print "line one\nline two\nline three" }'
     -| line one
     -| line two
     -| line three

The next example, which is run on theinventory-shipped file,prints the first two fields of each input record, with a space betweenthem:

     $ awk '{ print $1, $2 }' inventory-shipped
     -| Jan 13
     -| Feb 15
     -| Mar 15
     ...

A common mistake in using theprint statement is to omit the commabetween two items. This often has the effect of making the items runtogether in the output, with no space. The reason for this is thatjuxtaposing two string expressions inawk means to concatenatethem. Here is the same program, without the comma:

     $ awk '{ print $1 $2 }' inventory-shipped
     -| Jan13
     -| Feb15
     -| Mar15
     ...

To someone unfamiliar with theinventory-shipped file, neitherexample's output makes much sense. A heading line at the beginningwould make it clearer. Let's add some headings to our table of months($1) and green crates shipped ($2). We do this using theBEGIN pattern(see BEGIN/END)so that the headings are only printed once:

     awk 'BEGIN {  print "Month Crates"
                   print "----- ------" }
                {  print $1, $2 }' inventory-shipped

When run, the program prints the following:

     Month Crates
     ----- ------
     Jan 13
     Feb 15
     Mar 15
     ...

The only problem, however, is that the headings and the table datadon't line up! We can fix this by printing some spaces between thetwo fields:

     awk 'BEGIN { print "Month Crates"
                  print "----- ------" }
                { print $1, "     ", $2 }' inventory-shipped

Lining up columns this way can get prettycomplicated when there are many columns to fix. Counting spaces for twoor three columns is simple, but any more than this can take upa lot of time. This is why theprintf statement wascreated (see Printf);one of its specialties is lining up columns of data.

NOTE: You can continue either a print or printf statement simply by putting a newline after any comma(see Statements/Lines).


Next:  ,Previous:  Print Examples,Up:  Printing

5.3 Output Separators

As mentioned previously, aprint statement contains a listof items separated by commas. In the output, the items are normallyseparated by single spaces. However, this doesn't need to be the case;a single space is simply the default. Any string ofcharacters may be used as the output field separator by setting thebuilt-in variable OFS. The initial value of this variableis the string" "—that is, a single space.

The output from an entire print statement is called anoutput record. Eachprint statement outputs one outputrecord, and then outputs a string called theoutput record separator(or ORS). The initialvalue of ORS is the string "\n"; i.e., a newlinecharacter. Thus, each print statement normally makes a separate line.

In order to change how output fields and records are separated, assignnew values to the variablesOFS and ORS. The usualplace to do this is in the BEGIN rule(see BEGIN/END), sothat it happens before any input is processed. It can also be donewith assignments on the command line, before the names of the inputfiles, or using the-v command-line option(see Options). The following example prints the first and second fields of each inputrecord, separated by a semicolon, with a blank line added after eachnewline:

     $ awk 'BEGIN { OFS = ";"; ORS = "\n\n" }
     >            { print $1, $2 }' BBS-list
     -| aardvark;555-5553
     -|
     -| alpo-net;555-3412
     -|
     -| barfly;555-7685
     ...

If the value of ORS does not contain a newline, the program's outputruns together on a single line.


Next:  ,Previous:  Output Separators,Up:  Printing

5.4 Controlling Numeric Output with print

When printing numeric values with theprint statement,awk internally converts the number to a string of charactersand prints that string.awk uses the sprintf() functionto do this conversion(seeString Functions). For now, it suffices to say that thesprintf()function accepts a format specification that tells it how to formatnumbers (or strings), and that there are a number of different ways in whichnumbers can be formatted. The different format specifications are discussedmore fully inControl Letters.

The built-in variableOFMT contains the default format specificationthat print uses withsprintf() when it wants to convert anumber to a string for printing. The default value ofOFMT is "%.6g". The way print prints numbers can be changedby supplying different format specificationsas the value ofOFMT, as shown in the following example:

     $ awk 'BEGIN {
     >   OFMT = "%.0f"  # print numbers as integers (rounds)
     >   print 17.23, 17.54 }'
     -| 17 18

According to the POSIX standard, awk's behavior is undefinedifOFMT contains anything but a floating-point conversion specification. (d.c.)


Next:  ,Previous:  OFMT,Up:  Printing

5.5 Using printf Statements for Fancier Printing

For more precise control over the output format than what isprovided byprint, use printf. With printf you canspecify the width to use for each item, as well as variousformatting choices for numbers (such as what output base to use, whether toprint an exponent, whether to print a sign, and how many digits to printafter the decimal point). You do this by supplying a string, calledtheformat string, that controls how and where to print the otherarguments.


Next:  ,Up:  Printf

5.5.1 Introduction to the printf Statement

A simpleprintf statement looks like this:

     printf format, item1, item2, ...

The entire list of arguments may optionally be enclosed in parentheses. Theparentheses are necessary if any of the item expressions use the ‘>’relational operator; otherwise, it can be confused with an output redirection(see Redirection).

The difference between printf andprint is the formatargument. This is an expression whose value is taken as a string; itspecifies how to output each of the other arguments. It is called theformat string.

The format string is very similar to that in the ISO C library functionprintf(). Most offormat is text to output verbatim. Scattered among this text are format specifiers—one per item. Each format specifier says to output the next item in the argument listat that place in the format.

The printf statement does not automatically append a newlineto its output. It outputs only what the format string specifies. So if a newline is needed, you must include one in the format string. The output separator variablesOFS and ORS have no effecton printf statements. For example:

     $ awk 'BEGIN {
     >    ORS = "\nOUCH!\n"; OFS = "+"
     >    msg = "Dont Panic!"
     >    printf "%s\n", msg
     > }'
     -| Dont Panic!

Here, neither the ‘+’ nor the ‘OUCH’ appear inthe output message.


Next:  ,Previous:  Basic Printf,Up:  Printf

5.5.2 Format-Control Letters

A format specifier starts with the character ‘%’ and ends witha format-control letter—it tells the printf statementhow to output one item. The format-control letter specifies whatkindof value to print. The rest of the format specifier is made up ofoptionalmodifiers that control how to print the value, such asthe field width. Here is a list of the format-control letters:

%c
Print a number as an ASCII character; thus, ‘ printf "%c",65’ outputs the letter ‘ A’. The output for a string value isthe first character of the string.

NOTE: The POSIX standard says the first character of a string is printed. In locales with multibyte characters, gawk attempts toconvert the leading bytes of the string into a valid wide characterand then to print the multibyte encoding of that character. Similarly, when printing a numeric value, gawk allows thevalue to be within the numeric range of values that can be heldin a wide character.

Other awk versions generally restrict themselves to printingthe first byte of a string or to numeric values within the range ofa single byte (0–255).


%d , %i
Print a decimal integer. The two control letters are equivalent. (The ‘ %i’ specification is for compatibility with ISO C.)
%e , %E
Print a number in scientific (exponential) notation;for example:
          printf "%4.3e\n", 1950

prints ‘1.950e+03’, with a total of four significant figures, three ofwhich follow the decimal point. (The ‘4.3’ represents two modifiers,discussed in the next subsection.) ‘%E’ uses ‘E’ instead of ‘e’ in the output.

%f
Print a number in floating-point notation. For example:
          printf "%4.3f", 1950

prints ‘1950.000’, with a total of four significant figures, three ofwhich follow the decimal point. (The ‘4.3’ represents two modifiers,discussed in the next subsection.)

On systems supporting IEEE 754 floating point format, valuesrepresenting negativeinfinity are formatted as‘-inf’ or ‘-infinity’,and positive infinity as‘inf’ and ‘infinity’. The special “not a number” value formats as ‘-nan’ or ‘nan’.

%F
Like ‘ %f’ but the infinity and “not a number” values are spelledusing uppercase letters.

The ‘%F’ format is a POSIX extension to ISO C; not all systemssupport it. On those that don't,gawk uses ‘%f’ instead.

%g , %G
Print a number in either scientific notation or in floating-pointnotation, whichever uses fewer characters; if the result is printed inscientific notation, ‘ %G’ uses ‘ E’ instead of ‘ e’.
%o
Print an unsigned octal integer(see Nondecimal-numbers).
%s
Print a string.
%u
Print an unsigned decimal integer. (This format is of marginal use, because all numbers in awkare floating-point; it is provided primarily for compatibility with C.)
%x , %X
Print an unsigned hexadecimal integer;‘ %X’ uses the letters ‘ A’ through ‘ F’instead of ‘ a’ through ‘ f’(see Nondecimal-numbers).
%%
Print a single ‘ %’. This does not consume anargument and it ignores any modifiers.

NOTE: When using the integer format-control letters for values that areoutside the range of the widest C integer type, gawk switches tothe ‘ %g’ format specifier. If --lint is provided on thecommand line (see Options), gawkwarns about this. Other versions of awk may print invalidvalues or do something else entirely. (d.c.)


Next:  ,Previous:  Control Letters,Up:  Printf

5.5.3 Modifiers for printf Formats

A format specification can also includemodifiers that can controlhow much of the item's value is printed, as well as how much space it gets. The modifiers come between the ‘%’ and the format-control letter. We will use the bullet symbol “•” in the following examples torepresentspaces in the output. Here are the possible modifiers, in the order inwhich they may appear:

N $
An integer constant followed by a ‘ $’ is a positional specifier. Normally, format specifications are applied to arguments in the ordergiven in the format string. With a positional specifier, the formatspecification is applied to a specific argument, instead of whatwould be the next argument in the list. Positional specifiers begincounting with one. Thus:
          printf "%s %s\n", "don't", "panic"
          printf "%2$s %1$s\n", "panic", "don't"

prints the famous friendly message twice.

At first glance, this feature doesn't seem to be of much use. It is in fact a gawk extension, intended for use in translatingmessages at runtime. SeePrintf Ordering,which describes how and why to use positional specifiers. For now, we will not use them.

-
The minus sign, used before the width modifier (see later on inthis list),says to left-justifythe argument within its specified width. Normally, the argumentis printed right-justified in the specified width. Thus:
          printf "%-4s", "foo"

prints ‘foo•’.

space
For numeric conversions, prefix positive values with a space andnegative values with a minus sign.
+
The plus sign, used before the width modifier (see later on inthis list),says to always supply a sign for numeric conversions, even if the datato format is positive. The ‘ +’ overrides the space modifier.
#
Use an “alternate form” for certain control letters. For ‘ %o’, supply a leading zero. For ‘ %x’ and ‘ %X’, supply a leading ‘ 0x’ or ‘ 0X’ fora nonzero result. For ‘ %e’, ‘ %E’, ‘ %f’, and ‘ %F’, the result alwayscontains a decimal point. For ‘ %g’ and ‘ %G’, trailing zeros are not removed from the result.
0
A leading ‘ 0’ (zero) acts as a flag that indicates that output should bepadded with zeros instead of spaces. This applies only to the numeric output formats. This flag only has an effect when the field width is wider than thevalue to print.
'
A single quote or apostrophe character is a POSIX extension to ISO C. It indicates that the integer part of a floating point value, or theentire part of an integer decimal value, should have a thousands-separatorcharacter in it. This only works in locales that support such characters. For example:
          $ cat thousands.awk          Show source program
          -| BEGIN { printf "%'d\n", 1234567 }
          $ LC_ALL=C gawk -f thousands.awk
          -| 1234567                   Results in "C" locale
          $ LC_ALL=en_US.UTF-8 gawk -f thousands.awk
          -| 1,234,567                 Results in US English UTF locale

For more information about locales and internationalization issues,seeLocales.

NOTE: The ‘ '’ flag is a nice feature, but its use complicates things: itbecomes difficult to use it in command-line programs. For informationon appropriate quoting tricks, see Quoting.

width
This is a number specifying the desired minimum width of a field. Inserting anynumber between the ‘ %’ sign and the format-control character forces thefield to expand to this width. The default way to do this is topad with spaces on the left. For example:
          printf "%4s", "foo"

prints ‘•foo’.

The value of width is a minimum width, not a maximum. If the itemvalue requires more thanwidth characters, it can be as wide asnecessary. Thus, the following:

          printf "%4s", "foobar"

prints ‘foobar’.

Preceding the width with a minus sign causes the output to bepadded with spaces on the right, instead of on the left.

. prec
A period followed by an integer constantspecifies the precision to use when printing. The meaning of the precision varies by control letter:
%d, %i, %o, %u, %x, %X
Minimum number of digits to print.
%e, %E, %f, %F
Number of digits to the right of the decimal point.
%g, %G
Maximum number of significant digits.
%s
Maximum number of characters from the string that should print.

Thus, the following:

          printf "%.4s", "foobar"

prints ‘foob’.

The C library printf's dynamic width and preccapability (for example,"%*.*s") is supported. Instead ofsupplying explicit width and/orprec values in the formatstring, they are passed in the argument list. For example:

     w = 5
     p = 3
     s = "abcdefg"
     printf "%*.*s\n", w, p, s

is exactly equivalent to:

     s = "abcdefg"
     printf "%5.3s\n", s

Both programs output ‘••abc’. Earlier versions ofawk did not support this capability. If you must use such a version, you may simulate this feature by usingconcatenation to build up the format string, like so:

     w = 5
     p = 3
     s = "abcdefg"
     printf "%" w "." p "s\n", s

This is not particularly easy to read but it does work.

C programmers may be used to supplying additional‘l’, ‘L’, and ‘h’modifiers inprintf format strings. These are not valid in awk. Mostawk implementations silently ignore them. If--lint is provided on the command line(seeOptions),gawk warns about their use. If--posix is supplied,their use is a fatal error.


Previous:  Format Modifiers,Up:  Printf

5.5.4 Examples Using printf

The following simple example showshow to use printf to make an aligned table:

     awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list

This commandprints the names of the bulletin boards ($1) in the fileBBS-list as a string of 10 characters that are left-justified. It alsoprints the phone numbers ($2) next on the line. Thisproduces an aligned two-column table of names and phone numbers,as shown here:

     $ awk '{ printf "%-10s %s\n", $1, $2 }' BBS-list
     -| 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

In this case, the phone numbers had to be printed as strings becausethe numbers are separated by a dash. Printing the phone numbers asnumbers would have produced just the first three digits: ‘555’. This would have been pretty confusing.

It wasn't necessary to specify a width for the phone numbers becausethey are last on their lines. They don't need to have spacesafter them.

The table could be made to look even nicer by adding headings to thetops of the columns. This is done using theBEGIN pattern(see BEGIN/END)so that the headers are only printed once, at the beginning oftheawk program:

     awk 'BEGIN { print "Name      Number"
                  print "----      ------" }
          { printf "%-10s %s\n", $1, $2 }' BBS-list

The above example mixes print and printf statements inthe same program. Using justprintf statements can produce thesame results:

     awk 'BEGIN { printf "%-10s %s\n", "Name", "Number"
                  printf "%-10s %s\n", "----", "------" }
          { printf "%-10s %s\n", $1, $2 }' BBS-list

Printing each column heading with the same format specificationused for the column elements ensures that the headingsare aligned just like the columns.

The fact that the same format specification is used three times can beemphasized by storing it in a variable, like this:

     awk 'BEGIN { format = "%-10s %s\n"
                  printf format, "Name", "Number"
                  printf format, "----", "------" }
          { printf format, $1, $2 }' BBS-list

At this point, it would be a worthwhile exercise to use theprintf statement to line up the headings and table data for theinventory-shipped example that was covered earlier in the sectionon theprint statement(see Print).


Next:  ,Previous:  Printf,Up:  Printing

5.6 Redirecting Output of print and printf

So far, the output from print and printf has goneto the standardoutput, usually the screen. Bothprint and printf canalso send their output to other places. This is calledredirection.

NOTE: When --sandbox is specified (see Options),redirecting output to files and pipes is disabled.

A redirection appears after the print or printf statement. Redirections inawk are written just like redirections in shellcommands, except that they are written inside theawk program.

There are four forms of output redirection: output to a file, outputappended to a file, output through a pipe to another command, and outputto a coprocess. They are all shown for theprint statement,but they work identically for printf:

print items > output-file
This redirection prints the items into the output file named output-file. The file name output-file can be anyexpression. Its value is changed to a string and then used as afile name (see Expressions).

When this type of redirection is used, the output-file is erasedbefore the first output is written to it. Subsequent writes to the sameoutput-file do not eraseoutput-file, but append to it. (This is different from how you use redirections in shell scripts.) Ifoutput-file does not exist, it is created. For example, hereis how an awk program can write a list of BBS names to onefile namedname-list, and a list of phone numbers to another filenamedphone-list:

          $ awk '{ print $2 > "phone-list"
          >        print $1 > "name-list" }' BBS-list
          $ cat phone-list
          -| 555-5553
          -| 555-3412
          ...
          $ cat name-list
          -| aardvark
          -| alpo-net
          ...

Each output file contains one name or number per line.


print items >> output-file
This redirection prints the items into the pre-existing output filenamed output-file. The difference between this and thesingle-‘ >’ redirection is that the old contents (if any) of output-file are not erased. Instead, the awk output isappended to the file. If output-file does not exist, then it is created.


print items | command
It is possible to send output to another program through a pipeinstead of into a file. This redirection opens a pipe to command, and writes the values of items through this pipeto another process created to execute command.

The redirection argument command is actually an awkexpression. Its value is converted to a string whose contents givethe shell command to be run. For example, the following produces twofiles, one unsorted list of BBS names, and one list sorted in reversealphabetical order:

          awk '{ print $1 > "names.unsorted"
                 command = "sort -r > names.sorted"
                 print $1 | command }' BBS-list

The unsorted list is written with an ordinary redirection, whilethe sorted list is written by piping through thesort utility.

The next example uses redirection to mail a message to the mailinglist ‘bug-system’. This might be useful when trouble is encounteredin anawk script run periodically for system maintenance:

          report = "mail bug-system"
          print "Awk script failed:", $0 | report
          m = ("at record number " FNR " of " FILENAME)
          print m | report
          close(report)

The message is built using string concatenation and saved in the variablem. It's then sent down the pipeline to themail program. (The parentheses group the items to concatenate—seeConcatenation.)

The close() function is called here because it's a good idea to closethe pipe as soon as all the intended output has been sent to it. SeeClose Files And Pipes,for more information.

This example also illustrates the use of a variable to representa file orcommand—it is not necessary to alwaysuse a string constant. Using a variable is generally a good idea,because (if you mean to refer to that same file or command)awk requires that the string value be spelled identicallyevery time.


print items |& command
This redirection prints the items to the input of command. The difference between this and thesingle-‘ |’ redirection is that the output from commandcan be read with getline. Thus command is a coprocess, which works together with,but subsidiary to, the awk program.

This feature is a gawk extension, and is not available inPOSIXawk. See Getline/Coprocess,for a brief discussion. See Two-way I/O,for a more complete discussion.

Redirecting output using ‘>’, ‘>>’, ‘|’, or ‘|&’asks the system to open a file, pipe, or coprocess only if the particularfile or command you specify has not already been writtento by your program or if it has been closed since it was last written to.

It is a common error to use ‘>’ redirection for the firstprintto a file, and then to use ‘>>’ for subsequent output:

     # clear the file
     print "Don't panic" > "guide.txt"
     ...
     # append
     print "Avoid improbability generators" >> "guide.txt"

This is indeed how redirections must be used from the shell. But inawk, it isn't necessary. In this kind of case, a program shoulduse ‘>’ for all theprint statements, since the output fileis only opened once. (It happens that if you mix ‘>’ and ‘>>’that output is produced in the expected order. However, mixing the operatorsfor the same file is definitely poor style, and is confusing to readersof your program.)

As mentioned earlier(see Getline Notes),manyManyolderawk implementations limit the number of pipelines that anawkprogram may have open to just one! Ingawk, there is no such limit. gawk allows a program toopen as many pipelines as the underlying operating system permits.

Advanced Notes: Piping into sh

A particularly powerful way to use redirection is to build command linesand pipe them into the shell,sh. For example, suppose youhave a list of files brought over from a system where all the file namesare stored in uppercase, and you wish to rename them to have names inall lowercase. The following program is both simple and efficient:

     { printf("mv %s %s\n", $0, tolower($0)) | "sh" }
     
     END { close("sh") }

The tolower() function returns its argument string with alluppercase characters converted to lowercase(seeString Functions). The program builds up a list of command lines,using themv utility to rename the files. It then sends the list to the shell for execution.


Next:  ,Previous:  Redirection,Up:  Printing

5.7 Special File Names in gawk

gawk provides a number of special file names that it interpretsinternally. These file names provide access to standard file descriptorsand TCP/IP networking.

5.7.1 Special Files for Standard Descriptors

Running programs conventionally have three input and output streamsalready available to them for reading and writing. These are known asthestandard input, standard output, and standard erroroutput. These streams are, by default, connected to your keyboard and screen, butthey are often redirected with the shell, via the ‘<’, ‘<<’,‘>’, ‘>>’, ‘>&’, and ‘|’ operators. Standard erroris typically used for writing error messages; the reason there are two separatestreams, standard output and standard error, is so that they can beredirected separately.

In other implementations ofawk, the only way to write an errormessage to standard error in anawk program is as follows:

     print "Serious error detected!" | "cat 1>&2"

This works by opening a pipeline to a shell command that can access thestandard error stream that it inherits from theawk process. This is far from elegant, and it is also inefficient, because it requires aseparate process. So people writingawk programs oftendon't do this. Instead, they send the error messages to thescreen, like this:

     print "Serious error detected!" > "/dev/tty"

(/dev/tty is a special file supplied by the operating systemthat is connected to your keyboard and screen. It represents the“terminal,”25 which on modern systems is a keyboardand screen, not a serial console.) This usually has the same effect but not always: although thestandard error stream is usually the screen, it can be redirected; whenthat happens, writing to the screen is not correct. In fact, ifawk is run from a background job, it may not have aterminal at all. Then opening/dev/tty fails.

gawk provides special file names for accessing the three standardstreams. (c.e.). It also provides syntax for accessingany other inherited open files. If the file name matchesone of these special names whengawk redirects input or output,then it directly uses the stream that the file name stands for. These special file names work for all operating systems thatgawkhas been ported to, not just those that are POSIX-compliant:

/dev/stdin
The standard input (file descriptor 0).
/dev/stdout
The standard output (file descriptor 1).
/dev/stderr
The standard error output (file descriptor 2).
/dev/fd/N
The file associated with file descriptor N. Such a file mustbe opened by the program initiating the awk execution (typicallythe shell). Unless special pains are taken in the shell from which gawk is invoked, only descriptors 0, 1, and 2 are available.

The file names /dev/stdin, /dev/stdout, and/dev/stderrare aliases for /dev/fd/0,/dev/fd/1, and /dev/fd/2,respectively. However, they are more self-explanatory. The proper way to write an error message in agawk programis to use /dev/stderr, like this:

     print "Serious error detected!" > "/dev/stderr"

Note the use of quotes around the file name. Like any other redirection, the value must be a string. It is a common error to omit the quotes, which leadsto confusing results.

Finally, using the close() function on a file name of theform "/dev/fd/N", for file descriptor numbersabove two, will actually close the given file descriptor.

The /dev/stdin, /dev/stdout, and/dev/stderrspecial files are also recognized internally by several otherversions ofawk.


Next:  ,Previous:  Special FD,Up:  Special Files

5.7.2 Special Files for Network Communications

gawk programscan open a two-wayTCP/IP connection, acting as either a client or a server. This is done using a special file name of the form:

     /net-type/protocol/local-port/remote-host/remote-port

The net-type is one of ‘inet’, ‘inet4’ or ‘inet6’. Theprotocol is one of ‘tcp’ or ‘udp’,and the other fields represent the other essential pieces of informationfor making a networking connection. These file names are used with the ‘|&’ operator for communicatingwith a coprocess(seeTwo-way I/O). This is an advanced feature, mentioned here only for completeness. Full discussion is delayed untilTCP/IP Networking.


Previous:  Special Network,Up:  Special Files

5.7.3 Special File Name Caveats

Here is a list of things to bear in mind when using thespecial file names thatgawk provides:

  • Recognition of these special file names is disabled if gawk is incompatibility mode (seeOptions).
  • gawk alwaysinterprets these special file names. For example, using ‘/dev/fd/4’for output actually writes on file descriptor 4, and not on a newfile descriptor that is dup()'ed from file descriptor 4. Most ofthe time this does not matter; however, it is important tonotclose any of the files related to file descriptors 0, 1, and 2. Doing so results in unpredictable behavior.


Previous:  Special Files,Up:  Printing

5.8 Closing Input and Output Redirections

If the same file name or the same shell command is used with getlinemore than once during the execution of anawk program(see Getline),the file is opened (or the command is executed) the first time only. 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 with getline,another record is read from it, and so on.

Similarly, when a file or pipe is opened for output, awk remembersthe file name or command associated with it, and subsequentwrites to the same file or command are appended to the previous writes. The file or pipe stays open until awk exits.

This implies that special steps are necessary in order to read the samefile again from the beginning, or to rerun a shell command (rather thanreading more output from the same command). The close() functionmakes these things possible:

     close(filename)

or:

     close(command)

The argument filename or command can be any expression. Itsvalue mustexactly match the string that was used to open the file orstart the command (spaces and other “irrelevant” charactersincluded). For example, if you open a pipe with this:

     "sort -r names" | getline foo

then you must close it with this:

     close("sort -r names")

Once this function call is executed, the next getline from thatfile or command, or the nextprint or printf to thatfile or command, reopens the file or reruns the command. Because the expression that you use to close a file or pipeline mustexactly match the expression used to open the file or run the command,it is good practice to use a variable to store the file name or command. The previous example becomes the following:

     sortcom = "sort -r names"
     sortcom | getline foo
     ...
     close(sortcom)

This helps avoid hard-to-find typographical errors in your awkprograms. Here are some of the reasons for closing an output file:

  • To write a file and read it back later on in the same awkprogram. Close the file after writing it, thenbegin reading it withgetline.
  • To write numerous files, successively, in the same awkprogram. If the files aren't closed, eventuallyawk may exceed asystem limit on the number of open files in one process. It is best toclose each one when the program has finished writing it.
  • To make a command finish. When output is redirected through a pipe,the command reading the pipe normally continues to try to read inputas long as the pipe is open. Often this means the command cannotreally do its work until the pipe is closed. For example, ifoutput is redirected to the mail program, the message is notactually sent until the pipe is closed.
  • 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 a program pipes output to the mail program. If it outputs several lines redirected to this pipe without closingit, they make a single message of several lines. By contrast, if theprogram closes the pipe after each line of output, then each line makesa separate message.

If you use more files than the system allows you to have open,gawk attempts to multiplex the available open files amongyour data files.gawk's ability to do this depends upon thefacilities of your operating system, so it may not always work. It istherefore both good practice and good portability advice to alwaysuseclose() on your files when you are done with them. In fact, if you are using a lot of pipes, it is essential thatyou close commands when done. For example, consider something like this:

     {
         ...
         command = ("grep " $1 " /some/file | my_prog -q " $3)
         while ((command | getline) > 0) {
             process output of command
         }
         # need close(command) here
     }

This example creates a new pipeline based on data in each record. Without the call toclose() indicated in the comment, awkcreates child processes to run the commands, until it eventuallyruns out of file descriptors for more pipelines.

Even though each command has finished (as indicated by the end-of-filereturn status fromgetline), the child process is notterminated;26more importantly, the file descriptor for the pipeis not closed and released untilclose() is called orawk exits.

close() will silently do nothing if given an argument thatdoes not represent a file, pipe or coprocess that was opened witha redirection.

Note also that ‘close(FILENAME)’ has no“magic” effects on the implicit loop that reads through thefiles named on the command line. It is, more likely, a closeof a file that was never opened, soawk silentlydoes nothing.

When using the ‘|&’ operator to communicate with a coprocess,it is occasionally useful to be able to close one end of the two-waypipe without closing the other. This is done by supplying a second argument toclose(). As in any other call to close(),the first argument is the name of the command or special file usedto start the coprocess. The second argument should be a string, with either of the values"to" or"from". Case does not matter. As this is an advanced feature, a more complete discussion isdelayed untilTwo-way I/O,which discusses it in more detail and gives an example.

Advanced Notes: Using close()'s Return Value

In many versions of Unix awk, the close() functionis actually a statement. It is a syntax error to try and use the returnvalue fromclose():(d.c.)

     command = "..."
     command | getline info
     retval = close(command)  # syntax error in many Unix awks

gawk treatsclose() as a function. The return value is −1 if the argument names somethingthat was never opened with a redirection, or if there isa system problem closing the file or process. In these cases,gawk sets the built-in variableERRNO to a string describing the problem.

In gawk,when closing a pipe or coprocess (input or output),the return value is the exit status of the command.27Otherwise, it is the return value from the system's close() orfclose() C functions when closing input or outputfiles, respectively. This value is zero if the close succeeds, or −1 ifit fails.

The POSIX standard is very vague; it says that close()returns zero on success and nonzero otherwise. In general,different implementations vary in what they report when closingpipes; thus the return value cannot be used portably. (d.c.) In POSIX mode (see Options), gawk just returns zerowhen closing a pipe.


Next:  ,Previous:  Printing,Up:  Top

6 Expressions

Expressions are the basic building blocks ofawk patternsand actions. An expression evaluates to a value that you can print, test,or pass to a function. Additionally, an expressioncan assign a new value to a variable or a field by using an assignment operator.

An expression can serve as a pattern or action statement on its own. Most other kinds ofstatements contain one or more expressions that specify the data on which tooperate. As in other languages, expressions inawk includevariables, array references, constants, and function calls, as well ascombinations of these with various operators.


Next:  ,Up:  Expressions

6.1 Constants, Variables and Conversions

Expressions are built up from values and the operations performedupon them. This section describes the elementary objectswhich provide the values used in expressions.

6.1.1 Constant Expressions

The simplest type of expression is theconstant, which always hasthe same value. There are three types of constants: numeric,string, and regular expression.

Each is used in the appropriate context when you need a datavalue that isn't going to change. Numeric constants canhave different forms, but are stored identically internally.

6.1.1.1 Numeric and String Constants

A numeric constant stands for a number. This number can be aninteger, a decimal fraction, or a number in scientific (exponential)notation.28Here are some examples of numeric constants that allhave the same value:

     105
     1.05e+2
     1050e-1

A string constant consists of a sequence of characters enclosed indouble-quotation marks. For example:

     "parrot"

represents the string whose contents are ‘parrot’. Strings ingawk can be of any length, and they can contain any of the possibleeight-bit ASCII characters including ASCIInul (character code zero). Other awkimplementations may have difficulty with some character codes.


Next:  ,Previous:  Scalar Constants,Up:  Constants

6.1.1.2 Octal and Hexadecimal Numbers

Inawk, all numbers are in decimal; i.e., base 10. Many otherprogramming languages allow you to specify numbers in other bases, oftenoctal (base 8) and hexadecimal (base 16). In octal, the numbers go 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, etc. Just as ‘11’, in decimal, is 1 times 10 plus 1, so‘11’, in octal, is 1 times 8, plus 1. This equals 9 in decimal. In hexadecimal, there are 16 digits. Since the everyday decimalnumber system only has ten digits (‘0’–‘9’), the letters‘a’ through ‘f’ are used to represent the rest. (Case in the letters is usually irrelevant; hexadecimal ‘a’ and ‘A’have the same value.) Thus, ‘11’, inhexadecimal, is 1 times 16 plus 1, which equals 17 in decimal.

Just by looking at plain ‘11’, you can't tell what base it's in. So, in C, C++, and other languages derived from C,there is a special notation to signify the base. Octal numbers start with a leading ‘0’,and hexadecimal numbers start with a leading ‘0x’ or ‘0X’:

11
Decimal value 11.
011
Octal 11, decimal value 9.
0x11
Hexadecimal 11, decimal value 17.

This example shows the difference:

     $ gawk 'BEGIN { printf "%d, %d, %d\n", 011, 11, 0x11 }'
     -| 9, 11, 17

Being able to use octal and hexadecimal constants in your programs is mostuseful when working with data that cannot be represented conveniently ascharacters or as regular numbers, such as binary data of various sorts.

gawk allows the use of octal and hexadecimalconstants in your program text. However, such numbers in the input dataare not treated differently; doing so by default would break oldprograms. (If you really need to do this, use the--non-decimal-datacommand-line option;seeNondecimal Data.) If you have octal or hexadecimal data,you can use thestrtonum() function(see String Functions)to convert the data into a number. Most of the time, you will want to use octal or hexadecimal constantswhen working with the built-in bit manipulation functions;seeBitwise Functions,for more information.

Unlike some early C implementations, ‘8’ and ‘9’ are not validin octal constants; e.g.,gawk treats ‘018’ as decimal 18:

     $ gawk 'BEGIN { print "021 is", 021 ; print 018 }'
     -| 021 is 17
     -| 18

Octal and hexadecimal source code constants are agawk extension. If gawk is in compatibility mode(seeOptions),they are not available.

Advanced Notes: A Constant's Base Does Not Affect Its Value

Once a numeric constant hasbeen converted internally into a number,gawk no longer rememberswhat the original form of the constant was; the internal value isalways used. This has particular consequences for conversion ofnumbers to strings:

     $ gawk 'BEGIN { printf "0x11 is <%s>\n", 0x11 }'
     -| 0x11 is <17>


Previous:  Nondecimal-numbers,Up:  Constants

6.1.1.3 Regular Expression Constants

A regexp constant is a regular expression description enclosed inslashes, such as /^beginning and end$/. Most regexps used inawk programs are constant, but the ‘~’ and ‘!~’matching operators can also match computed or dynamic regexps(which are just ordinary strings or variables that contain a regexp).


Next:  ,Previous:  Constants,Up:  Values

6.1.2 Using Regular Expression Constants

When used on the righthand side of the ‘~’ or ‘!~’operators, a regexp constant merely stands for the regexp that is to bematched. However, regexp constants (such as /foo/) may be used like simple expressions. When aregexp constant appears by itself, it has the same meaning as if it appearedin a pattern, i.e., ‘($0 ~ /foo/)’(d.c.) See Expression Patterns. This means that the following two code segments:

     if ($0 ~ /barfly/ || $0 ~ /camelot/)
         print "found"

and:

     if (/barfly/ || /camelot/)
         print "found"

are exactly equivalent. One rather bizarre consequence of this rule is that the followingBoolean expression is valid, but does not do what the user probablyintended:

     # Note that /foo/ is on the left of the ~
     if (/foo/ ~ $1) print "found foo"

This code is “obviously” testing$1 for a match against the regexp/foo/. But in fact, the expression ‘/foo/ ~ $1’ really means‘($0 ~ /foo/) ~ $1’. In other words, first match the input recordagainst the regexp /foo/. The result is either zero or one,depending upon the success or failure of the match. That resultis then matched against the first field in the record. Because it is unlikely that you would ever really want to make this kind oftest,gawk issues a warning when it sees this construct ina program. Another consequence of this rule is that the assignment statement:

     matches = /foo/

assigns either zero or one to the variable matches, dependingupon the contents of the current input record.

Constant regular expressions are also used as the first argument forthe gensub(),sub(), and gsub() functions, as thesecond argument of thematch() function,and as the third argument of the patsplit() function(seeString Functions). Modern implementations of awk, including gawk, allowthe third argument ofsplit() to be a regexp constant, but someolder implementations do not. (d.c.) This can lead to confusion when attempting to use regexp constantsas arguments to user-defined functions(seeUser-defined). For example:

     function mysub(pat, repl, str, global)
     {
         if (global)
             gsub(pat, repl, str)
         else
             sub(pat, repl, str)
         return str
     }
     
     {
         ...
         text = "hi! hi yourself!"
         mysub(/hi/, "howdy", text, 1)
         ...
     }

In this example, the programmer wants to pass a regexp constant to theuser-defined functionmysub, which in turn passes it on toeither sub() or gsub(). However, what really happens is thatthe pat parameter is either one or zero, depending upon whetheror not$0 matches /hi/. gawk issues a warning when it sees a regexp constant used asa parameter to a user-defined function, since passing a truth value inthis way is probably not what was intended.


Next:  ,Previous:  Using Constant Regexps,Up:  Values

6.1.3 Variables

Variables are ways of storing values at one point in your program foruse later in another part of your program. They can be manipulatedentirely within the program text, and they can also be assigned valueson the awk command line.

6.1.3.1 Using Variables in a Program

Variables let you give names to values and refer to them later. Variableshave already been used in many of the examples. The name of a variablemust be a sequence of letters, digits, or underscores, and it may not beginwith a digit. Case is significant in variable names; a and Aare distinct variables.

A variable name is a valid expression by itself; it represents thevariable's current value. Variables are given new values withassignment operators,increment operators, anddecrement operators. See Assignment Ops. In addition, the sub() and gsub() functions canchange a variable's value, and thematch(), patsplit()and split() functions can change the contents of theirarray parameters. SeeString Functions.

A few variables have special built-in meanings, such asFS (thefield separator), and NF (the number of fields in the current inputrecord). SeeBuilt-in Variables, for a list of the built-in variables. These built-in variables can be used and assigned just like all othervariables, but their values are also used or changed automatically byawk. All built-in variables' names are entirely uppercase.

Variables in awk can be assigned either numeric or string values. The kind of value a variable holds can change over the life of a program. By default, variables are initialized to the empty string, whichis zero if converted to a number. There is no need to explicitly“initialize” a variable inawk,which is what you would do in C and in most other traditional languages.


Previous:  Using Variables,Up:  Variables

6.1.3.2 Assigning Variables on the Command Line

Anyawk variable can be set by including a variable assignmentamong the arguments on the command line when awk is invoked(seeOther Arguments). Such an assignment has the following form:

     variable=text

With it, a variable is set either at the beginning of theawk run or in between input files. When the assignment is preceded with the -v option,as in the following:

     -v variable=text

the variable is set at the very beginning, even before theBEGIN rules execute. The-v option and its assignmentmust precede all the file name arguments, as well as the program text. (SeeOptions, for more information aboutthe -v option.) Otherwise, the variable assignment is performed at a time determined byits position among the input file arguments—after the processing of thepreceding 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. Beforethe first file is read, the command line sets the variablenequal to four. This causes the fourth field to be printed in lines frominventory-shipped. After the first file has finished,but before the second file is started,n is set to two, so that thesecond field is printed in lines from BBS-list:

     $ awk '{ print $n }' n=4 inventory-shipped n=2 BBS-list
     -| 15
     -| 24
     ...
     -| 555-5553
     -| 555-3412
     ...

Command-line arguments are made available for explicit examination bytheawk program in the ARGV array(seeARGC and ARGV). awk processes the values of command-line assignments for escapesequences(seeEscape Sequences). (d.c.)


Previous:  Variables,Up:  Values

6.1.4 Conversion of Strings and Numbers

Strings are converted to numbers and numbers are converted to strings, if the contextof the awk program demands it. For example, if the value ofeitherfoo or bar in the expression ‘foo + bar’happens to be a string, it is converted to a number before the additionis performed. If numeric values appear in string concatenation, theyare converted to strings. Consider the following:

     two = 2; three = 3
     print (two three) + 4

This prints the (numeric) value 27. The numeric values ofthe variablestwo and three are converted to strings andconcatenated together. The resulting string is converted back to thenumber 23, to which 4 is then added.

If, for some reason, you need to force a number to be converted to astring, concatenate that number with the empty string,"". To force a string to be converted to a number, add zero to that string. A string is converted to a number by interpreting any numeric prefixof the string as numerals:"2.5" converts to 2.5,"1e3" converts to 1000, and "25fix"has a numeric value of 25. Strings that can't be interpreted as valid numbers convert to zero.

The exact manner in which numbers are converted into strings is controlledby theawk built-in variable CONVFMT (seeBuilt-in Variables). Numbers are converted using thesprintf() functionwith CONVFMT as the formatspecifier(seeString Functions).

CONVFMT's default value is "%.6g", which prints a value withat most six significant digits. For some applications, you might want tochange it to specify more precision. On most modern machines,17 digits is usually enough to capture a floating-point number'svalue exactly.29

Strange results can occur if you setCONVFMT to a string that doesn'ttell sprintf() how to format floating-point numbers in a useful way. For example, if you forget the ‘%’ in the format,awk convertsall numbers to the same constant string.

As a special case, if a number is an integer, then the result of convertingit to a string isalways an integer, no matter what the value ofCONVFMT may be. Given the following code fragment:

     CONVFMT = "%2.2f"
     a = 12
     b = a ""

b has the value "12", not "12.00". (d.c.)

Prior to the POSIX standard, awk used the valueofOFMT for converting numbers to strings. OFMTspecifies the output format to use when printing numbers withprint. CONVFMT was introduced in order to separate the semantics ofconversion from the semantics of printing. BothCONVFMT andOFMT have the same default value: "%.6g". In the vast majorityof cases, oldawk programs do not change their behavior. However, these semantics forOFMT are something to keep in mind if you mustport your new-style program to older implementations ofawk. We recommendthat instead of changing your programs, just portgawk itself. See Print,for more information on theprint statement.

And, once again, where you are can matter when it comes to convertingbetween numbers and strings. InLocales, we mentioned thatthe local character set and language (the locale) can affect howgawk matches characters. The locale also affects numericformats. In particular, forawk programs, it affects thedecimal point character. The"C" locale, and most English-languagelocales, use the period character (‘.’) as the decimal point. However, many (if not most) European and non-English locales use the comma(‘,’) as the decimal point character.

The POSIX standard says that awk always uses the period as the decimalpoint when reading theawk program source code, and for command-linevariable assignments (seeOther Arguments). However, when interpreting input data, forprint and printf output,and for number to string conversion, the local decimal point character is used. Here are some examples indicating the difference in behavior,on a GNU/Linux system:

     $ gawk 'BEGIN { printf "%g\n", 3.1415927 }'
     -| 3.14159
     $ LC_ALL=en_DK gawk 'BEGIN { printf "%g\n", 3.1415927 }'
     -| 3,14159
     $ echo 4,321 | gawk '{ print $1 + 1 }'
     -| 5
     $ echo 4,321 | LC_ALL=en_DK gawk '{ print $1 + 1 }'
     -| 5,321

The ‘en_DK’ locale is for English in Denmark, where the comma acts asthe decimal point separator. In the normal"C" locale, gawktreats ‘4,321’ as ‘4’, while in the Danish locale, it's treatedas the full number, 4.321.

Some earlier versions of gawk fully complied with this aspectof the standard. However, many users in non-English locales complainedabout this behavior, since their data used a period as the decimalpoint, so the default behavior was restored to use a period as thedecimal point character. You can use the--use-lc-numericoption (see Options) to force gawk to use the locale'sdecimal point character. (gawk also uses the locale's decimalpoint character when in POSIX mode, either via--posix, or thePOSIXLY_CORRECT environment variable.)

table-locale-affects describes the cases in which the locale's decimalpoint character is used and when a period is used. Some of thesefeatures have not been described yet.

FeatureDefault--posix or --use-lc-numeric
%'gUse localeUse locale
%gUse periodUse locale
InputUse periodUse locale
strtonum()Use periodUse locale

Table 6.1: Locale Decimal Point versus A Period

Finally, modern day formal standards and IEEE standard floating pointrepresentation can have an unusual but important effect on the waygawk converts some special string values to numbers. The detailsare presented in POSIX Floating Point Problems.


Next:  ,Previous:  Values,Up:  Expressions

6.2 Operators: Doing Something With Values

This section introduces the operators which make useof the values provided by constants and variables.

6.2.1 Arithmetic Operators

The awk language uses the common arithmetic operators whenevaluating expressions. All of these arithmetic operators follow normalprecedence rules and work as you would expect them to.

The following example uses a file named grades, which containsa list of student names as well as three test scores per student (it'sa small class):

     Pat   100 97 58
     Sandy  84 72 93
     Chris  72 92 89

This program takes the file grades and prints the averageof the scores:

     $ awk '{ sum = $2 + $3 + $4 ; avg = sum / 3
     >        print $1, avg }' grades
     -| Pat 85
     -| Sandy 83
     -| Chris 84.3333

The following list provides the arithmetic operators in awk, in order fromthe highest precedence to the lowest:

- x
Negation.
+ x
Unary plus; the expression is converted to a number.


x ^ y x ** y
Exponentiation; x raised to the y power. ‘ 2 ^ 3’ hasthe value eight; the character sequence ‘ **’ is equivalent to‘ ^’. (c.e.)
x * y
Multiplication.


x / y
Division; because all numbers in awk are floating-pointnumbers, the result is not rounded to an integer—‘ 3 / 4’ hasthe value 0.75. (It is a common mistake, especially for C programmers,to forget that all numbers in awk are floating-point,and that division of integer-looking constants produces a real number,not an integer.)
x % y
Remainder; further discussion is provided in the text, justafter this list.
x + y
Addition.
x - y
Subtraction.

Unary plus and minus have the same precedence,the multiplication operators all have the same precedence, andaddition and subtraction have the same precedence.

When computing the remainder of ‘x %y’,the quotient is rounded toward zero to an integer andmultiplied byy. This result is subtracted from x;this operation is sometimes known as “trunc-mod.” The followingrelation always holds:

     b * int(a / b) + (a % b) == a

One possibly undesirable effect of this definition of remainder is thatx %y is negative if x is negative. Thus:

     -17 % 8 = -1

In other awk implementations, the signedness of the remaindermay be machine-dependent.

NOTE: The POSIX standard only specifies the use of ‘ ^’for exponentiation. For maximum portability, do not use the ‘ **’ operator.


Next:  ,Previous:  Arithmetic Ops,Up:  All Operators

6.2.2 String Concatenation

It seemed like a good idea at the time.
Brian Kernighan

There is only one string operation: concatenation. It does not have aspecific operator to represent it. Instead, concatenation is performed bywriting expressions next to one another, with no operator. For example:

     $ awk '{ print "Field number one: " $1 }' BBS-list
     -| Field number one: aardvark
     -| Field number one: alpo-net
     ...

Without the space in the string constant after the ‘:’, the lineruns together. For example:

     $ awk '{ print "Field number one:" $1 }' BBS-list
     -| Field number one:aardvark
     -| Field number one:alpo-net
     ...

Because string concatenation does not have an explicit operator, it isoften necessary to insure that it happens at the right time by usingparentheses to enclose the items to concatenate. For example,you might expect that thefollowing code fragment concatenates file andname:

     file = "file"
     name = "name"
     print "something meaningful" > file name

This produces a syntax error with some versions of Unixawk.30It is necessary to use the following:

     print "something meaningful" > (file name)

Parentheses should be used around concatenation in all but themost common contexts, such as on the righthand side of ‘=’. Be careful about the kinds of expressions used in string concatenation. In particular, the order of evaluation of expressions used for concatenationis undefined in theawk language. Consider this example:

     BEGIN {
         a = "don't"
         print (a " " (a = "panic"))
     }

It is not defined whether the assignment to a happensbefore or after the value ofa is retrieved for producing theconcatenated value. The result could be either ‘don't panic’,or ‘panic panic’.

The precedence of concatenation, when mixed with other operators, is oftencounter-intuitive. Consider this example:

     $ awk 'BEGIN { print -12 " " -24 }'
     -| -12-24

This “obviously” is concatenating −12, a space, and −24. But where did the space disappear to? The answer lies in the combination of operator precedences andawk's automatic conversion rules. To get the desired result,write the program this way:

     $ awk 'BEGIN { print -12 " " (-24) }'
     -| -12 -24

This forces awk to treat the ‘-’ on the ‘-24’ as unary. Otherwise, it's parsed as follows:

         −12 (" " − 24)
     ⇒ −12 (0 − 24)
     ⇒ −12 (−24)
     ⇒ −12−24

As mentioned earlier,when doing concatenation, parenthesize. Otherwise,you're never quite sure what you'll get.


Next:  ,Previous:  Concatenation,Up:  All Operators

6.2.3 Assignment Expressions

Anassignment is an expression that stores a (usually different)value into a variable. For example, let's assign the value one to the variablez:

     z = 1

After this expression is executed, the variable z has the value one. Whatever old valuez had before the assignment is forgotten.

Assignments can also store string values. For example, thefollowing storesthe value"this food is good" in the variable message:

     thing = "food"
     predicate = "good"
     message = "this " thing " is " predicate

This also illustrates string concatenation. The ‘=’ sign is called anassignment operator. It is thesimplest assignment operator because the value of the righthandoperand is stored unchanged. Most operators (addition, concatenation, and so on) have no effectexcept to compute a value. If the value isn't used, there's no reason touse the operator. An assignment operator is different; it doesproduce a value, but even if you ignore it, the assignment stillmakes itself felt through the alteration of the variable. We call thisaside effect.

The lefthand operand of an assignment need not be a variable(see Variables); it can also be a field(seeChanging Fields) oran array element (see Arrays). These are all called lvalues,which means they can appear on the lefthand side of an assignment operator. The righthand operand may be any expression; it produces the new valuethat the assignment stores in the specified variable, field, or arrayelement. (Such values are called rvalues.)

It is important to note that variables donot have permanent types. A variable's type is simply the type of whatever value it happensto hold at the moment. In the following program fragment, the variablefoo 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 thatit previously had a numeric value is forgotten.

String values that do not begin with a digit have a numeric value ofzero. After executing the following code, the value offoo is five:

     foo = "a string"
     foo = foo + 5
NOTE: Using a variable as a number and then later as a stringcan be confusing and is poor programming style. The previous two examplesillustrate how awk works, not how you should write yourprograms!

An assignment is an expression, so it has a value—the same value thatis assigned. Thus, ‘z = 1’ is an expression with the value one. One consequence of this is that you can write multiple assignments together,such as:

     x = y = z = 5

This example stores the value five in all three variables(x,y, and z). It does so because thevalue of ‘z = 5’, which is five, is stored intoy and thenthe value of ‘y = z = 5’, which is five, is stored intox.

Assignments may be used anywhere an expression is called for. Forexample, it is valid to write ‘x != (y = 1)’ to sety to one,and then test whether x equals one. But this style tends to makeprograms hard to read; such nesting of assignments should be avoided,except perhaps in a one-shot program.

Aside from ‘=’, there are several other assignment operators thatdo arithmetic with the old value of the variable. For example, theoperator ‘+=’ computes a new value by adding the righthand valueto the old value of the variable. Thus, the following assignment addsfive to the value of foo:

     foo += 5

This is equivalent to the following:

     foo = foo + 5

Use whichever makes the meaning of your program clearer.

There are situations where using ‘+=’ (or any assignment operator)isnot the same as simply repeating the lefthand operand in therighthand expression. For example:

     # Thanks to Pat Rankin for this example
     BEGIN  {
         foo[rand()] += 5
         for (x in foo)
            print x, foo[x]
     
         bar[rand()] = bar[rand()] + 5
         for (x in bar)
            print x, bar[x]
     }

The indices ofbar are practically guaranteed to be different, becauserand() returns different values each time it is called. (Arrays and therand() function haven't been covered yet. See Arrays,and seeNumeric Functions, for more information). This example illustrates an important fact about assignmentoperators: the lefthand expression is only evaluatedonce. It is up to the implementation as to which expression is evaluatedfirst, the lefthand or the righthand. Consider this example:

     i = 1
     a[i += 2] = i + 1

The value of a[3] could be either two or four.

table-assign-ops lists the arithmetic assignment operators. In eachcase, the righthand operand is an expression whose value is convertedto a number.

OperatorEffect
lvalue += incrementAdds increment to the value of lvalue.
lvalue -= decrementSubtracts decrement from the value of lvalue.
lvalue *= coefficientMultiplies the value of lvalue by coefficient.
lvalue /= divisorDivides the value of lvalue by divisor.
lvalue %= modulusSets lvalue to its remainder by modulus.
lvalue ^= power 
lvalue **= powerRaises lvalue to the power power. (c.e.)

Table 6.2: Arithmetic Assignment Operators

NOTE: Only the ‘ ^=’ operator is specified by POSIX. For maximum portability, do not use the ‘ **=’ operator.
Advanced Notes: Syntactic Ambiguities Between ‘/=’ and Regular Expressions

<!-- derived from email from "Nelson H. F. Beebe" -->

There is a syntactic ambiguity between the /= assignmentoperator and regexp constants whose first character is an ‘=’. (d.c.) This is most notable in commercialawk versions. For example:

     $ awk /==/ /dev/null
     error--> awk: syntax error at source line 1
     error-->  context is
     error-->         >>> /= <<<
     error--> awk: bailing out at source line 1

A workaround is:

     awk '/[=]=/' /dev/null

gawk does not have this problem,nor do the otherfreely available versions described inOther Versions.


Previous:  Assignment Ops,Up:  All Operators

6.2.4 Increment and Decrement Operators

Increment anddecrement operators increase or decrease the value ofa variable by one. An assignment operator can do the same thing, sothe increment operators add no power to theawk language; however, theyare convenient abbreviations for very common operations.

The operator used for adding one is written ‘++’. It can be used to incrementa variable either before or after taking its value. To pre-increment a variablev, write ‘++v’. This addsone to the value ofv—that new value is also the value of theexpression. (The assignment expression ‘v += 1’ is completelyequivalent.) Writing the ‘++’ after the variable specifies post-increment. Thisincrements the variable value just the same; the difference is that thevalue of the increment expression itself is the variable'soldvalue. Thus, if foo has the value four, then the expression ‘foo++’has the value four, but it changes the value offoo to five. In other words, the operator returns the old value of the variable,but with the side effect of incrementing it.

The post-increment ‘foo++’ is nearly the same as writing ‘(foo+= 1) - 1’. It is not perfectly equivalent because all numbers inawk are floating-point—in floating-point, ‘foo + 1 - 1’ doesnot necessarily equalfoo. But the difference is minute aslong as you stick to numbers that are fairly small (less than 10e12).

Fields and array elements are incrementedjust like variables. (Use ‘$(i++)’ when you want to do a field referenceand a variable increment at the same time. The parentheses are necessarybecause of the precedence of the field reference operator ‘$’.)

The decrement operator ‘--’ works just like ‘++’, except thatit subtracts one instead of adding it. As with ‘++’, it can be used beforethe lvalue to pre-decrement or after it to post-decrement. Following is a summary of increment and decrement expressions:

++ lvalue
Increment lvalue, returning the new value as thevalue of the expression.
lvalue ++
Increment lvalue, returning the old value of lvalueas the value of the expression.


-- lvalue
Decrement lvalue, returning the new value as thevalue of the expression. (This expression islike ‘ ++lvalue’, but instead of adding, it subtracts.)
lvalue --
Decrement lvalue, returning the old value of lvalueas the value of the expression. (This expression islike ‘ lvalue++’, but instead of adding, it subtracts.)

Advanced Notes: Operator Evaluation Order

Doctor, doctor! It hurts when I do this!
So don't do that!

Groucho Marx

What happens for something like the following?

     b = 6
     print b += b++

Or something even stranger?

     b = 6
     b += ++b + b++
     print b

In other words, when do the various side effects prescribed by thepostfix operators (‘b++’) take effect? When side effects happen isimplementation defined. In other words, it is up to the particular version ofawk. The result for the first example may be 12 or 13, and for the second, itmay be 22 or 23.

In short, doing things like this is not recommended and definitelynot anything that you can rely upon for portability. You should avoid such things in your own programs.


Next:  ,Previous:  All Operators,Up:  Expressions

6.3 Truth Values and Conditions

In certain contexts, expression values also serve as “truth values;” i.e.,they determine what should happen next as the program runs. Thissection describes howawk defines “true” and “false”and how values are compared.

6.3.1 True and False in awk

Many programming languages have a special representation for the conceptsof “true” and “false.” Such languages usually use the specialconstantstrue and false, or perhaps their uppercaseequivalents. However,awk is different. It borrows a very simple concept of true andfalse from C. Inawk, any nonzero numeric value or anynonempty string value is true. Any other value (zero or the nullstring,"") is false. The following program prints ‘A strangetruth value’ three times:

     BEGIN {
        if (3.1415927)
            print "A strange truth value"
        if ("Four Score And Seven Years Ago")
            print "A strange truth value"
        if (j = 57)
            print "A strange truth value"
     }

There is a surprising consequence of the “nonzero or non-null” rule:the string constant"0" is actually true, because it is non-null. (d.c.)

6.3.2 Variable Typing and Comparison Expressions
The Guide is definitive. Reality is frequently inaccurate.
The Hitchhiker's Guide to the Galaxy

Unlike other programming languages, awk variables do not have afixed type. Instead, they can be either a number or a string, dependingupon the value that is assigned to them. We look now at how variables are typed, and howawkcompares variables.

6.3.2.1 String Type Versus Numeric Type

The 1992 POSIX standard introducedthe concept of anumeric string, which is simply a string that lookslike a number—for example," +2". This concept is usedfor determining the type of a variable. The type of the variable is important because the types of two variablesdetermine how they are compared. The various versions of the POSIX standard did not get the rulesquite right for several editions. Fortunately, as of at least the2008 standard (and possibly earlier), the standard has been fixed,and variable typing follows these rules:31

  • A numeric constant or the result of a numeric operation has the numericattribute.
  • A string constant or the result of a string operation has the stringattribute.
  • Fields, getline input, FILENAME, ARGV elements,ENVIRON elements, and the elements of an array created bypatsplit(),split() and match() that are numericstrings have the strnum attribute. Otherwise, they havethe string attribute. Uninitialized variables also have thestrnum attribute.
  • Attributes propagate across assignments but are not changed byany use.

The last rule is particularly important. In the following program,a has numeric type, even though it is later used in a stringoperation:

     BEGIN {
          a = 12.345
          b = a " is a cute number"
          print b
     }

When two operands are compared, either string comparison or numeric comparisonmay be used. This depends upon the attributes of the operands, according to thefollowing symmetric matrix:

             +——————————————————————–
             |       STRING          NUMERIC         STRNUM
     ———–+——————————————————————–
             |
     STRING  |       string          string          string
             |
     NUMERIC |       string          numeric         numeric
             |
     STRNUM  |       string          numeric         numeric
     ———–+——————————————————————–

The basic idea is that user input that looks numeric—and onlyuser input—should be treated as numeric, even though it is actuallymade of characters and is therefore also a string. Thus, for example, the string constant" +3.14",when it appears in program source code,is a string—even though it looks numeric—andisnever treated as number for comparisonpurposes.

In short, when one operand is a “pure” string, such as a stringconstant, then a string comparison is performed. Otherwise, anumeric comparison is performed.

This point bears additional emphasis: All user input is made of characters,and so is first and foremost ofstring type; input stringsthat look numeric are additionally given thestrnum attribute. Thus, the six-character input string ‘ +3.14’ receives thestrnum attribute. In contrast, the eight-character literal" +3.14" appearing in program text is a string constant. The following examples print ‘1’ when the comparison betweenthe two different constants is true, ‘0’ otherwise:

     $ echo ' +3.14' | gawk '{ print $0 == " +3.14" }'    True
     -| 1
     $ echo ' +3.14' | gawk '{ print $0 == "+3.14" }'     False
     -| 0
     $ echo ' +3.14' | gawk '{ print $0 == "3.14" }'      False
     -| 0
     $ echo ' +3.14' | gawk '{ print $0 == 3.14 }'        True
     -| 1
     $ echo ' +3.14' | gawk '{ print $1 == " +3.14" }'    False
     -| 0
     $ echo ' +3.14' | gawk '{ print $1 == "+3.14" }'     True
     -| 1
     $ echo ' +3.14' | gawk '{ print $1 == "3.14" }'      False
     -| 0
     $ echo ' +3.14' | gawk '{ print $1 == 3.14 }'        True
     -| 1
6.3.2.2 Comparison Operators

Comparison expressions compare strings or numbers forrelationships such as equality. They are written usingrelationaloperators, which are a superset of those in C. table-relational-ops describes them.

ExpressionResult
x < yTrue if x is less than y.
x <= yTrue if x is less than or equal to y.
x > yTrue if x is greater than y.
x >= yTrue if x is greater than or equal to y.
x == yTrue if x is equal to y.
x != yTrue if x is not equal to y.
x ~ yTrue if the string x matches the regexp denoted byy.
x !~ yTrue if the string x does not match the regexp denoted byy.
subscript in arrayTrue if the array array has an element with the subscriptsubscript.

Table 6.3: Relational Operators

Comparison expressions have the value one if true and zero if false. When comparing operands of mixed types, numeric operands are convertedto strings using the value ofCONVFMT(see Conversion).

Strings are comparedby comparing the first character of each, then the second character of each,and so on. Thus,"10" is less than "9". If there are twostrings where one is a prefix of the other, the shorter string is less thanthe longer one. Thus,"abc" is less than "abcd".

It is very easy to accidentally mistype the ‘==’ operator andleave off one of the ‘=’ characters. The result is still validawk code, but the program does not do what is intended:

     if (a = b)   # oops! should be a == b
        ...
     else
        ...

Unless b happens to be zero or the null string, theifpart of the test always succeeds. Because the operators areso similar, this kind of error is very difficult to spot whenscanning the source code.

The following table of expressions illustrates the kind of comparisongawk performs, as well as what the result of the comparison is:

1.5 <= 2.0
numeric comparison (true)
"abc" >= "xyz"
string comparison (false)
1.5 != " +2"
string comparison (true)
"1e2" < "3"
string comparison (true)
a = 2; b = "2" a == b
string comparison (true)
a = 2; b = " +2"
a == b
string comparison (false)

In this example:

     $ echo 1e2 3 | awk '{ print ($1 < $2) ? "true" : "false" }'
     -| false

the result is ‘false’ because both$1 and $2are user input. They are numeric strings—therefore both havethestrnum attribute, dictating a numeric comparison. The purpose of the comparison rules and the use of numeric strings isto attempt to produce the behavior that is “least surprising,” whilestill “doing the right thing.”

String comparisons and regular expression comparisons are very different. For example:

     x == "foo"

has the value one, or is true if the variable xis precisely ‘foo’. By contrast:

     x ~ /foo/

has the value one if x contains ‘foo’, such as"Oh, what a fool am I!".

The righthand operand of the ‘~’ and ‘!~’ operators may beeither a regexp constant (/.../) or an ordinaryexpression. In the latter case, the value of the expression as a string is used as adynamic regexp (see Regexp Usage; alsoseeComputed Regexps).

In modern implementations ofawk, a constant regularexpression in slashes by itself is also an expression. The regexp/regexp/ is an abbreviation for the following comparison expression:

     $0 ~ /regexp/

One special place where /foo/ is not an abbreviation for‘$0 ~ /foo/’ is when it is the righthand operand of ‘~’ or‘!~’. See Using Constant Regexps,where this is discussed in more detail.

6.3.2.3 String Comparison With POSIX Rules

The POSIX standard says that string comparison is performed basedon the locale's collating order. This is usually very differentfrom the results obtained when doing straight character-by-charactercomparison.32

Because this behavior differs considerably from existing practice,gawk only implements it when in POSIX mode (seeOptions). Here is an example to illustrate the difference, in an ‘en_US.UTF-8’locale:

     $ gawk 'BEGIN { printf("ABC < abc = %s\n",
     >                     ("ABC" < "abc" ? "TRUE" : "FALSE")) }'
     -| ABC < abc = TRUE
     $ gawk --posix 'BEGIN { printf("ABC < abc = %s\n",
     >                             ("ABC" < "abc" ? "TRUE" : "FALSE")) }'
     -| ABC < abc = FALSE
6.3.3 Boolean Expressions

ABoolean expression is a combination of comparison expressions ormatching expressions, using the Boolean operators “or”(‘||’), “and” (‘&&’), and “not” (‘!’), along withparentheses to control nesting. The truth value of the Boolean expression iscomputed by combining the truth values of the component expressions. Boolean expressions are also referred to aslogical expressions. The terms are equivalent.

Boolean expressions can be used wherever comparison and matchingexpressions can be used. They can be used inif, while,do, and for statements(seeStatements). They have numeric values (one if true, zero if false) that come into playif the result of the Boolean expression is stored in a variable orused in arithmetic.

In addition, every Boolean expression is also a valid pattern, soyou can use one as a pattern to control the execution of rules. The Boolean operators are:

boolean1 && boolean2
True if both boolean1 and boolean2 are true. For example,the following statement prints the current input record if it containsboth ‘ 2400’ and ‘ foo’:
          if ($0 ~ /2400/ && $0 ~ /foo/) print

The subexpression boolean2 is evaluated only if boolean1is true. This can make a difference whenboolean2 containsexpressions that have side effects. In the case of ‘$0 ~ /foo/ &&($2 == bar++)’, the variablebar is not incremented if there isno substring ‘foo’ in the record.

boolean1 || boolean2
True if at least one of boolean1 or boolean2 is true. For example, the following statement prints all records in the inputthat contain either2400’ or‘ foo’ or both:
          if ($0 ~ /2400/ || $0 ~ /foo/) print

The subexpression boolean2 is evaluated only if boolean1is false. This can make a difference whenboolean2 containsexpressions that have side effects.

! boolean
True if boolean is false. For example,the following program prints ‘ no home!’ inthe unusual event that the HOME environmentvariable is not defined:
          BEGIN { if (! ("HOME" in ENVIRON))
                         print "no home!" }

(The in operator is described inReference to Elements.)

The ‘&&’ and ‘||’ operators are calledshort-circuitoperators because of the way they work. Evaluation of the full expressionis “short-circuited” if the result can be determined part way throughits evaluation.

Statements that use ‘&&’ or ‘||’ can be continued simplyby putting a newline after them. But you cannot put a newline in frontof either of these operators without using backslash continuation(see Statements/Lines).

The actual value of an expression using the ‘!’ operator iseither one or zero, depending upon the truth value of the expression itis applied to. The ‘!’ operator is often useful for changing the sense of a flagvariable from false to true and back again. For example, the followingprogram is one way to print lines in between special bracketing lines:

     $1 == "START"   { interested = ! interested; next }
     interested == 1 { print }
     $1 == "END"     { interested = ! interested; next }

The variable interested, as with all awk variables, startsout initialized to zero, which is also false. When a line is seen whosefirst field is ‘START’, the value of interested is toggledto true, using ‘!’. The next rule prints lines as long asinterested is true. When a line is seen whose first field is‘END’,interested is toggled back to false.33

NOTE: The next statement is discussed in Next Statement. next tells awk to skip the rest of the rules, get thenext record, and start processing the rules over again at the top. The reason it's there is to avoid printing the bracketing‘ START’ and ‘ END’ lines.
6.3.4 Conditional Expressions

Aconditional expression is a special kind of expression that hasthree operands. It allows you to use one expression's value to selectone of two other expressions. The conditional expression is the same as in the C language,as shown here:

     selector ? if-true-exp : if-false-exp

There are three subexpressions. The first, selector, is alwayscomputed first. If it is “true” (not zero or not null), thenif-true-exp is computed next and its value becomes the value ofthe whole expression. Otherwise,if-false-exp is computed nextand its value becomes the value of the whole expression. For example, the following expression produces the absolute value ofx:

     x >= 0 ? x : -x

Each time the conditional expression is computed, only one ofif-true-exp andif-false-exp is used; the other is ignored. This is important when the expressions have side effects. For example,this conditional expression examines elementi of either arraya or array b, and incrementsi:

     x == y ? a[i++] : b[i++]

This is guaranteed to increment i exactly once, because each timeonly one of the two increment expressions is executedand the other is not. SeeArrays,for more information about arrays.

As a minor gawk extension,a statement that uses ‘?:’ can be continued simplyby putting a newline after either character. However, putting a newline in frontof either character does not work without using backslash continuation(see Statements/Lines). If --posix is specified(seeOptions), then this extension is disabled.

6.4 Function Calls

A function is a name for a particular calculation. This enables you toask for it by name at any point in the program. Forexample, the functionsqrt() computes the square root of a number.

A fixed set of functions arebuilt-in, which means they areavailable in every awk program. Thesqrt() function is oneof these. See Built-in, for a list of built-infunctions and their descriptions. In addition, you can definefunctions for use in your program. SeeUser-defined,for instructions on how to do this.

The way to use a function is with afunction call expression,which consists of the function name followed immediately by a list ofarguments in parentheses. The arguments are expressions thatprovide the raw materials for the function's calculations. When there is more than one argument, they are separated by commas. Ifthere are no arguments, just write ‘()’ after the function name. The following examples show function calls with and without arguments:

     sqrt(x^2 + y^2)        one argument
     atan2(y, x)            two arguments
     rand()                 no arguments

CAUTION: Do not put any space between the function name and the open-parenthesis! A user-defined function name looks just like the name of avariable—a space would make the expression look like concatenation ofa variable with an expression inside parentheses. With built-in functions, space before the parenthesis is harmless, butit is best not to get into the habit of using space to avoid mistakeswith user-defined functions.

Each function expects a particular numberof arguments. For example, the sqrt() function must be called witha single argument, the number of which to take the square root:

     sqrt(argument)

Some of the built-in functions have one ormore optional arguments. If those arguments are not supplied, the functionsuse a reasonable default value. SeeBuilt-in, for full details. If argumentsare omitted in calls to user-defined functions, then those arguments aretreated as local variables and initialized to the empty string(seeUser-defined).

As an advanced feature, gawk provides indirect function calls,which is a way to choose the function to call at runtime, instead ofwhen you write the source code to your program. We defer discussion ofthis feature until later; see Indirect Calls.

Like every other expression, the function call has a value, which iscomputed by the function based on the arguments you give it. In thisexample, the value of ‘sqrt(argument)’ is the square root ofargument. The following program reads numbers, one number per line, and prints thesquare root of each one:

     $ awk '{ print "The square root of", $1, "is", sqrt($1) }'
     1
     -| The square root of 1 is 1
     3
     -| The square root of 3 is 1.73205
     5
     -| The square root of 5 is 2.23607
     Ctrl-d

A function can also have side effects, such as assigningvalues to certain variables or doing I/O. This program shows how thematch() function(see String Functions)changes the variablesRSTART and RLENGTH:

     {
         if (match($1, $2))
             print RSTART, RLENGTH
         else
             print "no match"
     }

Here is a sample run:

     $ awk -f matchit.awk
     aaccdd  c+
     -| 3 2
     foo     bar
     -| no match
     abcdefg e
     -| 5 1


Next:  ,Previous:  Function Calls,Up:  Expressions

6.5 Operator Precedence (How Operators Nest)

Operator precedence determines how operators are grouped whendifferent operators appear close by in one expression. For example,‘*’ has higher precedence than ‘+’; thus, ‘a + b * c’means to multiplyb and c, and then add a to theproduct (i.e., ‘a + (b * c)’).

The normal precedence of the operators can be overruled by using parentheses. Think of the precedence rules as saying where theparentheses are assumed to be. Infact, it is wise to always use parentheses whenever there is an unusualcombination of operators, because other people who read the program maynot remember what the precedence is in this case. Even experienced programmers occasionally forget the exact rules,which leads to mistakes. Explicit parentheses help preventany such mistakes.

When operators of equal precedence are used together, the leftmostoperator groups first, except for the assignment, conditional, andexponentiation operators, which group in the opposite order. Thus, ‘a - b + c’ groups as ‘(a - b) + c’ and‘a = b = c’ groups as ‘a = (b = c)’.

Normally the precedence of prefix unary operators does not matter,because there is only one way to interpretthem: innermost first. Thus, ‘$++i’ means ‘$(++i)’ and‘++$x’ means ‘++($x)’. However, when another operator followsthe operand, then the precedence of the unary operators can matter. ‘$x^2’ means ‘($x)^2’, but ‘-x^2’ means‘-(x^2)’, because ‘-’ has lower precedence than ‘^’,whereas ‘$’ has higher precedence. Also, operators cannot be combined in a way that violates theprecedence rules; for example, ‘$$0++--’ is not a validexpression because the first ‘$’ has higher precedence than the‘++’; to avoid the problem the expression can be rewritten as‘$($0++)--’.

This table presents awk's operators, in order of highestto lowest precedence:

(...)
Grouping.


$
Field reference.


++ --
Increment, decrement.


^ **
Exponentiation. These operators group right-to-left.


+ - !
Unary plus, minus, logical “not.”


* / %
Multiplication, division, remainder.


+ -
Addition, subtraction.
String Concatenation
There is no special symbol for concatenation. The operands are simply written side by side(see Concatenation).


< <= == != > >= >> | |&
Relational and redirection. The relational operators and the redirections have the same precedencelevel. Characters such as ‘ >’ serve both as relationals and asredirections; the context distinguishes between the two meanings.

Note that the I/O redirection operators inprint and printfstatements belong to the statement level, not to expressions. Theredirection does not produce an expression that could be the operand ofanother operator. As a result, it does not make sense to use aredirection operator near another operator of lower precedence withoutparentheses. Such combinations (for example, ‘print foo > a ? b : c’),result in syntax errors. The correct way to write this statement is ‘print foo > (a ? b : c)’.


~ !~
Matching, nonmatching.


in
Array membership.


&&
Logical “and”.


||
Logical “or”.


?:
Conditional. This operator groups right-to-left.


= += -= *= /= %= ^= **=
Assignment. These operators group right-to-left.

NOTE: The ‘ |&’, ‘ **’, and ‘ **=’ operators are not specified by POSIX. For maximum portability, do not use them.


Previous:  Precedence,Up:  Expressions

6.6 Where You Are Makes A Difference

Modern systems support the notion oflocales: a way to tellthe system about the local character set and language.

Once upon a time, the locale setting used to affect regexp matching(see Ranges and Locales), but this is no longer true.

Locales can affect record splitting. For the normal case of ‘RS = "\n"’, the locale is largely irrelevant. For other single-character record separators, setting ‘LC_ALL=C’in the environmentwill give you much better performance when reading records. Otherwise,gawk has to make several function calls,per inputcharacter, to find the record terminator.

According to POSIX, string comparison is also affected by locales(similar to regular expressions). The details are presented inPOSIX String Comparison.

Finally, the locale affects the value of the decimal point characterused when gawk parses input data. This is discussed indetail inConversion.


Next:  ,Previous:  Expressions,Up:  Top

7 Patterns, Actions, and Variables

As you have already seen, each awk statement consists ofa pattern with an associated action. This chapter describes howyou build patterns and actions, what kinds of things you can do withinactions, and awk's built-in variables.

The pattern-action rules and the statements available for usewithin actions form the core ofawk programming. In a sense, everything coveredup to here has been the foundationthat programs are built on top of. Now it's time to startbuilding something useful.

7.1 Pattern Elements

Patterns in awk control the execution of rules—a rule isexecuted when its pattern matches the current input record. The following is a summary of the types ofawk patterns:

/ regular expression /
A regular expression. It matches when the text of theinput record fits the regular expression. (See Regexp.)
expression
A single expression. It matches when its valueis nonzero (if a number) or non-null (if a string). (See Expression Patterns.)
pat1 , pat2
A pair of patterns separated by a comma, specifying a range of records. The range includes both the initial record that matches pat1 andthe final record that matches pat2. (See Ranges.)
BEGIN END
Special patterns for you to supply startup or cleanup actions for your awk program. (See BEGIN/END.)
BEGINFILE ENDFILE
Special patterns for you to supply startup or cleanup actions todone on a per file basis. (See BEGINFILE/ENDFILE.)
empty
The empty pattern matches every input record. (See Empty.)
7.1.1 Regular Expressions as Patterns

Regular expressions are one of the first kinds of patterns presentedin this book. This kind of pattern is simply a regexp constant in the pattern part ofa rule. Its meaning is ‘$0 ~ /pattern/’. The pattern matches when the input record matches the regexp. For example:

     /foo|bar|baz/  { buzzwords++ }
     END            { print buzzwords, "buzzwords seen" }


Next:  ,Previous:  Regexp Patterns,Up:  Pattern Overview

7.1.2 Expressions as Patterns

Any awk expression is valid as anawk pattern. The pattern matches if the expression's value is nonzero (if anumber) or non-null (if a string). The expression is reevaluated each time the rule is tested against a newinput record. If the expression uses fields such as $1, thevalue depends directly on the new input record's text; otherwise, itdepends on only what has happened so far in the execution of theawk program.

Comparison expressions, using the comparison operators described inTyping and Comparison,are a very common kind of pattern. Regexp matching and nonmatching are also very common expressions. The left operand of the ‘~’ and ‘!~’ operators is a string. The right operand is either a constant regular expression enclosed inslashes (/regexp/), or any expression whose string valueis used as a dynamic regular expression(seeComputed Regexps). The following example prints the second field of each input recordwhose first field is precisely ‘foo’:

     $ awk '$1 == "foo" { print $2 }' BBS-list

(There is no output, because there is no BBS site with the exact name ‘foo’.) Contrast this with the following regular expression match, whichaccepts any record with a first field that contains ‘foo’:

     $ awk '$1 ~ /foo/ { print $2 }' BBS-list
     -| 555-1234
     -| 555-6699
     -| 555-6480
     -| 555-2127

A regexp constant as a pattern is also a special case of an expressionpattern. The expression/foo/ has the value one if ‘foo’appears in the current input record. Thus, as a pattern,/foo/matches any record containing ‘foo’.

Boolean expressions are also commonly used as patterns. Whether the patternmatches an input record depends on whether its subexpressions match. For example, the following command prints all the records inBBS-list that contain both ‘2400’ and ‘foo’:

     $ awk '/2400/ && /foo/' BBS-list
     -| fooey        555-1234     2400/1200/300     B

The following command prints all records inBBS-list that containeither2400’ or ‘foo’(or both, of course):

     $ awk '/2400/ || /foo/' BBS-list
     -| alpo-net     555-3412     2400/1200/300     A
     -| bites        555-1675     2400/1200/300     A
     -| 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 following command prints all records inBBS-list that donot contain the string ‘foo’:

     $ awk '! /foo/' BBS-list
     -| 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
     -| sdace        555-3430     2400/1200/300     A

The subexpressions of a Boolean operator in a pattern can be constant regularexpressions, comparisons, or any otherawk expressions. Rangepatterns are not expressions, so they cannot appear inside Booleanpatterns. Likewise, the special patternsBEGIN, END,BEGINFILE and ENDFILE,which never match any input record, are not expressions and cannotappear inside Boolean patterns.


Next:  ,Previous:  Expression Patterns,Up:  Pattern Overview

7.1.3 Specifying Record Ranges with Patterns

Arange pattern is made of two patterns separated by a comma, inthe form ‘begpat,endpat’. It is used to match ranges ofconsecutive input records. The first pattern,begpat, controlswhere the range begins, while endpat controls wherethe pattern ends. For example, the following:

     awk '$1 == "on", $1 == "off"' myfile

prints every record in myfile between ‘on’/‘off’ pairs, inclusive.

A range pattern starts out by matching begpat against everyinput record. When a record matchesbegpat, the range pattern isturned on and the range pattern matches this record as well. As long asthe range pattern stays turned on, it automatically matches every inputrecord read. The range pattern also matchesendpat against everyinput record; when this succeeds, the range pattern is turned off againfor the following record. Then the range pattern goes back to checkingbegpat against each record.

The record that turns on the range pattern and the one that turns itoff both match the range pattern. If you don't want to operate onthese records, you can write if statements in the rule's actionto distinguish them from the records you are interested in.

It is possible for a pattern to be turned on and off by the samerecord. If the record satisfies both conditions, then the action isexecuted for just that record. For example, suppose there is text between two identical markers (e.g.,the ‘%’ symbol), each on its own line, that should be ignored. A first attempt would be tocombine a range pattern that describes the delimited text with thenext statement(not discussed yet, seeNext Statement). This causes awk to skip any further processing of the currentrecord and start over again with the next input record. Such a programlooks like this:

     /^%$/,/^%$/    { next }
                    { print }

This program fails because the range pattern is both turned on and turned offby the first line, which just has a ‘%’ on it. To accomplish this task,write the program in the following manner, using a flag:

     /^%$/     { skip = ! skip; next }
     skip == 1 { next } # skip lines with `skip' set

In a range pattern, the comma (‘,’) has the lowest precedence ofall the operators (i.e., it is evaluated last). Thus, the followingprogram attempts to combine a range pattern with another, simpler test:

     echo Yes | awk '/1/,/2/ || /Yes/'

The intent of this program is ‘(/1/,/2/) || /Yes/’. However,awk interprets this as ‘/1/, (/2/ || /Yes/)’. This cannot be changed or worked around; range patterns do not combinewith other patterns:

     $ echo Yes | gawk '(/1/,/2/) || /Yes/'
     error--> gawk: cmd. line:1: (/1/,/2/) || /Yes/
     error--> gawk: cmd. line:1:           ^ syntax error


Next:  ,Previous:  Ranges,Up:  Pattern Overview

7.1.4 The BEGIN and END Special Patterns

All the patterns described so far are for matching input records. TheBEGIN and END special patterns are different. They supply startup and cleanup actions forawk programs. BEGIN and END rules must have actions; there is no defaultaction for these rules because there is no current record when they run.BEGIN and END rules are often referred to as“BEGIN andEND blocks” by long-time awkprogrammers.

7.1.4.1 Startup and Cleanup Actions

A BEGIN rule is executed once only, before the first input recordis read. Likewise, anEND rule is executed once only, after all theinput is read. For example:

     $ awk '
     > BEGIN { print "Analysis of \"foo\"" }
     > /foo/ { ++n }
     > END   { print "\"foo\" appears", n, "times." }' BBS-list
     -| Analysis of "foo"
     -| "foo" appears 4 times.

This program finds the number of records in the input fileBBS-listthat contain the string ‘foo’. TheBEGIN rule prints a titlefor the report. There is no need to use theBEGIN rule toinitialize the counter n to zero, since awk does thisautomatically (see Variables). The second rule increments the variable n every time arecord containing the pattern ‘foo’ is read. TheEND ruleprints the value of n at the end of the run.

The special patterns BEGIN and END cannot be used in rangesor with Boolean operators (indeed, they cannot be used with any operators). Anawk program may have multiple BEGIN and/orENDrules. They are executed in the order in which they appear: all theBEGINrules at startup and all the END rules at termination.BEGIN and END rules may be intermixed with other rules. This feature was added in the 1987 version ofawk and is includedin the POSIX standard. The original (1978) version ofawkrequired the BEGIN rule to be placed at the beginning of theprogram, theEND rule to be placed at the end, and only allowed one ofeach. This is no longer required, but it is a good idea to follow this templatein terms of program organization and readability.

Multiple BEGIN and END rules are useful for writinglibrary functions, because each library file can have its ownBEGIN and/orEND rule to do its own initialization and/or cleanup. The order in which library functions are named on the command linecontrols the order in which theirBEGIN and END rules areexecuted. Therefore, you have to be careful when writing such rules inlibrary files so that the order in which they are executed doesn't matter. SeeOptions, for more information onusing library functions. SeeLibrary Functions,for a number of useful library functions.

If an awk program has only BEGIN rules and noother rules, then the program exits after theBEGIN rule isrun.34 However, if anEND rule exists, then the input is read, even if there areno other rules in the program. This is necessary in case theENDrule checks the FNR and NR variables.


Previous:  Using BEGIN/END,Up:  BEGIN/END

7.1.4.2 Input/Output from BEGIN and END Rules

There are several (sometimes subtle) points to remember when doing I/Ofrom aBEGIN or END rule. The first has to do with the value of$0 in a BEGINrule. Because BEGIN rules are executed before any input is read,there simply is no input record, and therefore no fields, whenexecutingBEGIN rules. References to $0 and the fieldsyield a null string or zero, depending upon the context. One wayto give$0 a real value is to execute a getline commandwithout a variable (seeGetline). Another way is simply to assign a value to $0.

The second point is similar to the first but from the other direction. Traditionally, due largely to implementation issues,$0 andNF were undefined inside an END rule. The POSIX standard specifies thatNF is available in an ENDrule. It contains the number of fields from the last input record. Most probably due to an oversight, the standard does not say that$0is also preserved, although logically one would think that it should be. In fact,gawk does preserve the value of $0 for use inEND rules. Be aware, however, that Brian Kernighan'sawk, and possiblyother implementations, do not.

The third point follows from the first two. The meaning of ‘print’inside aBEGIN or END rule is the same as always:‘print $0’. If$0 is the null string, then this prints anempty record. Many long timeawk programmers use an unadorned‘print’ inBEGIN and END rules, to mean ‘print ""’,relying on$0 being null. Although one might generally get away withthis in BEGIN rules, it is a very bad idea in END rules,at least in gawk. It is also poor style, since if an emptyline is needed in the output, the program should print one explicitly.

Finally, the next and nextfile statements are not allowedin a BEGIN rule, because the implicitread-a-record-and-match-against-the-rules loop has not started yet. Similarly, those statementsare not valid in anEND rule, since all the input has been read. (See Next Statement, and seeNextfile Statement.)


Next:  ,Previous:  BEGIN/END,Up:  Pattern Overview

7.1.5 The BEGINFILE and ENDFILE Special Patterns

This section describes agawk-specific feature.

Two special kinds of rule, BEGINFILE and ENDFILE, giveyou “hooks” intogawk's command-line file processing loop. As with theBEGIN and END rules (see BEGIN/END), allBEGINFILE rules in a program are merged, in the order they areread bygawk, and all ENDFILE rules are merged as well.

The body of the BEGINFILE rules is executed just beforegawk reads the first record from a file.FILENAMEis set to the name of the current file, and FNR is set to zero.

The BEGINFILE rule provides you the opportunity for two tasksthat would otherwise be difficult or impossible to perform:

  • You can test if the file is readable. Normally, it is a fatal error if afile named on the command line cannot be opened for reading. However,you can bypass the fatal error and move on to the next file on thecommand line.

    You do this by checking if the ERRNO variable is not the emptystring; if so, thengawk was not able to open the file. Inthis case, your program can execute thenextfile statement(see Nextfile Statement). This causesgawk to skipthe file entirely. Otherwise,gawk exits with the usualfatal error.

  • If you have written extensions that modify the record handling (by insertingan “open hook”), you can invoke them at this point, beforegawkhas started processing the file. (This is avery advanced feature,currently used only by the XMLgawk project.)

The ENDFILE rule is called when gawk has finished processingthe last record in an input file. For the last input file,it will be called before anyEND rules.

Normally, when an error occurs when reading input in the normal inputprocessing loop, the error is fatal. However, if anENDFILErule is present, the error becomes non-fatal, and instead ERRNOis set. This makes it possible to catch and process I/O errors at thelevel of theawk program.

Thenext statement (see Next Statement) is not allowed insideeither aBEGINFILE or and ENDFILE rule. The nextfilestatement (seeNextfile Statement) is allowed only inside aBEGINFILE rule, but not inside anENDFILE rule.

Thegetline statement (see Getline) is restricted insidebothBEGINFILE and ENDFILE. Only the ‘getlinevariable <file’ form is allowed.

BEGINFILE and ENDFILE are gawk extensions. In most otherawk implementations, or if gawk is incompatibility mode (seeOptions), they are not special.

7.1.6 The Empty Pattern

An empty (i.e., nonexistent) pattern is considered to matcheveryinput record. For example, the program:

     awk '{ print $1 }' BBS-list

prints the first field of every record.

7.2 Using Shell Variables in Programs

awk programs are often used as components in largerprograms written in shell. For example, it is very common to use a shell variable tohold a pattern that theawk program searches for. There are two ways to get the value of the shell variableinto the body of theawk program.

The most common method is to use shell quoting to substitutethe variable's value into the program inside the script. For example, in the following program:

     printf "Enter search pattern: "
     read pattern
     awk "/$pattern/ "'{ nmatches++ }
          END { print nmatches, "found" }' /path/to/data

the awk program consists of two pieces of quoted textthat are concatenated together to form the program. The first part is double-quoted, which allows substitution ofthepattern shell variable inside the quotes. The second part is single-quoted.

Variable substitution via quoting works, but can be potentiallymessy. It requires a good understanding of the shell's quoting rules(seeQuoting),and it's often difficult to correctlymatch up the quotes when reading the program.

A better method is to use awk's variable assignment feature(seeAssignment Options)to assign the shell variable's value to anawk variable'svalue. Then use dynamic regexps to match the pattern(seeComputed Regexps). The following shows how to redo theprevious example using this technique:

     printf "Enter search pattern: "
     read pattern
     awk -v pat="$pattern" '$0 ~ pat { nmatches++ }
            END { print nmatches, "found" }' /path/to/data

Now, the awk program is just one single-quoted string. The assignment ‘-v pat="$pattern"’ still requires double quotes,in case there is whitespace in the value of $pattern. The awk variablepat could be named patterntoo, but that would be more confusing. Using a variable alsoprovides more flexibility, since the variable can be used anywhere insidethe program—for printing, as an array subscript, or for any otheruse—without requiring the quoting tricks at every point in the program.

7.3 Actions

An awk program or script consists of a series ofrules and function definitions interspersed. (Functions aredescribed later. SeeUser-defined.) A rule contains a pattern and an action, either of which (but notboth) may be omitted. The purpose of theaction is to tellawk what to do once a match for the pattern is found. Thus,in outline, anawk program generally looks like this:

     [pattern]  { action }
      pattern  [{ action }]
     ...
     function name(args) { ... }
     ...

An action consists of one or more awk statements, enclosedin curly braces (‘{...}’). Each statement specifies onething to do. The statements are separated by newlines or semicolons. The curly braces around an action must be used even if the actioncontains only one statement, or if it contains no statements atall. However, if you omit the action entirely, omit the curly braces aswell. An omitted action is equivalent to ‘{ print $0 }’:

     /foo/  { }     match foo, do nothing --- empty action
     /foo/          match foo, print the record --- omitted action

The following types of statements are supported in awk:

Expressions
Call functions or assign values to variables(see Expressions). Executingthis kind of statement simply computes the value of the expression. This is useful when the expression has side effects(see Assignment Ops).
Control statements
Specify the control flow of awkprograms. The awk language gives you C-like constructs( if, for, while, and do) as well as a fewspecial ones (see Statements).
Compound statements
Consist of one or more statements enclosed incurly braces. A compound statement is used in order to put severalstatements together in the body of an if, while, do,or for statement.
Input statements
Use the getline command(see Getline). Also supplied in awk are the nextstatement (see Next Statement),and the nextfile statement(see Nextfile Statement).
Output statements
Such as print and printf. See Printing.
Deletion statements
For deleting array elements. See Delete.

7.4 Control Statements in Actions

Control statements, such asif, while, and so on,control the flow of execution in awk programs. Most of awk'scontrol statements are patterned after similar statements in C.

All the control statements start with special keywords, such as ifand while, to distinguish them from simple expressions. Many control statements contain other statements. For example, theif statement contains another statement that may or may not beexecuted. The contained statement is called thebody. To include more than one statement in the body, group them into asinglecompound statement with curly braces, separating them withnewlines or semicolons.


Next:  ,Up:  Statements

7.4.1 The if-else Statement

The if-else statement isawk's decision-makingstatement. It looks like this:

     if (condition) then-body [else else-body]

The condition is an expression that controls what the rest of thestatement does. If thecondition is true, then-body isexecuted; otherwise, else-body is executed. Theelse part of the statement isoptional. The condition is considered false if its value is zero orthe null string; otherwise, the condition is true. Refer to the following:

     if (x % 2 == 0)
         print "x is even"
     else
         print "x is odd"

In this example, if the expression ‘x % 2 == 0’ is true (that is,if the value ofx is evenly divisible by two), then the firstprint statement is executed; otherwise, the secondprintstatement is executed. If the else keyword appears on the same line asthen-body andthen-body is not a compound statement (i.e., not surrounded bycurly braces), then a semicolon must separatethen-body fromthe else. To illustrate this, the previous example can be rewritten as:

     if (x % 2 == 0) print "x is even"; else
             print "x is odd"

If the ‘;’ is left out,awk can't interpret the statement andit produces a syntax error. Don't actually write programs this way,because a human reader might fail to see theelse if it is notthe first thing on its line.


Next:  ,Previous:  If Statement,Up:  Statements

7.4.2 The while Statement

In programming, aloop is a part of a program that canbe executed two or more times in succession. Thewhile statement is the simplest looping statement inawk. It repeatedly executes a statement as long as a condition istrue. For example:

     while (condition)
       body

body is a statement called thebody of the loop,and condition is an expression that controls how long the loopkeeps running. The first thing thewhile statement does is test the condition. If the condition is true, it executes the statementbody. After body has been executed,condition is tested again, and if it is still true,body isexecuted again. This process repeats until the condition is no longertrue. If thecondition is initially false, the body of the loop isnever executed andawk continues with the statement followingthe loop. This example prints the first three fields of each record, one per line:

     awk '{
            i = 1
            while (i <= 3) {
                print $i
                i++
            }
     }' inventory-shipped

The body of this loop is a compound statement enclosed in braces,containing two statements. The loop works in the following manner: first, the value ofi is set to one. Then, the while statement tests whetheri is less than or equal tothree. This is true when i equals one, so thei-thfield is printed. Then the ‘i++’ increments the value ofiand the loop repeats. The loop terminates when i reaches four.

A newline is not required between the condition and thebody; however using one makes the program clearer unless the body is acompound statement or else is very simple. The newline after the open-bracethat begins the compound statement is not required either, but theprogram is harder to read without it.


Next:  ,Previous:  While Statement,Up:  Statements

7.4.3 The do-while Statement

Thedo loop is a variation of the while looping statement. Thedo loop executes the body once and then repeats thebody as long as thecondition is true. It looks like this:

     do
       body
     while (condition)

Even if the condition is false at the start, the body isexecuted at least once (and only once, unless executingbodymakes condition true). Contrast this with the correspondingwhile statement:

     while (condition)
       body

This statement does not execute body even once if theconditionis false to begin with. The following is an example of a do statement:

     {
            i = 1
            do {
               print $0
               i++
            } while (i <= 10)
     }

This program prints each input record 10 times. However, it isn't a veryrealistic example, since in this case an ordinarywhile would dojust as well. This situation reflects actual experience; onlyoccasionally is there a real use for ado statement.


Next:  ,Previous:  Do Statement,Up:  Statements

7.4.4 The for Statement

The for statement makes it more convenient to count iterations of aloop. The general form of thefor statement looks like this:

     for (initialization; condition; increment)
       body

The initialization, condition, and increment parts arearbitrary awk expressions, andbody stands for anyawk statement.

The for statement starts by executing initialization. Then, as longas thecondition is true, it repeatedly executes body and thenincrement. Typically,initialization sets a variable toeither zero or one, increment adds one to it, andconditioncompares it against the desired number of iterations. For example:

     awk '{
            for (i = 1; i <= 3; i++)
               print $i
     }' inventory-shipped

This prints the first three fields of each input record, with one field perline.

It isn't possible toset more than one variable in theinitialization part without using a multiple assignment statementsuch as ‘x = y = 0’. This makes sense only if all the initial valuesare equal. (But it is possible to initialize additional variables by writingtheir assignments as separate statements preceding thefor loop.)

The same is true of the increment part. Incrementing additionalvariables requires separate statements at the end of the loop. The C compound expression, using C's comma operator, is useful inthis context but it is not supported inawk.

Most often, increment is an increment expression, as in the previousexample. But this is not required; it can be any expressionwhatsoever. For example, the following statement prints all the powers of twobetween 1 and 100:

     for (i = 1; i <= 100; i *= 2)
       print i

If there is nothing to be done, any of the three expressions in theparentheses following thefor keyword may be omitted. Thus,‘for (; x > 0;)’ is equivalent to ‘while (x > 0)’. If thecondition is omitted, it is treated as true, effectivelyyielding an infinite loop (i.e., a loop that never terminates).

In most cases, a for loop is an abbreviation for a whileloop, as shown here:

     initialization
     while (condition) {
       body
       increment
     }

The only exception is when thecontinue statement(see Continue Statement) is usedinside the loop. Changing afor statement to a whilestatement in this way can change the effect of thecontinuestatement inside the loop.

The awk language has a for statement in addition to awhile statement because afor loop is often both less work totype and more natural to think of. Counting the number of iterations isvery common in loops. It can be easier to think of this counting as partof looping rather than as something to do inside the loop.

There is an alternate version of thefor loop, for iterating overall the indices of an array:

     for (i in array)
         do something with array[i]

See Scanning an Array,for more information on this version of thefor loop.


Next:  ,Previous:  For Statement,Up:  Statements

7.4.5 The switch Statement

Theswitch statement allows the evaluation of an expression andthe execution of statements based on acase match. Case statementsare checked for a match in the order they are defined. If no suitablecase is found, thedefault section is executed, if supplied.

Each case contains a single constant, be it numeric, string, orregexp. Theswitch expression is evaluated, and then eachcase's constant is compared against the result in turn. The type of constantdetermines the comparison: numeric or string do the usual comparisons. A regexp constant does a regular expression match against the stringvalue of the original expression. The general form of theswitchstatement looks like this:

     switch (expression) {
     case value or regular expression:
         case-body
     default:
         default-body
     }

Control flow inthe switch statement works as it does in C. Once a match to a givencase is made, the case statement bodies execute until abreak,continue, next, nextfile orexit is encountered,or the end of the switch statement itself. For example:

     switch (NR * 2 + 1) {
     case 3:
     case "11":
         print NR - 1
         break
     
     case /2[[:digit:]]+/:
         print NR
     
     default:
         print NR + 1
     
     case -1:
         print NR * -1
     }

Note that if none of the statements specified above halt executionof a matchedcase statement, execution falls through to thenext case until execution halts. In the above example, forany case value starting with ‘2’ followed by one or more digits,theprint statement is executed and then falls through into thedefault section, executing itsprint statement. In turn,the −1 case will also be executed since thedefault doesnot halt execution.

This switch statement is a gawk extension. Ifgawk is in compatibility mode(see Options),it is not available.


Next:  ,Previous:  Switch Statement,Up:  Statements

7.4.6 The break Statement

Thebreak statement jumps out of the innermost for,while, ordo loop that encloses it. The following examplefinds the smallest divisor of any integer, and also identifies primenumbers:

     # 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, awkimmediatelybreaks out of the containing for loop. This meansthat awk proceeds immediately to the statement following the loopand continues processing. (This is very different from theexitstatement, which stops the entire awk program. SeeExit Statement.)

The following program illustrates how the condition of a fororwhile statement could be replaced with a break insideanif:

     # 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
         }
       }
     }

The break statement is also used to break out of theswitch statement. This is discussed inSwitch Statement.

Thebreak statement has no meaning whenused outside the body of a loop orswitch. However, although it was never documented,historical implementations ofawk treated the breakstatement outside of a loop as if it were anext statement(see Next Statement). (d.c.) Recent versions of Brian Kernighan'sawk no longer allow this usage,nor doesgawk.


Next:  ,Previous:  Break Statement,Up:  Statements

7.4.7 The continue Statement

Similar to break, the continue statement is used only insidefor,while, and do loops. It skipsover the rest of the loop body, causing the next cycle around the loopto begin immediately. Contrast this withbreak, which jumps outof the loop altogether.

The continue statement in a for loop directs awk toskip the rest of the body of the loop and resume execution with theincrement-expression of thefor statement. The following programillustrates this fact:

     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, forwhich theprintf is skipped. Because the increment ‘x++’is not skipped,x does not remain stuck at 5. Contrast thefor loop from the previous example with the followingwhile loop:

     BEGIN {
          x = 0
          while (x <= 20) {
              if (x == 5)
                  continue
              printf "%d ", x
              x++
          }
          print ""
     }

This program loops forever once x reaches 5.

Thecontinue statement has no special meaning with respect to theswitch statement, nor does it any meaning when used outside the body ofa loop. Historical versions ofawk treated a continuestatement outside a loop the same way they treated abreakstatement outside a loop: as if it were a nextstatement(seeNext Statement). (d.c.) Recent versions of Brian Kernighan'sawk no longer work this way, nordoes gawk.

7.4.8 The next Statement

The next statement forcesawk to immediately stop processingthe current record and go on to the next record. This means that nofurther rules are executed for the current record, and the rest of thecurrent rule's action isn't executed.

Contrast this with the effect of the getline function(see Getline). That also causesawk to read the next record immediately, but it does not alter theflow of control in any way (i.e., the rest of the current action executeswith a new input record).

At the highest level,awk program execution is a loop that readsan input record and then tests each rule's pattern against it. If youthink of this loop as afor statement whose body contains therules, then the next statement is analogous to acontinuestatement. It skips to the end of the body of this implicit loop andexecutes the increment (which reads another record).

For example, suppose an awk program works only on recordswith four fields, and it shouldn't fail when given bad input. To avoidcomplicating the rest of the program, write a “weed out” rule nearthe beginning, in the following manner:

     NF != 4 {
       err = sprintf("%s:%d: skipped: NF != 4\n", FILENAME, FNR)
       print err > "/dev/stderr"
       next
     }

Because of the next statement,the program's subsequent rules won't see the bad record. The errormessage is redirected to the standard error output stream, as errormessages should be. For more detail seeSpecial Files.

If the next statement causes the end of the input to be reached,then the code in anyEND rules is executed. See BEGIN/END.

The next statement is not allowed inside BEGINFILE andENDFILE rules. SeeBEGINFILE/ENDFILE.

According to the POSIX standard, the behavior is undefined ifthe next statement is used in aBEGIN or END rule. gawk treats it as a syntax error. Although POSIX permits it,some otherawk implementations don't allow the nextstatement inside function bodies(see User-defined). Just as with any othernext statement, a next statement inside afunction body reads the next record and starts processing it with thefirst rule in the program.


Next:  ,Previous:  Next Statement,Up:  Statements

7.4.9 Using gawk'snextfile Statement

gawk provides the nextfile statement,which is similar to the next statement. (c.e.) However, instead of abandoning processing of the current record, thenextfile statement instructsgawk to stop processing thecurrent data file.

The nextfile statement is a gawk extension. In most otherawk implementations,or if gawk is in compatibility mode(seeOptions),nextfile is not special.

Upon execution of the nextfile statement,any ENDFILE rules are executed,FILENAME isupdated to the name of the next data file listed on the command line,FNR is reset to one,ARGIND is incremented,any BEGINFILE rules are executed, and processingstarts over with the first rule in the program. (ARGIND hasn't been introduced yet. SeeBuilt-in Variables.) If the nextfile statement causes the end of the input to be reached,then the code in anyEND rules is executed. See BEGIN/END.

The nextfile statement is useful when there are many data filesto process but it isn't necessary to process every record in every file. Normally, in order to move on to the next data file, a programhas to continue scanning the unwanted records. The nextfilestatement accomplishes this much more efficiently.

In addition, nextfile is useful inside a BEGINFILErule to skip over a file that would otherwise causegawkto exit with a fatal error. See BEGINFILE/ENDFILE.

While one might think that ‘close(FILENAME)’ would accomplishthe same asnextfile, this isn't true. close() isreserved for closing files, pipes, and coprocesses that areopened with redirections. It is not related to the main processing thatawk does with the files listed in ARGV.

The current version of the Brian Kernighan's awk (see Other Versions) also supports nextfile. However, it doesn't allow thenextfile statement inside function bodies (seeUser-defined). gawk does; anextfile inside a function body reads thenext record and starts processing it with the first rule in the program,just as any othernextfile statement.


Previous:  Nextfile Statement,Up:  Statements

7.4.10 The exit Statement

The exit statement causesawk to immediately stopexecuting the current rule and to stop processing input; any remaining inputis ignored. Theexit statement is written as follows:

     exit [return code]

When anexit statement is executed from a BEGIN rule, theprogram stops processing everything immediately. No input records areread. However, if anEND rule is present,as part of executing the exit statement,theEND rule is executed(see BEGIN/END). Ifexit is used in the body of an END rule, it causesthe program to stop immediately.

An exit statement that is not part of a BEGIN or ENDrule stops the execution of any further automatic rules for the currentrecord, skips reading any remaining input records, and executes theEND rule if there is one. AnyENDFILE rules are also skipped; they are not executed.

In such a case,if you don't want the END rule to do its job, set a variableto nonzero before theexit statement and check that variable inthe END rule. SeeAssert Function,for an example that does this.

If an argument is supplied toexit, its value is used as the exitstatus code for the awk process. If no argument is supplied,exit causesawk to return a “success” status. In the case where an argumentis supplied to a firstexit statement, and then exit iscalled a second time from anEND rule with no argument,awk uses the previously supplied exit value. (d.c.) SeeExit Status, for more information.

For example, suppose an error condition occurs that is difficult orimpossible to handle. Conventionally, programs report this byexiting with a nonzero status. Anawk program can do thisusing an exit statement with a nonzero argument, as shownin the following example:

     BEGIN {
            if (("date" | getline date_now) <= 0) {
              print "Can't get system date" > "/dev/stderr"
              exit 1
            }
            print "current date is", date_now
            close("date")
     }
NOTE: For full portability, exit values should be between zero and 126, inclusive. Negative values, and values of 127 or greater, may not produce consistentresults across different operating systems.


Previous:  Statements,Up:  Patterns and Actions

7.5 Built-in Variables

Mostawk variables are available to use for your ownpurposes; they never change unless your program assigns values tothem, and they never affect anything unless your program examines them. However, a few variables inawk have special built-in meanings. awk examines some of these automatically, so that they enable youto tellawk how to do certain things. Others are setautomatically byawk, so that they carry information from theinternal workings ofawk to your program.

This section documents all the built-in variables ofgawk, most of which are also documented in the chaptersdescribing their areas of activity.

7.5.1 Built-in Variables That Control awk

The following is an alphabetical list of variables that you can change tocontrol howawk does certain things. The variables that arespecific togawk are marked with a pound sign (‘#’).

BINMODE #
On non-POSIX systems, this variable specifies use of binary mode for all I/O. Numeric values of one, two, or three specify that input files, output files, orall files, respectively, should use binary I/O. A numeric value less than zero is treated as zero, and a numeric value greater thanthree is treated as three. Alternatively,string values of "r" or "w" specify that input files andoutput files, respectively, should use binary I/O. A string value of "rw" or "wr" indicates that allfiles should use binary I/O. Any other string value is treated the same as "rw",but causes gawkto generate a warning message. BINMODE is described in more detail in PC Using.

This variable is agawk extension. In other awk implementations(exceptmawk,see Other Versions),or ifgawk is in compatibility mode(see Options),it is not special.


CONVFMT
This string controls conversion of numbers tostrings (see Conversion). It works by being passed, in effect, as the first argument to the sprintf() function(see String Functions). Its default value is "%.6g". CONVFMT was introduced by the POSIX standard.


FIELDWIDTHS #
This is a space-separated list of columns that tells gawkhow to split input with fixed columnar boundaries. Assigning a value to FIELDWIDTHSoverrides the use of FS and FPAT for field splitting. See Constant Size, for more information.

If gawk is in compatibility mode(seeOptions), then FIELDWIDTHShas no special meaning, and field-splitting operations occur basedexclusively on the value ofFS.


FPAT #
This is a regular expression (as a string) that tells gawkto create the fields based on text that matches the regular expression. Assigning a value to FPAToverrides the use of FS and FIELDWIDTHS for field splitting. See Splitting By Content, for more information.

If gawk is in compatibility mode(seeOptions), then FPAThas no special meaning, and field-splitting operations occur basedexclusively on the value ofFS.


FS
This is the input field separator(see Field Separators). The value is a single-character string or a multi-character regularexpression that matches the separations between fields in an inputrecord. If the value is the null string ( ""), then eachcharacter in the record becomes a separate field. (This behavior is a gawk extension. POSIX awk does notspecify the behavior when FS is the null string. Nonetheless, some other versions of awk also treat "" specially.)

The default value is" ", a string consisting of a singlespace. As a special exception, this value means that anysequence of spaces, TABs, and/or newlines is a single separator.35 It also causesspaces, TABs, and newlines at the beginning and end of a record to be ignored.

You can set the value of FS on the command line using the-F option:

          awk -F, 'program' input-files

Ifgawk is using FIELDWIDTHS orFPATfor field splitting,assigning a value to FS causes gawk to return tothe normal, FS-based field splitting. An easy way to do thisis to simply say ‘FS = FS’, perhaps with an explanatory comment.


IGNORECASE #
If IGNORECASE is nonzero or non-null, then all string comparisonsand all regular expression matching are case independent. Thus, regexpmatching with ‘ ~’ and ‘ !~’, as well as the gensub(), gsub(), index(), match(), patsplit(), split(), and sub()functions, record termination with RS, and field splitting with FS and FPAT, all ignore case when doing their particular regexp operations. However, the value of IGNORECASE does not affect array subscriptingand it does not affect field splitting when using a single-characterfield separator. See Case-sensitivity.

If gawk is in compatibility mode(seeOptions),then IGNORECASE has no special meaning. Thus, stringand regexp operations are always case-sensitive.


LINT #
When this variable is true (nonzero or non-null), gawkbehaves as if the --lint command-line option is in effect. (see Options). With a value of "fatal", lint warnings become fatal errors. With a value of "invalid", only warnings about things that areactually invalid are issued. (This is not fully implemented yet.) Any other true value prints nonfatal warnings. Assigning a false value to LINT turns off the lint warnings.

This variable is a gawk extension. It is not specialin otherawk implementations. Unlike the other special variables,changingLINT does affect the production of lint warnings,even if gawk is in compatibility mode. Much asthe--lint and --traditional options independentlycontrol different aspects ofgawk's behavior, the controlof lint warnings during program execution is independent of the flavorofawk being executed.


OFMT
This string controls conversion of numbers tostrings (see Conversion) forprinting with the print statement. It works by being passedas the first argument to the sprintf() function(see String Functions). Its default value is "%.6g". Earlier versions of awkalso used OFMT to specify the format for converting numbers tostrings in general expressions; this is now done by CONVFMT.


OFS
This is the output field separator (see Output Separators). It isoutput between the fields printed by a print statement. Itsdefault value is " ", a string consisting of a single space.


ORS
This is the output record separator. It is output at the end of every print statement. Its default value is "\n", the newlinecharacter. (See Output Separators.)


RS
This is awk's input record separator. Its default value is a stringcontaining a single newline character, which means that an input recordconsists of a single line of text. It can also be the null string, in which case records are separated byruns of blank lines. If it is a regexp, records are separated bymatches of the regexp in the input text. (See Records.)

The ability for RS to be a regular expressionis a gawk extension. In most otherawk implementations,or if gawk is in compatibility mode(seeOptions),just the first character of RS's value is used.


SUBSEP
This is the subscript separator. It has the default value of "\034" and is used to separate the parts of the indices of amultidimensional array. Thus, the expression foo["A", "B"]really accesses foo["A\034B"](see Multi-dimensional).


TEXTDOMAIN #
This variable is used for internationalization of programs at the awk level. It sets the default text domain for speciallymarked string constants in the source text, as well as for the dcgettext(), dcngettext() and bindtextdomain() functions(see Internationalization). The default value of TEXTDOMAIN is "messages".

This variable is a gawk extension. In otherawk implementations,or if gawk is in compatibility mode(seeOptions),it is not special.


Next:  ,Previous:  User-modified,Up:  Built-in Variables

7.5.2 Built-in Variables That Convey Information

The following is an alphabetical list of variables thatawksets automatically on certain occasions in order to provideinformation to your program. The variables that are specific togawk are marked with a pound sign (‘#’).

ARGC , ARGV
The command-line arguments available to awk programs are stored inan array called ARGV. ARGC is the number of command-linearguments present. See Other Arguments. Unlike most awk arrays, ARGV is indexed from 0 to ARGC − 1. In the following example:
          $ awk 'BEGIN {
          >         for (i = 0; i < ARGC; i++)
          >             print ARGV[i]
          >      }' inventory-shipped BBS-list
          -| awk
          -| inventory-shipped
          -| BBS-list

ARGV[0] contains ‘awk’,ARGV[1]contains ‘inventory-shipped’, andARGV[2] contains‘BBS-list’. The value ofARGC is three, one more than theindex of the last element in ARGV, because the elements are numberedfrom zero.

The namesARGC and ARGV, as well as the convention of indexingthe array from 0 toARGC − 1, are derived from the C language'smethod of accessing command-line arguments.

The value ofARGV[0] can vary from system to system. Also, you should note that the program text isnot included inARGV, nor are any of awk's command-line options. SeeARGC and ARGV, for informationabout how awk uses these variables. (d.c.)


ARGIND #
The index in ARGV of the current file being processed. Every time gawk opens a new data file for processing, it sets ARGIND to the index in ARGV of the file name. When gawk is processing the input files,‘ FILENAME == ARGV[ARGIND]’ is always true.

This variable is useful in file processing; it allows you to tell how faralong you are in the list of data files as well as to distinguish betweensuccessive instances of the same file name on the command line.

While you can change the value ofARGIND within your awkprogram,gawk automatically sets it to a new value when thenext file is opened.

This variable is a gawk extension. In otherawk implementations,or if gawk is in compatibility mode(seeOptions),it is not special.


ENVIRON
An associative array containing the values of the environment. The arrayindices are the environment variable names; the elements are the values ofthe particular environment variables. For example, ENVIRON["HOME"] might be /home/arnold. Changing this arraydoes not affect the environment passed on to any programs that awk may spawn via redirection or the system() function.

Some operating systems may not have environment variables. On such systems, theENVIRON array is empty (except forENVIRON["AWKPATH"],seeAWKPATH Variable).


ERRNO #
If a system error occurs during a redirection for getline,during a read for getline, or during a close() operation,then ERRNO contains a string describing the error.

In addition, gawk clears ERRNObefore opening each command-line input file. This enables checking ifthe file is readable inside aBEGINFILE pattern (see BEGINFILE/ENDFILE).

Otherwise,ERRNO works similarly to the C variable errno. Except for the case just mentioned,gawknever clears it (sets itto zero or ""). Thus, you should only expect its valueto be meaningful when an I/O operation returns a failurevalue, such asgetline returning −1. You are, of course, free to clear it yourself before doing anI/O operation.

This variable is a gawk extension. In otherawk implementations,or if gawk is in compatibility mode(seeOptions),it is not special.


FILENAME
The name of the file that awk is currently reading. When no data files are listed on the command line, awk readsfrom the standard input and FILENAME is set to "-". FILENAME is changed each time a new file is read(see Reading Files). Inside a BEGIN rule, the value of FILENAME is "", since there are no input files being processedyet. 36(d.c.) Note, though, that using getline(see Getline)inside a BEGIN rule can give FILENAME a value.


FNR
The current record number in the current file. FNR isincremented each time a new record is read(see Records). It is reinitializedto zero each time a new input file is started.


NF
The number of fields in the current input record. NF is set each time a new record is read, when a new field iscreated or when $0 changes (see Fields).

Unlike most of the variables described in thissection,assigning a value to NF has the potential to affectawk's internal workings. In particular, assignmentstoNF can be used to create or remove fields from thecurrent record. SeeChanging Fields.


NR
The number of input records awk has processed sincethe beginning of the program's execution(see Records). NR is incremented each time a new record is read.


PROCINFO #
The elements of this array provide access to information about therunning awk program. The following elements (listed alphabetically)are guaranteed to be available:
PROCINFO["egid"]
The value of the getegid() system call.
PROCINFO["euid"]
The value of the geteuid() system call.
PROCINFO["FS"]
This is "FS" if field splitting with FS is in effect, "FIELDWIDTHS" if field splitting with FIELDWIDTHS is in effect,or "FPAT" if field matching with FPAT is in effect.
PROCINFO["gid"]
The value of the getgid() system call.
PROCINFO["pgrpid"]
The process group ID of the current process.
PROCINFO["pid"]
The process ID of the current process.
PROCINFO["ppid"]
The parent process ID of the current process.
PROCINFO["sorted_in"]
If this element exists in PROCINFO, its value controls theorder in which array indices will be processed by‘ for (index in array) ...’ loops. Since this is an advanced feature, we defer thefull description until later; see Scanning an Array.
PROCINFO["strftime"]
The default time format string for strftime(). Assigning a new value to this element changes the default. See Time Functions.
PROCINFO["uid"]
The value of the getuid() system call.
PROCINFO["version"]
The version of gawk.

On some systems, there may be elements in the array, "group1"through"groupN" for some N. N is the number ofsupplementary groups that the process has. Use thein operatorto test for these elements(see Reference to Elements).

ThePROCINFO array is also used to cause coprocessesto communicate over pseudo-ttys instead of through two-way pipes;this is discussed further inTwo-way I/O.

This array is a gawk extension. In otherawk implementations,or if gawk is in compatibility mode(seeOptions),it is not special.


RLENGTH
The length of the substring matched by the match() function(see String Functions). RLENGTH is set by invoking the match() function. Its valueis the length of the matched string, or −1 if no match is found.


RSTART
The start-index in characters of the substring that is matched by the match() function(see String Functions). RSTART is set by invoking the match() function. Its valueis the position of the string where the matched substring starts, or zeroif no match was found.


RT #
This is set each time a record is read. It contains the input textthat matched the text denoted by RS, the record separator.

This variable is a gawk extension. In otherawk implementations,or if gawk is in compatibility mode(seeOptions),it is not special.

Advanced Notes: Changing NR and FNR

awk increments NR and FNReach time it reads a record, instead of setting them to the absolutevalue of the number of records read. This means that a program canchange these variables and their new values are incremented foreach record. (d.c.) The following example shows this:

     $ echo '1
     > 2
     > 3
     > 4' | awk 'NR == 2 { NR = 17 }
     > { print NR }'
     -| 1
     -| 17
     -| 18
     -| 19

Before FNR was added to the awk language(seeV7/SVR3.1),many awk programs used this feature to track the number ofrecords in a file by resettingNR to zero when FILENAMEchanged.


Previous:  Auto-set,Up:  Built-in Variables

7.5.3 Using ARGC and ARGV

Auto-set,presented the following program describing the information contained in ARGCand ARGV:

     $ awk 'BEGIN {
     >        for (i = 0; i < ARGC; i++)
     >            print ARGV[i]
     >      }' inventory-shipped BBS-list
     -| awk
     -| inventory-shipped
     -| BBS-list

In this example, ARGV[0] contains ‘awk’,ARGV[1]contains ‘inventory-shipped’, andARGV[2] contains‘BBS-list’. Notice that theawk program is not entered in ARGV. Theother command-line options, with their arguments, are also notentered. This includes variable assignments done with the-voption (see Options). Normal variable assignments on the command linearetreated as arguments and do show up in the ARGV array. Given the following program in a file namedshowargs.awk:

     BEGIN {
         printf "A=%d, B=%d\n", A, B
         for (i = 0; i < ARGC; i++)
             printf "\tARGV[%d] = %s\n", i, ARGV[i]
     }
     END   { printf "A=%d, B=%d\n", A, B }

Running it produces the following:

     $ awk -v A=1 -f showargs.awk B=2 /dev/null
     -| A=1, B=0
     -|        ARGV[0] = awk
     -|        ARGV[1] = B=2
     -|        ARGV[2] = /dev/null
     -| A=1, B=2

A program can alter ARGC and the elements of ARGV. Each timeawk reaches the end of an input file, it uses the nextelement ofARGV as the name of the next input file. By storing adifferent string there, a program can change which files are read. Use"-" to represent the standard input. Storingadditional elements and incrementingARGC causesadditional files to be read.

If the value of ARGC is decreased, that eliminates input filesfrom the end of the list. By recording the old value ofARGCelsewhere, a program can treat the eliminated arguments assomething other than file names.

To eliminate a file from the middle of the list, store the null string("") intoARGV in place of the file's name. As aspecial feature, awk ignores file names that have beenreplaced with the null string. Another option is touse thedelete statement to remove elements fromARGV (see Delete).

All of these actions are typically done in the BEGIN rule,before actual processing of the input begins. SeeSplit Program, and seeTee Program, for examplesof each way of removing elements fromARGV. The following fragment processes ARGV in order to examine, andthen remove, command-line options:

     BEGIN {
         for (i = 1; i < ARGC; i++) {
             if (ARGV[i] == "-v")
                 verbose = 1
             else if (ARGV[i] == "-q")
                 debug = 1
             else if (ARGV[i] ~ /^-./) {
                 e = sprintf("%s: unrecognized option -- %c",
                         ARGV[0], substr(ARGV[i], 2, 1))
                 print e > "/dev/stderr"
             } else
                 break
             delete ARGV[i]
         }
     }

To actually get the options into the awk program,end theawk options with -- and then supplytheawk program's options, in the following manner:

     awk -f myprog -- -v -q file1 file2 ...

This is not necessary ingawk. Unless --posix hasbeen specified,gawk silently puts any unrecognized optionsintoARGV for the awk program to deal with. As soonas it sees an unknown option,gawk stops looking for otheroptions that it might otherwise recognize. The previous example withgawk would be:

     gawk -f myprog -q -v file1 file2 ...

Because -q is not a validgawk option,it and the following -vare passed on to the awk program. (SeeGetopt Function, for an awk library functionthat parses command-line options.)


Next:  ,Previous:  Patterns and Actions,Up:  Top

8 Arrays in awk

An array is a table of values calledelements. Theelements of an array are distinguished by their indices. Indicesmay be either numbers or strings.

This chapter describes how arrays work in awk,how to use array elements, how to scan through every element in an array,and how to remove array elements. It also describes howawk simulates multidimensionalarrays, as well as some of the less obvious points about array usage. The chapter moves on to discussgawk's facilityfor sorting arrays, and ends with a brief description ofgawk'sability to support true multidimensional arrays.

awk maintains a single setof names that may be used for naming variables, arrays, and functions(seeUser-defined). Thus, you cannot have a variable and an array with the same name in thesameawk program.


Next:  ,Up:  Arrays

8.1 The Basics of Arrays

This section presents the basics: working with elementsin arrays one at a time, and traversing all of the elements inan array.

8.1.1 Introduction to Arrays

Doing linear scans over an associative array is like trying to club someoneto death with a loaded Uzi.
Larry Wall

The awk language provides one-dimensional arraysfor storing groups of related strings or numbers. Everyawk array must have a name. Array names have the samesyntax as variable names; any valid variable name would also be a validarray name. But one name cannot be used in both ways (as an array andas a variable) in the same awk program.

Arrays in awk superficially resemble arrays in other programminglanguages, but there are fundamental differences. Inawk, itisn't necessary to specify the size of an array before starting to use it. Additionally, any number or string inawk, not just consecutive integers,may be used as an array index.

In most other languages, arrays must be declared before use,including a specification ofhow many elements or components they contain. In such languages, thedeclaration causes a contiguous block of memory to be allocated for thatmany elements. Usually, an index in the array must be a positive integer. For example, the index zero specifies the first element in the array, which isactually stored at the beginning of the block of memory. Index onespecifies the second element, which is stored in memory right after thefirst element, and so on. It is impossible to add more elements to thearray, because it has room only for as many elements as given inthe declaration. (Some languages allow arbitrary starting and endingindices—e.g., ‘15 .. 27’—but the size of the array is still fixed whenthe array is declared.)

A contiguous array of four elements might look like the following example,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 ofthe values. Here, 8 is the value at index zero, because 8 appears in theposition with zero elements before it.

Arrays inawk are different—they are associative. This meansthat each array is a collection of pairs: an index and its correspondingarray element value:

     Index 3     Value 30
     Index 1     Value "foo"
     Index 0     Value 8
     Index 2     Value ""

The pairs are shown in jumbled order because their order is irrelevant.

One advantage of associative arrays is that new pairs can be addedat any time. For example, suppose a tenth element is added to the arraywhose value is"number ten". The result is:

     Index 10    Value "number ten"
     Index 3     Value 30
     Index 1     Value "foo"
     Index 0     Value 8
     Index 2     Value ""

Now the array issparse, which just means some indices are missing. It has elements 0–3 and 10, but doesn't have elements 4, 5, 6, 7, 8, or 9.

Another consequence of associative arrays is that the indices don'thave to be positive integers. Any number, or even a string, can bean index. For example, the following is an array that translates words fromEnglish to French:

     Index "dog" Value "chien"
     Index "cat" Value "chat"
     Index "one" Value "un"
     Index 1     Value "un"

Here we decided to translate the number one in both spelled-out andnumeric form—thus illustrating that a single array can have bothnumbers and strings as indices. In fact, array subscripts are always strings; this is discussedin more detail inNumeric Array Subscripts. Here, the number1 isn't double-quoted, since awkautomatically converts it to a string.

The value of IGNORECASE has no effect upon array subscripting. The identical string value used to store an array element must be usedto retrieve it. Whenawk creates an array (e.g., with the split()built-in function),that array's indices are consecutive integers starting at one. (SeeString Functions.)

awk's arrays are efficient—the time to access an elementis independent of the number of elements in the array.


Next:  ,Previous:  Array Intro,Up:  Array Basics

8.1.2 Referring to an Array Element

The principal way to use an array is to refer to one of its elements. An array reference is an expression as follows:

     array[index-expression]

Here, array is the name of an array. The expressionindex-expression isthe index of the desired element of the array.

The value of the array reference is the current value of that arrayelement. For example,foo[4.3] is an expression for the elementof array foo at index ‘4.3’.

A reference to an array element that has no recorded value yields a value of"", the null string. This includes elementsthat have not been assigned any value as well as elements that have beendeleted (seeDelete).

NOTE: A reference to an element that does not exist automatically createsthat array element, with the null string as its value. (In some cases,this is unfortunate, because it might waste memory inside awk.)

Novice awk programmers often make the mistake of checking ifan element exists by checking if the value is empty:

     # Check if "foo" exists in a:         Incorrect!
     if (a["foo"] != "") ...

This is incorrect, since this will create a["foo"]if it didn't exist before!

To determine whether an element exists in an array at a certain index, usethe following expression:

     ind in array

This expression tests whether the particular indexind exists,without the side effect of creating that element if it is not present. The expression has the value one (true) ifarray[ind]exists and zero (false) if it does not exist. For example, this statement tests whether the arrayfrequenciescontains the index ‘2’:

     if (2 in frequencies)
         print "Subscript 2 is present."

Note that this is not a test of whether the arrayfrequencies contains an element whosevalue is two. There is no way to do that except to scan all the elements. Also, thisdoes not createfrequencies[2], while the following(incorrect) alternative does:

     if (frequencies[2] != "")
         print "Subscript 2 is present."
8.1.3 Assigning Array Elements

Array elements can be assigned values just likeawk variables:

     array[index-expression] = value

array is the name of an array. The expressionindex-expression is the index of the element of the array that isassigned a value. The expressionvalue is the value toassign to that element of the array.

8.1.4 Basic Array Example

The following program takes a list of lines, each beginning with a linenumber, and prints them out in order of line number. The line numbersare not in order when they are first read—instead theyare scrambled. This program sorts the lines by making an array usingthe line numbers as subscripts. The program then prints out the linesin sorted order of their numbers. It is a very simple program and getsconfused upon encountering repeated numbers, gaps, or lines that don'tbegin with a number:

     
     {
       if ($1 > max)
         max = $1
       arr[$1] = $0
     }
     
     END {
       for (x = 1; x <= max; x++)
         print arr[x]
     }
     

The first rule keeps track of the largest line number seen so far;it also stores each line into the arrayarr, at an index thatis the line's number. The second rule runs after all the input has been read, to print outall 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:

     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

If a line number is repeated, the last line with a given number overridesthe others. Gaps in the line numbers can be handled with an easy improvement to theprogram'sEND rule, as follows:

     END {
       for (x = 1; x <= max; x++)
         if (x in arr)
           print arr[x]
     }


Previous:  Array Example,Up:  Array Basics

8.1.5 Scanning All Elements of an Array

In programs that use arrays, it is often necessary to use a loop thatexecutes once for each element of an array. In other languages, wherearrays are contiguous and indices are limited to positive integers,this is easy: all the valid indices can be found by counting fromthe lowest index up to the highest. This technique won't do the jobinawk, because any number or string can be an array index. Soawk has a special kind of for statement for scanningan array:

     for (var in array)
       body

This loop executesbody once for each index in array that theprogram has previously used, with the variablevar set to that index.

The following program uses this form of thefor statement. Thefirst rule scans the input records and notes which words appear (atleast once) in the input, by storing a one into the arrayused withthe word as index. The second rule scans the elements of used tofind all the distinct words that appear in the input. It prints eachword that is more than 10 characters long and also prints the number ofsuch words. SeeString Functions,for more information on the built-in functionlength().

     # Record a 1 for each word that is used at least once
     {
         for (i = 1; i <= NF; i++)
             used[$i] = 1
     }
     
     # Find number of distinct words more than 10 characters long
     END {
         for (x in used) {
             if (length(x) > 10) {
                 ++num_long_words
                 print x
             }
         }
         print num_long_words, "words longer than 10 characters"
     }

See Word Sorting,for a more detailed example of this type.

The order in which elements of the array are accessed by this statementis determined by the internal arrangement of the array elements withinawk and normally cannot be controlled or changed. This can lead toproblems if new elements are added toarray by statements inthe loop body; it is not predictable whether thefor loop willreach them. Similarly, changing var inside the loop may producestrange results. It is best to avoid such things.

As an extension, gawk makes it possible for you toloop over the elements of an array in order, based on the value ofPROCINFO["sorted_in"] (seeAuto-set). This is an advanced feature, so discussion of it is delayeduntilControlling Array Traversal.

In addition, gawk provides built-in functions forsorting arrays; seeArray Sorting Functions.


Next:  ,Previous:  Array Basics,Up:  Arrays

8.2 The delete Statement

To remove an individual element of an array, use the deletestatement:

     delete array[index-expression]

Once an array element has been deleted, any value the element oncehad is no longer available. It is as if the element had neverbeen referred to or been given a value. The following is an example of deleting elements in an array:

     for (i in frequencies)
       delete frequencies[i]

This example removes all the elements from the array frequencies. Once an element is deleted, a subsequentfor statement to scan the arraydoes not report that element and the in operator to check forthe presence of that element returns zero (i.e., false):

     delete foo[4]
     if (4 in foo)
         print "This will never be printed"

It is important to note that deleting an element isnot thesame as assigning it a null value (the empty string, ""). For example:

     foo[4] = ""
     if (4 in foo)
       print "This is printed, even though foo[4] is empty"

It is not an error to delete an element that does not exist. However, if--lint is provided on the command line(seeOptions),gawk issues a warning message when an element thatis not in the array is deleted.

All the elements of an array may be deleted with a single statement(c.e.) by leaving off the subscript in thedelete statement,as follows:

     delete array

This ability is a gawk extension; it is not available incompatibility mode (seeOptions).

Using this version of the delete statement is about three timesmore efficient than the equivalent loop that deletes each element oneat a time.

The following statement provides a portable but nonobvious way to clearout an array:37

     split("", array)

Thesplit() function(see String Functions)clears out the target array first. This call asks it to splitapart the null string. Because there is no data to split out, thefunction simply clears the array and then returns.

CAUTION: Deleting an array does not change its type; you cannotdelete an array and then use the array's name as a scalar(i.e., a regular variable). For example, the following does not work:
     a[1] = 3
     delete a
     a = 3


Next:  ,Previous:  Delete,Up:  Arrays

8.3 Using Numbers to Subscript Arrays

An important aspect to remember about arrays is that array subscriptsare always strings. When a numeric value is used as a subscript,it is converted to a string value before being used for subscripting(seeConversion). This means that the value of the built-in variableCONVFMT canaffect how your program accesses elements of an array. For example:

     xyz = 12.153
     data[xyz] = 1
     CONVFMT = "%2.2f"
     if (xyz in data)
         printf "%s is in data\n", xyz
     else
         printf "%s is not in data\n", xyz

This prints ‘12.15 is not in data’. The first statement givesxyz a numeric value. Assigning todata[xyz] subscriptsdata with the string value "12.153"(using the default conversion value ofCONVFMT, "%.6g"). Thus, the array element data["12.153"] is assigned the value one. The program then changesthe value ofCONVFMT. The test ‘(xyz in data)’ generates a newstring value fromxyz—this time "12.15"—because the value ofCONVFMT only allows two significant digits. This test fails,since"12.15" is different from "12.153".

According to the rules for conversions(seeConversion), integervalues are always converted to strings as integers, no matter what thevalue ofCONVFMT may happen to be. So the usual case ofthe following works:

     for (i = 1; i <= maxsub; i++)
         do something with array[i]

The “integer values always convert to strings as integers” rulehas an additional consequence for array indexing. Octal and hexadecimal constants(seeNondecimal-numbers)are converted internally into numbers, and their original formis forgotten. This means, for example, thatarray[17],array[021],andarray[0x11]all refer to the same element!

As with many things in awk, the majority of the timethings work as one would expect them to. But it is useful to have a preciseknowledge of the actual rules since they can sometimes have a subtleeffect on your programs.

8.4 Using Uninitialized Variables as Subscripts

Suppose it's necessary to write a programto print the input data in reverse order. A reasonable attempt to do so (with some testdata) might look like this:

     $ echo 'line 1
     > line 2
     > line 3' | awk '{ l[lines] = $0; ++lines }
     > END {
     >     for (i = lines-1; i >= 0; --i)
     >        print l[i]
     > }'
     -| line 3
     -| line 2

Unfortunately, the very first line of input data did not come out in theoutput!

Upon first glance, we would think that this program should have worked. The variablelinesis uninitialized, and uninitialized variables have the numeric value zero. So,awk should have printed the value of l[0].

The issue here is that subscripts for awk arrays arealwaysstrings. Uninitialized variables, when used as strings, have thevalue"", not zero. Thus, ‘line 1’ ends up stored inl[""]. The following version of the program works correctly:

     { l[lines++] = $0 }
     END {
         for (i = lines - 1; i >= 0; --i)
            print l[i]
     }

Here, the ‘++’ forces lines to be numeric, thus makingthe “old value” numeric zero. This is then converted to"0"as the array subscript.

Even though it is somewhat unusual, the null string("") is a valid array subscript. (d.c.) gawk warns about the use of the null string as a subscriptif--lint is providedon the command line (seeOptions).

8.5 Multidimensional Arrays

A multidimensional array is an array in which an element is identifiedby a sequence of indices instead of a single index. For example, atwo-dimensional array requires two indices. The usual way (in mostlanguages, includingawk) to refer to an element of atwo-dimensional array namedgrid is withgrid[x,y].

Multidimensional arrays are supported inawk throughconcatenation of indices into one string.awk converts the indices into strings(seeConversion) andconcatenates them together, with a separator between them. This createsa single string that describes the values of the separate indices. Thecombined string is used as a single index into an ordinary,one-dimensional array. The separator used is the value of the built-invariable SUBSEP.

For example, suppose we evaluate the expression ‘foo[5,12] = "value"’when the value ofSUBSEP is "@". The numbers 5 and 12 areconverted to strings andconcatenated with an ‘@’ between them, yielding"5@12"; thus,the array element foo["5@12"] is set to "value".

Once the element's value is stored, awk has no record of whetherit was stored with a single index or a sequence of indices. The twoexpressions ‘foo[5,12]’ and ‘foo[5 SUBSEP 12]’ are alwaysequivalent.

The default value of SUBSEP is the string "\034",which contains a nonprinting character that is unlikely to appear in anawk program or in most input data. The usefulness of choosing an unlikely character comes from the factthat index values that contain a string matching SUBSEP can lead tocombined strings that are ambiguous. Suppose that SUBSEP is"@"; then ‘foo["a@b", "c"]’ and ‘foo["a", "b@c"]’ are indistinguishable because both are actuallystored as ‘foo["a@b@c"]’.

To test whether a particular index sequence exists in amultidimensional array, use the same operator (in) that isused for single dimensional arrays. Write the whole sequence of indicesin parentheses, separated by commas, as the left operand:

     (subscript1, subscript2, ...) in array

The following example treats its input as a two-dimensional array offields; it rotates this array 90 degrees clockwise and prints theresult. It assumes that all lines have the same number ofelements:

     {
          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

the program produces the following output:

     4 3 2 1
     5 4 3 2
     6 5 4 3
     1 6 5 4
     2 1 6 5
     3 2 1 6
8.5.1 Scanning Multidimensional Arrays

There is no special for statement for scanning a“multidimensional” array. There cannot be one, because, in truth, thereare no multidimensional arrays or elements—there is only amultidimensionalway of accessing an array.

However, if your program has an array that is always accessed asmultidimensional, you can get the effect of scanning it by combiningthe scanning for statement(see Scanning an Array) with thebuilt-in split() function(see String Functions). It works in the following manner:

     for (combined in array) {
         split(combined, separate, SUBSEP)
         ...
     }

This sets the variable combined toeach concatenated combined index in the array, and splits itinto the individual indices by breaking it apart where the value ofSUBSEP appears. The individual indices then become the elements ofthe array separate.

Thus, if a value is previously stored in array[1, "foo"]; thenan element with index"1\034foo" exists in array. (Recallthat the default value ofSUBSEP is the character with code 034.) Sooner or later, the for statement finds that index and does aniteration with the variablecombined set to "1\034foo". Then the split() function is called as follows:

     split("1\034foo", separate, "\034")

The result is to set separate[1] to "1" andseparate[2] to"foo". Presto! The original sequence ofseparate indices is recovered.


Previous:  Multi-dimensional,Up:  Arrays

8.6 Arrays of Arrays

gawk supports arrays ofarrays. Elements of a subarray are referred to by their own indicesenclosed in square brackets, just like the elements of the main array. For example, the following creates a two-element subarray at index ‘1’of the main array a:

     a[1][1] = 1
     a[1][2] = 2

This simulates a true two-dimensional array. Each subarray element cancontain another subarray as a value, which in turn can hold other arraysas well. In this way, you can create arrays of three or more dimensions. The indices can be anyawk expression, including scalarsseparated by commas (that is, a regularawk simulatedmultidimensional subscript). So the following is valid ingawk:

     a[1][3][1, "name"] = "barney"

Each subarray and the main array can be of different length. In fact, theelements of an array or its subarray do not all have to have the sametype. This means that the main array and any of its subarrays can benon-rectangular, or jagged in structure. One can assign a scalar value tothe index ‘4’ of the main arraya:

     a[4] = "An element in a jagged array"

The terms dimension, row and column aremeaningless when appliedto such an array, but we will use “dimension” henceforth to imply themaximum number of indices needed to refer to an existing element. Thetype of any element that has already been assigned cannot be changedby assigning a value of a different type. You have to first delete thecurrent element, which effectively makesgawk forget aboutthe element at that index:

     delete a[4]
     a[4][5][6][7] = "An element in a four-dimensional array"

This removes the scalar value from index ‘4’ and then inserts asubarray of subarray of subarray containing a scalar. You can alsodelete an entire subarray or subarray of subarrays:

     delete a[4][5]
     a[4][5] = "An element in subarray a[4]"

But recall that you can not delete the main array a and then use itas a scalar.

The built-in functions which take array arguments can also be usedwith subarrays. For example, the following code fragment useslength()(see String Functions)to determine the number of elements in the main arraya andits subarrays:

     print length(a), length(a[1]), length(a[1][3])

This results in the following output for our main array a:

     2, 3, 1

The ‘subscript in array’ expression(see Reference to Elements) works similarly for bothregularawk-stylearrays and arrays of arrays. For example, the tests ‘1 in a’,‘3 in a[1]’, and ‘(1, "name") in a[1][3]’ all evaluate toone (true) for our array a.

The ‘for (item in array)’ statement (seeScanning an Array)can be nested to scan all theelements of an array of arrays if it is rectangular in structure. In orderto print the contents (scalar values) of a two-dimensional array of arrays(i.e., in which each first-level element is itself anarray, not necessarily of the same length)you could use the following code:

     for (i in array)
         for (j in array[i])
             print array[i][j]

The isarray() function (see Type Functions)lets you test if an array element is itself an array:

     for (i in array) {
         if (isarray(array[i]) {
             for (j in array[i]) {
                 print array[i][j]
             }
         }
     }

If the structure of a jagged array of arrays is known in advance,you can often devise workarounds using control statements. For example,the following code prints the elements of our main arraya:

     for (i in a) {
         for (j in a[i]) {
             if (j == 3) {
                 for (k in a[i][j])
                     print a[i][j][k]
             } else
                 print a[i][j]
         }
     }

See Walking Arrays, for a user-defined function that will “walk” anarbitrarily-dimensioned array of arrays.

Recall that a reference to an uninitialized array element yields a valueof "", the null string. This has one important implication when youintend to use a subarray as an argument to a function, as illustrated bythe following example:

     $ gawk 'BEGIN { split("a b c d", b[1]); print b[1][1] }'
     error--> gawk: cmd. line:1: fatal: split: second argument is not an array

The way to work around this is to first force b[1] to be an array bycreating an arbitrary index:

     $ gawk 'BEGIN { b[1][1] = ""; split("a b c d", b[1]); print b[1][1] }'
     -| a


Next:  ,Previous:  Arrays,Up:  Top

9 Functions

This chapter describesawk's built-in functions,which fall into three categories: numeric, string, and I/O.gawk provides additional groups of functionsto work with values that represent time, dobit manipulation, sort arrays, and internationalize and localize programs.

Besides the built-in functions, awk has provisions forwriting new functions that the rest of a program can use. The second half of this chapter describes theseuser-defined functions.


Next:  ,Up:  Functions

9.1 Built-in Functions

Built-in functions are always available foryour awk program to call. This section defines allthe built-infunctions inawk; some of these are mentioned in other sectionsbut are summarized here for your convenience.


Next:  ,Up:  Built-in

9.1.1 Calling Built-in Functions

To call one of awk's built-in functions, write the name ofthe function followedby arguments in parentheses. For example, ‘atan2(y + z, 1)’is a call to the functionatan2() and has two arguments.

Whitespace is ignored between the built-in function name and theopen parenthesis, but nonetheless it is good practice to avoid using whitespacethere. User-defined functions do not permit whitespace in this way, andit is easier to avoid mistakes by following a simpleconvention that always works—no whitespace after a function name.

Each built-in function accepts a certain number of arguments. In some cases, arguments can be omitted. The defaults for omittedarguments vary from function to function and are described under theindividual functions. In someawk implementations, extraarguments given to built-in functions are ignored. However, ingawk,it is a fatal error to give extra arguments to a built-in function.

When a function is called, expressions that create the function's actualparameters are evaluated completely before the call is performed. For example, in the following code fragment:

     i = 4
     j = sqrt(i++)

the variablei is incremented to the value five before sqrt()is called with a value of four for its actual parameter. The order of evaluation of the expressions used for the function'sparameters is undefined. Thus, avoid writing programs thatassume that parameters are evaluated from left to right or fromright to left. For example:

     i = 5
     j = atan2(i++, i *= 2)

If the order of evaluation is left to right, then i first becomes6, and then 12, andatan2() is called with the two arguments 6and 12. But if the order of evaluation is right to left,ifirst becomes 10, then 11, and atan2() is called with thetwo arguments 11 and 10.


Next:  ,Previous:  Calling Built-in,Up:  Built-in

9.1.2 Numeric Functions

The following list describes all ofthe built-in functions that work with numbers. Optional parameters are enclosed in square brackets ([ ]):

atan2( y , x )
Return the arctangent of y / x in radians.
cos( x )
Return the cosine of x, with x in radians.
exp( x )
Return the exponential of x ( e ^ x) or reportan error if x is out of range. The range of values x can havedepends on your machine's floating-point representation.
int( x )
Return the nearest integer to x, located between x and zero andtruncated toward zero.

For example, int(3) is 3, int(3.9) is 3, int(-3.9)is −3, andint(-3) is −3 as well.

log( x )
Return the natural logarithm of x, if x is positive;otherwise, report an error.
rand()
Return a random number. The values of rand() areuniformly distributed between zero and one. The value could be zero but is never one. 38

Often random integers are needed instead. Following is a user-defined functionthat can be used to obtain a random non-negative integer less thann:

          function randint(n) {
               return int(n * rand())
          }

The multiplication produces a random number greater than zero and lessthann. Using int(), this result is made intoan integer between zero andn − 1, inclusive.

The following example uses a similar function to produce random integersbetween one andn. This program prints a new random number foreach input record:

          # 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))
          }

CAUTION: In most awk implementations, including gawk, rand() starts generating numbers from the samestarting number, or seed, each time you run awk. 39 Thus,a program generates the same results each time you run it. The numbers are random within one awk run but predictablefrom run to run. This is convenient for debugging, but if you wanta program to do different things each time it is used, you must changethe seed to a value that is different in each run. To do this,use srand().

sin( x )
Return the sine of x, with x in radians.
sqrt( x )
Return the positive square root of x. gawk prints a warning messageif x is negative. Thus, sqrt(4) is 2.
srand( [ x ] )
Set the starting point, or seed,for generating random numbers to the value x.

Each seed value leads to a particular sequence of randomnumbers.40Thus, if the seed is set to the same value a second time,the same sequence of random numbers is produced again.

CAUTION: Different awk implementations use different random-numbergenerators internally. Don't expect the same awk programto produce the same series of random numbers when executed bydifferent versions of awk.

If the argument x is omitted, as in ‘srand()’, then the currentdate and time of day are used for a seed. This is the way to get randomnumbers that are truly unpredictable.

The return value of srand() is the previous seed. This makes iteasy to keep track of the seeds in case you need to consistently reproducesequences of random numbers.


Next:  ,Previous:  Numeric Functions,Up:  Built-in

9.1.3 String-Manipulation Functions

The functions in this section look at or change the text of one or morestrings.gawk understands locales (see Locales), and does all string processing in terms ofcharacters, notbytes. This distinction is particularly importantto understand for locales where one charactermay be represented by multiple bytes. Thus, for example,length()returns the number of characters in a string, and not the number of bytesused to represent those characters, Similarly,index() works withcharacter indices, and not byte indices.

In the following list, optional parameters are enclosed in square brackets ([ ]).Several functions perform string substitution; the full discussion isprovided in the description of thesub() function, which comestowards the end since the list is presented in alphabetic order. Those functions that are specific togawk are marked with apound sign (‘#’):

asort( source [ , dest [ , how ] ] ) #
Return the number of elements in the array source. gawk sorts the contents of sourceand replaces the indicesof the sorted values of source with sequentialintegers starting with one. If the optional array dest is specified,then source is duplicated into dest. dest is thensorted, leaving the indices of source unchanged. The optional thirdargument how is a string which controls the rule for comparing values,and the sort direction. A single space is required between thecomparison mode, ‘ string’ or ‘ number’, and the direction specification,‘ ascending’ or ‘ descending’. You can omit direction and/or modein which case it will default to ‘ ascending’ and ‘ string’, respectively. An empty string "" is the same as the default "ascending string"for the value of how. If the ‘ source’ array contains subarrays as values,they will come out last(first) in the ‘ dest’ array for ‘ ascending’(‘ descending’)order specification. The value of IGNORECASE affects the sorting. The third argument can also be a user-defined function name in which casethe value returned by the function is used to order the array elementsbefore constructing the result array. See Array Sorting Functions, for more information.

For example, if the contents of a are as follows:

          a["last"] = "de"
          a["first"] = "sac"
          a["middle"] = "cul"

A call to asort():

          asort(a)

results in the following contents of a:

          a[1] = "cul"
          a[2] = "de"
          a[3] = "sac"

In order to reverse the direction of the sorted results in the above example,asort() can be called with three arguments as follows:

          asort(a, a, "descending")

The asort() function is described in more detail inArray Sorting Functions.asort() is a gawk extension; it is not availablein compatibility mode (seeOptions).

asorti( source [ , dest [ , how ] ] ) #
Return the number of elements in the array source. It works similarly to asort(), however, the indicesare sorted, instead of the values. (Here too, IGNORECASE affects the sorting.)

The asorti() function is described in more detail inArray Sorting Functions.asorti() is a gawk extension; it is not availablein compatibility mode (seeOptions).

gensub( regexp , replacement , how [ , target ] ) #
Search the target string target for matches of the regularexpression regexp. If how is a string beginning with‘ g’ or ‘ G’ (short for “global”), then replace all matches of regexp with replacement. Otherwise, how is treated as a number indicatingwhich match of regexp to replace. If no target is supplied,use $0. It returns the modified string as the resultof the function and the original target string is not changed.

gensub() is a general substitution function. It's purpose isto provide more features than the standardsub() and gsub()functions.

gensub() provides an additional feature that is not availablein sub() or gsub(): the ability to specify components of aregexp in the replacement text. This is done by using parentheses inthe regexp to mark the components and then specifying ‘\N’in the replacement text, where N is a digit from 1 to 9. For example:

          $ gawk '
          > BEGIN {
          >      a = "abc def"
          >      b = gensub(/(.+) (.+)/, "\\2 \\1", "g", a)
          >      print b
          > }'
          -| def abc

As with sub(), you must type two backslashes in orderto get one into the string. In the replacement text, the sequence ‘\0’ represents the entirematched text, as does the character ‘&’.

The following example shows how you can use the third argument to controlwhich match of the regexp should be changed:

          $ echo a b c a b c |
          > gawk '{ print gensub(/a/, "AA", 2) }'
          -| a b c AA b c

In this case, $0 is the default target string. gensub() returns the new string as its result, which ispassed directly toprint for printing.

If the how argument is a string that does not begin with ‘g’ or‘G’, or if it is a number that is less than or equal to zero, only onesubstitution is performed. Ifhow is zero, gawk issuesa warning message.

If regexp does not match target, gensub()'s return valueis the original unchanged value oftarget.

gensub() is a gawk extension; it is not availablein compatibility mode (seeOptions).

gsub( regexp , replacement [ , target ] )
Search target for all of the longest, leftmost, nonoverlapping matchingsubstrings it can find and replace them with replacement. The ‘ g’ in gsub() stands for“global,” which means replace everywhere. For example:
          { gsub(/Britain/, "United Kingdom"); print }

replaces all occurrences of the string ‘Britain’ with ‘UnitedKingdom’ for all input records.

The gsub() function returns the number of substitutions made. Ifthe variable to search and alter (target) isomitted, then the entire input record ($0) is used. As insub(), the characters ‘&’ and ‘\’ are special,and the third argument must be assignable.

index( in , find )
Search the string in for the first occurrence of the string find, and return the position in characters where that occurrencebegins in the string in. Consider the following example:
          $ awk 'BEGIN { print index("peanut", "an") }'
          -| 3

If find is not found, index() returns zero. (Remember that string indices inawk start at one.)

length( [ string ] )
Return the number of characters in string. If string is a number, the length of the digit string representingthat number is returned. For example, length("abcde") is five. Bycontrast, length(15 * 35) works out to three. In this example, 15 * 35 =525, and 525 is then converted to the string "525", which hasthree characters.

If no argument is supplied, length() returns the length of $0.

NOTE: In older versions of awk, the length() function couldbe calledwithout any parentheses. Doing so is considered poor practice,although the 2008 POSIX standard explicitly allows it, tosupport historical practice. For programs to be maximally portable,always supply the parentheses.

Iflength() is called with a variable that has not been used,gawk forces the variable to be a scalar. Otherimplementations ofawk leave the variable without a type. (d.c.) Consider:

          $ gawk 'BEGIN { print length(x) ; x[1] = 1 }'
          -| 0
          error--> gawk: fatal: attempt to use scalar `x' as array
          
          $ nawk 'BEGIN { print length(x) ; x[1] = 1 }'
          -| 0

If --lint hasbeen specified on the command line,gawk issues awarning about this.

Withgawk and several other awk implementations, when given anarray argument, thelength() function returns the number of elementsin the array. (c.e.) This is less useful than it might seem at first, as thearray is not guaranteed to be indexed from one to the number of elementsin it. If--lint is provided on the command line(seeOptions),gawk warns that passing an array argument is not portable. If--posix is supplied, using an array argument is a fatal error(seeArrays).

match( string , regexp [ , array ] )
Search string for thelongest, leftmost substring matched by the regular expression, regexp and return the character position, or index,at which that substring begins (one, if it starts at the beginning of string). If no match is found, return zero.

The regexp argument may be either a regexp constant(/.../) or a string constant ("..."). In the latter case, the string is treated as a regexp to be matched. SeeComputed Regexps, for adiscussion of the difference between the two forms, and theimplications for writing your program correctly.

The order of the first two arguments is backwards from most other stringfunctions that work with regular expressions, such assub() andgsub(). It might help to remember thatfor match(), the order is the same as for the ‘~’ operator:‘string ~regexp’.

Thematch() function sets the built-in variable RSTART tothe index. It also sets the built-in variableRLENGTH to thelength in characters of the matched substring. If no match is found,RSTART is set to zero, andRLENGTH to −1.

For example:

          
          {
                 if ($1 == "FIND")
                   regex = $2
                 else {
                   where = match($0, regex)
                   if (where != 0)
                     print "Match of", regex, "found at",
                               where, "in", $0
                 }
          }
          

This program looks for lines that match the regular expression stored inthe variableregex. This regular expression can be changed. If thefirst word on a line is ‘FIND’,regex is changed to be thesecond word on that line. Therefore, if given:

          
          FIND ru+n
          My program runs
          but not very quickly
          FIND Melvin
          JF+KM
          This line is property of Reality Engineering Co.
          Melvin was here.
          

awk prints:

          Match of ru+n found at 12 in My program runs
          Match of Melvin found at 1 in Melvin was here.

Ifarray is present, it is cleared, and then the zeroth elementof array is set to the entire portion ofstringmatched by regexp. If regexp contains parentheses,the integer-indexed elements ofarray are set to contain theportion of string matching the corresponding parenthesizedsubexpression. For example:

          $ echo foooobazbarrrrr |
          > gawk '{ match($0, /(fo+).+(bar*)/, arr)
          >         print arr[1], arr[2] }'
          -| foooo barrrrr

In addition,multidimensional subscripts are available providingthe start index and length of each matched subexpression:

          $ echo foooobazbarrrrr |
          > gawk '{ match($0, /(fo+).+(bar*)/, arr)
          >           print arr[1], arr[2]
          >           print arr[1, "start"], arr[1, "length"]
          >           print arr[2, "start"], arr[2, "length"]
          > }'
          -| foooo barrrrr
          -| 1 5
          -| 9 7

There may not be subscripts for the start and index for every parenthesizedsubexpression, since they may not all have matched text; thus theyshould be tested for with thein operator(see Reference to Elements).

Thearray argument to match() is agawk extension. In compatibility mode(seeOptions),using a third argument is a fatal error.

patsplit( string , array [ , fieldpat [ , seps ] ] ) #
Divide string into pieces defined by fieldpatand store the pieces in array and the separator strings in the seps array. The first piece is stored in array [1], the second piece in array [2], and soforth. The third argument, fieldpat, isa regexp describing the fields in string (just as FPAT isa regexp describing the fields in input records). It may be either a regexp constant or a string. If fieldpat is omitted, the value of FPAT is used. patsplit() returns the number of elements created. seps [ i ] isthe separator stringbetween array [ i ] and array [ i +1]. Any leading separator will be in seps [0].

The patsplit() function splits strings into pieces in amanner similar to the way input lines are split into fields usingFPAT(see Splitting By Content.

Before splitting the string, patsplit() deletes any previously existingelements in the arraysarray and seps.

Thepatsplit() function is agawk extension. In compatibility mode(seeOptions),it is not available.

split( string , array [ , fieldsep [ , seps ] ] )
Divide string into pieces separated by fieldsepand store the pieces in array and the separator strings in the seps array. The first piece is stored in array [1], the second piece in array [2], and soforth. The string value of the third argument, fieldsep, isa regexp describing where to split string (much as FS canbe a regexp describing where to split input records;see Regexp Field Splitting). If fieldsep is omitted, the value of FS is used. split() returns the number of elements created. seps is a gawk extension with seps [ i ]being the separator stringbetween array [ i ] and array [ i +1]. If fieldsep is a singlespace then any leading whitespace goes into seps [0] andany trailingwhitespace goes into seps [ n ] where n is thereturn value of split() (that is, the number of elements in array).

The split() function splits strings into pieces in amanner similar to the way input lines are split into fields. For example:

          split("cul-de-sac", a, "-", seps)

splits the string ‘cul-de-sac’ into three fields using ‘-’ as theseparator. It sets the contents of the arraya as follows:

          a[1] = "cul"
          a[2] = "de"
          a[3] = "sac"

and sets the contents of the array seps as follows:

          seps[1] = "-"
          seps[2] = "-"

The value returned by this call to split() is three.

As with input field-splitting, when the value offieldsep is" ", leading and trailing whitespace is ignored in values assigned tothe elements ofarray but not inseps, and the elementsare separated by runs of whitespace. Also as with input field-splitting, iffieldsep is the null string, eachindividual character in the string is split into its own array element. (c.e.)

Note, however, that RS has no effect on the way split()works. Even though ‘RS = ""’ causes newline to also be an inputfield separator, this does not affect howsplit() splits strings.

Modern implementations ofawk, including gawk, allowthe third argument to be a regexp constant (/abc/) as well as astring. (d.c.) The POSIX standard allows this as well. SeeComputed Regexps, for adiscussion of the difference between using a string constant or a regexp constant,and the implications for writing your program correctly.

Before splitting the string, split() deletes any previously existingelements in the arraysarray and seps.

If string is null, the array has no elements. (So this is a portableway to delete an entire array with one statement. SeeDelete.)

If string does not match fieldsep at all (but is not null),array has one element only. The value of that element is the originalstring.

sprintf( format , expression1 , ...)
Return (without printing) the string that printf wouldhave printed out with the same arguments(see Printf). For example:
          pival = sprintf("pi = %.2f (approx.)", 22/7)

assigns the string ‘pi = 3.14 (approx.)’ to the variablepival.


strtonum( str ) #
Examine str and return its numeric value. If strbegins with a leading ‘ 0’, strtonum() assumes that stris an octal number. If str begins with a leading ‘ 0x’ or‘ 0X’, strtonum() assumes that str is a hexadecimal number. For example:
          $ echo 0x11 |
          > gawk '{ printf "%d\n", strtonum($1) }'
          -| 17

Using the strtonum() function is not the same as adding zeroto a string value; the automatic coercion of strings to numbersworks only for decimal data, not for octal or hexadecimal.41

Note also that strtonum() uses the current locale's decimal pointfor recognizing numbers (seeLocales).

strtonum() is agawk extension; it is not availablein compatibility mode (seeOptions).

sub( regexp , replacement [ , target ] )
Search target, which is treated as a string, for theleftmost, longest substring matched by the regular expression regexp. Modify the entire stringby replacing the matched text with replacement. The modified string becomes the new value of target. Return the number of substitutions made (zero or one).

The regexp argument may be either a regexp constant(/.../) or a string constant ("..."). In the latter case, the string is treated as a regexp to be matched. SeeComputed Regexps, for adiscussion of the difference between the two forms, and theimplications for writing your program correctly.

This function is peculiar because target is not simplyused to compute a value, and not just any expression will do—itmust be a variable, field, or array element so thatsub() canstore a modified value there. If this argument is omitted, then thedefault is to use and alter$0.42For example:

          str = "water, water, everywhere"
          sub(/at/, "ith", str)

sets str to ‘wither, water, everywhere’, by replacing theleftmost longest occurrence of ‘at’ with ‘ith’.

If the special character ‘&’ appears inreplacement, itstands for the precise substring that was matched by regexp. (Ifthe regexp can match more than one string, then this precise substringmay vary.) For example:

          { sub(/candidate/, "& and his wife"); print }

changes the first occurrence of ‘candidate’ to ‘candidateand his wife’ on each input line. Here is another example:

          $ awk 'BEGIN {
          >         str = "daabaaa"
          >         sub(/a+/, "C&C", str)
          >         print str
          > }'
          -| dCaaCbaaa

This shows how ‘&’ can represent a nonconstant string and alsoillustrates the “leftmost, longest” rule in regexp matching(seeLeftmost Longest).

The effect of this special character (‘&’) can be turned off by putting abackslash before it in the string. As usual, to insert one backslash inthe string, you must write two backslashes. Therefore, write ‘\\&’in a string constant to include a literal ‘&’ in the replacement. For example, the following shows how to replace the first ‘|’ on each line withan ‘&’:

          { sub(/\|/, "\\&"); print }

As mentioned, the third argument tosub() mustbe a variable, field or array element. Some versions of awk allow the third argument tobe an expression that is not an lvalue. In such a case,sub()still searches for the pattern and returns zero or one, but the result ofthe substitution (if any) is thrown away because there is no placeto put it. Such versions ofawk accept expressionslike the following:

          sub(/USA/, "United States", "the USA and Canada")

For historical compatibility,gawk accepts such erroneous code. However, using any other nonchangeableobject as the third parameter causes a fatal error and your programwill not run.

Finally, if the regexp is not a regexp constant, it is converted into astring, and then the value of that string is treated as the regexp to match.

substr( string , start [ , length ] )
Return a length-character-long substring of string,starting at character number start. The first character of astring is character number one. 43For example, substr("washington", 5, 3) returns "ing".

If length is not present, substr() returns the whole suffix ofstring that begins at character numberstart. For example,substr("washington", 5) returns "ington". The wholesuffix is also returnedif length is greater than the number of characters remainingin the string, counting from characterstart.

If start is less than one, substr() treats it asif it was one. (POSIX doesn't specify what to do in this case:Brian Kernighan'sawk acts this way, and therefore gawkdoes too.) If start is greater than the number of charactersin the string,substr() returns the null string. Similarly, if length is present but less than or equal to zero,the null string is returned.

The string returned bysubstr() cannot beassigned. Thus, it is a mistake to attempt to change a portion ofa string, as shown in the following example:

          string = "abcdef"
          # try to get "abCDEf", won't work
          substr(string, 3, 3) = "CDE"

It is also a mistake to use substr() as the third argumentofsub() or gsub():

          gsub(/xyz/, "pdq", substr($0, 5, 20))  # WRONG

(Some commercial versions ofawk treatsubstr() as assignable, but doing so is not portable.)

If you need to replace bits and pieces of a string, combine substr()with string concatenation, in the following manner:

          string = "abcdef"
          ...
          string = substr(string, 1, 2) "CDE" substr(string, 6)


tolower( string )
Return a copy of string, with each uppercase characterin the string replaced with its corresponding lowercase character. Nonalphabetic characters are left unchanged. For example, tolower("MiXeD cAsE 123") returns "mixed case 123".
toupper( string )
Return a copy of string, with each lowercase characterin the string replaced with its corresponding uppercase character. Nonalphabetic characters are left unchanged. For example, toupper("MiXeD cAsE 123") returns "MIXED CASE 123".

9.1.3.1 More About ‘\’ and ‘&’ withsub(), gsub(), and gensub()

When using sub(), gsub(), or gensub(), and trying to get literalbackslashes and ampersands into the replacement text, you need to rememberthat there are several levels ofescape processing going on.

First, there is the lexical level, which is when awk readsyour programand builds an internal copy of it that can be executed. Then there is the runtime level, which is whenawk actually scans thereplacement string to determine what to generate.

At both levels, awk looks for a defined set of characters thatcan come after a backslash. At the lexical level, it looks for theescape sequences listed inEscape Sequences. Thus, for every ‘\’ thatawk processes at the runtimelevel, you must type two backslashes at the lexical level. When a character that is not valid for an escape sequence follows the‘\’, Brian Kernighan'sawk and gawk both simply remove the initial‘\’ and put the next character into the string. Thus, forexample,"a\qb" is treated as "aqb".

At the runtime level, the various functions handle sequences of‘\’ and ‘&’ differently. The situation is (sadly) somewhat complex. Historically, thesub() and gsub() functions treated the twocharacter sequence ‘\&’ specially; this sequence was replaced inthe generated text with a single ‘&’. Any other ‘\’ withinthe replacement string that did not precede an ‘&’ was passedthrough unchanged. This is illustrated intable-sub-escapes.

      You type         sub() sees          sub() generates
      ———–         ————–          ———————
          \&              &            the matched text
         \\&             \&            a literal ‘&\\\&             \&            a literal ‘&\\\\&            \\&            a literal ‘\&\\\\\&            \\&            a literal ‘\&\\\\\\&           \\\&            a literal ‘\\&\\q             \q            a literal ‘\q

Table 9.1: Historical Escape Sequence Processing forsub() and gsub()

This table shows both the lexical-level processing, wherean odd number of backslashes becomes an even number at the runtime level,as well as the runtime processing done bysub(). (For the sake of simplicity, the rest of the following tables only show thecase of even numbers of backslashes entered at the lexical level.)

The problem with the historical approach is that there is no way to geta literal ‘\’ followed by the matched text.

The POSIX rules state that ‘\&’ in the replacement string producesa literal ‘&’, ‘\\’ produces a literal ‘\’, and ‘\’ followedby anything else is not special; the ‘\’ is placed straight into the output. These rules are presented intable-posix-sub.

      You type         sub() sees         sub() generates
      ———–         ————–         ———————
     \\\\\\&           \\\&            a literal ‘\&\\\\&            \\&            a literal ‘\’, followed by the matched text
         \\&             \&            a literal ‘&\\q             \q            a literal ‘\q\\\\             \\            \

Table 9.2: POSIX rules for sub() andgsub()

gawk follows the POSIX rules.

The rules for gensub() are considerably simpler. At the runtimelevel, whenevergawk sees a ‘\’, if the following characteris a digit, then the text that matched the corresponding parenthesizedsubexpression is placed in the generated output. Otherwise,no matter what character follows the ‘\’, itappears in the generated text and the ‘\’ does not,as shown intable-gensub-escapes.

       You type          gensub() sees         gensub() generates
       ———–          ——————         ————————–
           &                    &            the matched text
         \\&                   \&            a literal ‘&\\\\                   \\            a literal ‘\\\\\&                  \\&            a literal ‘\’, then the matched text
     \\\\\\&                 \\\&            a literal ‘\&\\q                   \q            a literal ‘q

Table 9.3: Escape Sequence Processing for gensub()

Because of the complexity of the lexical and runtime level processingand the special cases forsub() and gsub(),we recommend the use of gawk andgensub() when you haveto do substitutions.

Advanced Notes: Matching the Null String

Inawk, the ‘*’ operator can match the null string. This is particularly important for thesub(), gsub(),and gensub() functions. For example:

     $ echo abc | awk '{ gsub(/m*/, "X"); print }'
     -| XaXbXcX

Although this makes a certain amount of sense, it can be surprising.


Next:  ,Previous:  String Functions,Up:  Built-in

9.1.4 Input/Output Functions

The following functions relate to input/output (I/O). Optional parameters are enclosed in square brackets ([ ]):

close( filename [ , how ] )
Close the file filename for input or output. Alternatively, theargument may be a shell command that was used for creating a coprocess, orfor redirecting to or from a pipe; then the coprocess or pipe is closed. See Close Files And Pipes,for more information.

When closing a coprocess, it is occasionally useful to first closeone end of the two-way pipe and then to close the other. This is doneby providing a second argument toclose(). This second argumentshould be one of the two string values "to" or "from",indicating which end of the pipe to close. Case in the string doesnot matter. SeeTwo-way I/O,which discusses this feature in more detail and gives an example.

fflush( [ filename ] )
Flush any buffered output associated with filename, which is either afile opened for writing or a shell command for redirecting output toa pipe or coprocess. (c.e.).

Many utility programsbuffer their output; i.e., they save informationto write to a disk file or the screen in memory until there is enoughfor it to be worthwhile to send the data to the output device. This is often more efficient than writingevery little bit of information as soon as it is ready. However, sometimesit is necessary to force a program to flush its buffers; that is,write the information to its destination, even if a buffer is not full. This is the purpose of thefflush() function—gawk alsobuffers its output and thefflush() function forcesgawk to flush its buffers.

fflush() was added to Brian Kernighan'sversion of awk in 1994; it is not part of the POSIX standard and isnot available if--posix has been specified on thecommand line (seeOptions).

gawk extends thefflush() function in two ways. The firstis to allow no argument at all. In this case, the buffer for thestandard output is flushed. The second is to allow the null string("") as the argument. In this case, the buffers forall open output files and pipes are flushed. Brian Kernighan's awk also supports these extensions.

fflush() returns zero if the buffer is successfully flushed;otherwise, it returns −1. In the case where all buffers are flushed, the return value is zeroonly if all buffers were flushed successfully. Otherwise, it is−1, and gawk warns about the problemfilename.

gawk also issues a warning message if you attempt to flusha file or pipe that was opened for reading (such as withgetline),or if filename is not an open file, pipe, or coprocess. In such a case,fflush() returns −1, as well.

system( command )
Execute the operating-systemcommand command and then return to the awk program. Return command's exit status.

For example, if the following fragment of code is put in your awkprogram:

          END {
               system("date | mail -s 'awk run done' root")
          }

the system administrator is sent mail when the awk programfinishes processing input and begins its end-of-input processing.

Note that redirecting print or printf into a pipe is oftenenough to accomplish your task. If you need to run many commands, itis more efficient to simply print them down a pipeline to the shell:

          while (more stuff to do)
              print command | "/bin/sh"
          close("/bin/sh")

However, if yourawkprogram is interactive, system() is useful for running largeself-contained programs, such as a shell or an editor. Some operating systems cannot implement thesystem() function. system() causes a fatal error if it is not supported.

NOTE: When --sandbox is specified, the system() function is disabled(see Options).

Advanced Notes: Interactive Versus Noninteractive Buffering

As a side point, buffering issues can be even more confusing, dependingupon whether your program isinteractive, i.e., communicatingwith a user sitting at a keyboard.44

Interactive programs generally line buffer their output; i.e., theywrite out every line. Noninteractive programs wait until they havea full buffer, which may be many lines of output. Here is an example of the difference:

     $ awk '{ print $1 + $2 }'
     1 1
     -| 2
     2 3
     -| 5
     Ctrl-d

Each line of output is printed immediately. Compare that behaviorwith this example:

     $ awk '{ print $1 + $2 }' | cat
     1 1
     2 3
     Ctrl-d
     -| 2
     -| 5

Here, no output is printed until after the Ctrl-d is typed, becauseit is all buffered and sent down the pipe tocat in one shot.

Advanced Notes: Controlling Output Buffering with system()

Thefflush() function provides explicit control over output buffering forindividual files and pipes. However, its use is not portable to many otherawk implementations. An alternative method to flush outputbuffers is to call system() with a null string as its argument:

     system("")   # flush output

gawk treats this use of thesystem() function as a specialcase and is smart enough not to run a shell (or other commandinterpreter) with the empty command. Therefore, withgawk, thisidiom is not only useful, it is also efficient. While this method should workwith otherawk implementations, it does not necessarily avoidstarting an unnecessary shell. (Other implementations may onlyflush the buffer associated with the standard output and not necessarilyall buffered output.)

If you think about what a programmer expects, it makes sense thatsystem() should flush any pending output. The following program:

     BEGIN {
          print "first print"
          system("echo system echo")
          print "second print"
     }

must print:

     first print
     system echo
     second print

and not:

     system echo
     first print
     second print

If awk did not flush its buffers before callingsystem(),you would see the latter (undesirable) output.


Next:  ,Previous:  I/O Functions,Up:  Built-in

9.1.5 Time Functions

awk programs are commonly used to process log filescontaining timestamp information, indicating when aparticular log record was written. Many programs log their timestampin the form returned by thetime() system call, which is thenumber of seconds since a particular epoch. On POSIX-compliant systems,it is the number of seconds since1970-01-01 00:00:00 UTC, not counting leap seconds.45All known POSIX-compliant systems support timestamps from 0 through2^31 - 1, which is sufficient to represent times through2038-01-19 03:14:07 UTC. Many systems support a wider range of timestamps,including negative timestamps that represent times before theepoch.

In order to make it easier to process such log files and to produceuseful reports,gawk provides the following functions forworking with timestamps. They aregawk extensions; they arenot specified in the POSIX standard, nor are they in any other knownversion ofawk.46Optional parameters are enclosed in square brackets ([ ]):

mktime( datespec )
Turn datespec into a timestamp in the same formas is returned by systime(). It is similar to the function of thesame name in ISO C. The argument, datespec, is a string of the form " YYYY   MM   DD   HH   MM   SS  [ DST ]". The string consists of six or seven numbers representing, respectively,the full year including century, the month from 1 to 12, the day of the monthfrom 1 to 31, the hour of the day from 0 to 23, the minute from 0 to59, the second from 0 to 60, 47and an optional daylight-savings flag.

The values of these numbers need not be within the ranges specified;for example, an hour of −1 means 1 hour before midnight. The origin-zero Gregorian calendar is assumed, with year 0 precedingyear 1 and year −1 preceding year 0. The time is assumed to be in the local timezone. If the daylight-savings flag is positive, the time is assumed to bedaylight savings time; if zero, the time is assumed to be standardtime; and if negative (the default),mktime() attempts to determinewhether daylight savings time is in effect for the specified time.

If datespec does not contain enough elements or if the resulting timeis out of range,mktime() returns −1.


strftime( [ format [ , timestamp [ , utc-flag ]]] )
Format the time specified by timestampbased on the contents of the format string and return the result. It is similar to the function of the same name in ISO C. If utc-flag is present and is either nonzero or non-null, the valueis formatted as UTC (Coordinated Universal Time, formerly GMT or GreenwichMean Time). Otherwise, the value is formatted for the local time zone. The timestamp is in the same format as the value returned by the systime() function. If no timestamp argument is supplied, gawk uses the current time of day as the timestamp. If no format argument is supplied, strftime() usesthe value of PROCINFO["strftime"] as the format string(see Built-in Variables). The default string value is "%a %b %e %H:%M:%S %Z %Y". This format string producesoutput that is equivalent to that of the date utility. You can assign a new value to PROCINFO["strftime"] tochange the default format.
systime()
Return the current time as the number of seconds sincethe system epoch. On POSIX systems, this is the number of secondssince 1970-01-01 00:00:00 UTC, not counting leap seconds. It may be a different number on other systems.

The systime() function allows you to compare a timestamp from alog file with the current time of day. In particular, it is easy todetermine how long ago a particular record was logged. It also allowsyou to produce log records using the “seconds since the epoch” format.

Themktime() function allows you to convert a textual representationof a date and time into a timestamp. This makes it easy to do before/aftercomparisons of dates and times, particularly when dealing with date andtime data coming from an external source, such as a log file.

The strftime() function allows you to easily turn a timestampinto human-readable information. It is similar in nature to thesprintf()function(see String Functions),in that it copies nonformat specification characters verbatim to thereturned string, while substituting date and time values for formatspecifications in theformat string.

strftime() is guaranteed by the 1999 ISO Cstandard48to support the following date format specifications:

%a
The locale's abbreviated weekday name.
%A
The locale's full weekday name.
%b
The locale's abbreviated month name.
%B
The locale's full month name.
%c
The locale's “appropriate” date and time representation. (This is ‘ %A %B %d %T %Y’ in the "C" locale.)
%C
The century part of the current year. This is the year divided by 100 and truncated to the nextlower integer.
%d
The day of the month as a decimal number (01–31).
%D
Equivalent to specifying ‘ %m/%d/%y’.
%e
The day of the month, padded with a space if it is only one digit.
%F
Equivalent to specifying ‘ %Y-%m-%d’. This is the ISO 8601 date format.
%g
The year modulo 100 of the ISO 8601 week number, as a decimal number (00–99). For example, January 1, 1993 is in week 53 of 1992. Thus, the yearof its ISO 8601 week number is 1992, even though its year is 1993. Similarly, December 31, 1973 is in week 1 of 1974. Thus, the yearof its ISO week number is 1974, even though its year is 1973.
%G
The full year of the ISO week number, as a decimal number.
%h
Equivalent to ‘ %b’.
%H
The hour (24-hour clock) as a decimal number (00–23).
%I
The hour (12-hour clock) as a decimal number (01–12).
%j
The day of the year as a decimal number (001–366).
%m
The month as a decimal number (01–12).
%M
The minute as a decimal number (00–59).
%n
A newline character (ASCII LF).
%p
The locale's equivalent of the AM/PM designations associatedwith a 12-hour clock.
%r
The locale's 12-hour clock time. (This is ‘ %I:%M:%S %p’ in the "C" locale.)
%R
Equivalent to specifying ‘ %H:%M’.
%S
The second as a decimal number (00–60).
%t
A TAB character.
%T
Equivalent to specifying ‘ %H:%M:%S’.
%u
The weekday as a decimal number (1–7). Monday is day one.
%U
The week number of the year (the first Sunday as the first day of week one)as a decimal number (00–53).
%V
The week number of the year (the first Monday as the firstday of week one) as a decimal number (01–53). The method for determining the week number is as specified by ISO 8601. (To wit: if the week containing January 1 has four or more days in thenew year, then it is week one; otherwise it is week 53 of the previous yearand the next week is week one.)
%w
The weekday as a decimal number (0–6). Sunday is day zero.
%W
The week number of the year (the first Monday as the first day of week one)as a decimal number (00–53).
%x
The locale's “appropriate” date representation. (This is ‘ %A %B %d %Y’ in the "C" locale.)
%X
The locale's “appropriate” time representation. (This is ‘ %T’ in the "C" locale.)
%y
The year modulo 100 as a decimal number (00–99).
%Y
The full year as a decimal number (e.g., 2011).
%z
The timezone offset in a +HHMM format (e.g., the format necessary toproduce RFC 822/RFC 1036 date headers).
%Z
The time zone name or abbreviation; no characters ifno time zone is determinable.
%Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy
“Alternate representations” for the specificationsthat use only the second letter (‘ %c’, ‘ %C’,and so on). 49(These facilitate compliance with the POSIX date utility.)
%%
A literal ‘ %’.

If a conversion specifier is not one of the above, the behavior isundefined.50

Informally, a locale is the geographic place in which a programis meant to run. For example, a common way to abbreviate the dateSeptember 4, 2012 in the United States is “9/4/12.”In many countries in Europe, however, it is abbreviated “4.9.12.”Thus, the ‘%x’ specification in a "US" locale might produce‘9/4/12’, while in a"EUROPE" locale, it might produce‘4.9.12’. The ISO C standard defines a default"C"locale, which is an environment that is typical of what many C programmersare used to.

For systems that are not yet fully standards-compliant,gawk supplies a copy ofstrftime() from the GNU C Library. It supports all of the just-listed format specifications. If that version isused to compilegawk (see Installation),then the following additional format specifications are available:

%k
The hour (24-hour clock) as a decimal number (0–23). Single-digit numbers are padded with a space.
%l
The hour (12-hour clock) as a decimal number (1–12). Single-digit numbers are padded with a space.
%s
The time as a decimal timestamp in seconds since the epoch.

Additionally, the alternate representations are recognized but theirnormal representations are used.

The following example is anawk implementation of the POSIXdate utility. Normally, thedate utility prints thecurrent date and time of day in a well-known format. However, if youprovide an argument to it that begins with a ‘+’,datecopies nonformat specifier characters to the standard output andinterprets the current time according to the format specifiers inthe string. For example:

     $ date '+Today is %A, %B %d, %Y.'
     -| Today is Wednesday, March 30, 2011.

Here is the gawk version of the date utility. It has a shell “wrapper” to handle the-u option,which requires that date run as if the time zoneis set to UTC:

     #! /bin/sh
     #
     # date --- approximate the POSIX 'date' command
     
     case $1 in
     -u)  TZ=UTC0     # use UTC
          export TZ
          shift ;;
     esac
     
     gawk 'BEGIN  {
         format = "%a %b %e %H:%M:%S %Z %Y"
         exitval = 0
     
         if (ARGC > 2)
             exitval = 1
         else if (ARGC == 2) {
             format = ARGV[1]
             if (format ~ /^\+/)
                 format = substr(format, 2)   # remove leading +
         }
         print strftime(format)
         exit exitval
     }' "$@"


Next:  ,Previous:  Time Functions,Up:  Built-in

9.1.6 Bit-Manipulation Functions

I can explain it for you, but I can't understand it for you.
Anonymous

Many languages provide the ability to perform bitwise operationson two integer numbers. In other words, the operation is performed oneach successive pair of bits in the operands. Three common operations are bitwise AND, OR, and XOR. The operations are described in table-bitwise-ops.

                     Bit Operator
               |  AND  |   OR  |  XOR
               |—+—+—+—+—+—
     Operands  | 0 | 1 | 0 | 1 | 0 | 1
     ————–+—+—+—+—+—+—
         0     | 0   0 | 0   1 | 0   1
         1     | 0   1 | 1   1 | 1   0

Table 9.4: Bitwise Operations

As you can see, the result of an AND operation is 1 only whenbothbits are 1. The result of an OR operation is 1 if either bit is 1. The result of an XOR operation is 1 if either bit is 1,but not both. The next operation is thecomplement; the complement of 1 is 0 andthe complement of 0 is 1. Thus, this operation “flips” all the bitsof a given value.

Finally, two other common operations are to shift the bits left or right. For example, if you have a bit string ‘10111001’ and you shift itright by three bits, you end up with ‘00010111’.51If you start overagain with ‘10111001’ and shift it left by three bits, you end upwith ‘11001000’.gawk provides built-in functions that implement thebitwise operations just described. They are:

and( v1 , v2 )
Return the bitwise AND of the values provided by v1 and v2.


compl( val )
Return the bitwise complement of val.


lshift( val , count )
Return the value of val, shifted left by count bits.


or( v1 , v2 )
Return the bitwise OR of the values provided by v1 and v2.


rshift( val , count )
Return the value of val, shifted right by count bits.


xor( v1 , v2 )
Return the bitwise XOR of the values provided by v1 and v2.

For all of these functions, first the double precision floating-point value isconverted to the widest C unsigned integer type, then the bitwise operation isperformed. If the result cannot be represented exactly as a Cdouble,leading nonzero bits are removed one by one until it can be representedexactly. The result is then converted back into a Cdouble. (Ifyou don't understand this paragraph, don't worry about it.)

Here is a user-defined function (see User-defined)that illustrates the use of these functions:

     
     # bits2str --- turn a byte into readable 1's and 0's
     
     function bits2str(bits,        data, mask)
     {
         if (bits == 0)
             return "0"
     
         mask = 1
         for (; bits != 0; bits = rshift(bits, 1))
             data = (and(bits, mask) ? "1" : "0") data
     
         while ((length(data) % 8) != 0)
             data = "0" data
     
         return data
     }
     
     
     
     
     BEGIN {
         printf "123 = %s\n", bits2str(123)
         printf "0123 = %s\n", bits2str(0123)
         printf "0x99 = %s\n", bits2str(0x99)
         comp = compl(0x99)
         printf "compl(0x99) = %#x = %s\n", comp, bits2str(comp)
         shift = lshift(0x99, 2)
         printf "lshift(0x99, 2) = %#x = %s\n", shift, bits2str(shift)
         shift = rshift(0x99, 2)
         printf "rshift(0x99, 2) = %#x = %s\n", shift, bits2str(shift)
     }
     

This program produces the following output when run:

     $ gawk -f testbits.awk
     -| 123 = 01111011
     -| 0123 = 01010011
     -| 0x99 = 10011001
     -| compl(0x99) = 0xffffff66 = 11111111111111111111111101100110
     -| lshift(0x99, 2) = 0x264 = 0000001001100100
     -| rshift(0x99, 2) = 0x26 = 00100110

Thebits2str() function turns a binary number into a string. The number 1 represents a binary value where the rightmost bitis set to 1. Using this mask,the function repeatedly checks the rightmost bit. ANDing the mask with the value indicates whether therightmost bit is 1 or not. If so, a"1" is concatenated onto the frontof the string. Otherwise, a "0" is added. The value is then shifted right by one bit and the loop continuesuntil there are no more 1 bits.

If the initial value is zero it returns a simple "0". Otherwise, at the end, it pads the value with zeros to represent multiplesof 8-bit quantities. This is typical in modern computers.

The main code in the BEGIN rule shows the difference between thedecimal and octal values for the same numbers(seeNondecimal-numbers),and then demonstrates theresults of thecompl(), lshift(), and rshift() functions.


Next:  ,Previous:  Bitwise Functions,Up:  Built-in

9.1.7 Getting Type Information

gawk provides a single function that lets you distinguishan array from a scalar variable. This is necessary for writing codethat traverses every element of a true multidimensional array(seeArrays of Arrays).

isarray( x )
Return a true value if x is an array. Otherwise return false.


Previous:  Type Functions,Up:  Built-in

9.1.8 String-Translation Functions

gawk provides facilities for internationalizing awk programs. These include the functions described in the following list. The descriptions here are purposely brief. SeeInternationalization,for the full story. Optional parameters are enclosed in square brackets ([ ]):

bindtextdomain( directory [ , domain ] )
Set the directory in which gawk will look for message translation files, in case theywill not or cannot be placed in the “standard” locations(e.g., during testing). It returns the directory in which domain is “bound.”

The default domain is the value of TEXTDOMAIN. If directory is the null string (""), thenbindtextdomain() returns the current binding for thegivendomain.


dcgettext( string [ , domain [ , category ]] )
Return the translation of string intext domain domain for locale category category. The default value for domain is the current value of TEXTDOMAIN. The default value for category is "LC_MESSAGES".


dcngettext( string1 , string2 , number [ , domain [ , category ]] )
Return the plural form used for number of thetranslation of string1 and string2 in text domain domain for locale category category. string1 is theEnglish singular variant of a message, and string2 the English pluralvariant of the same message. The default value for domain is the current value of TEXTDOMAIN. The default value for category is "LC_MESSAGES".


Next:  ,Previous:  Built-in,Up:  Functions

9.2 User-Defined Functions

Complicatedawk programs can often be simplified by definingyour own functions. User-defined functions can be called just likebuilt-in ones (seeFunction Calls), but it is up to you to definethem, i.e., to tellawk what they should do.

9.2.1 Function Definition Syntax

Definitions of functions can appear anywhere between the rules of anawk program. Thus, the general form of anawk program isextended to include sequences of rulesand user-defined functiondefinitions. There is no need to put the definition of a functionbefore all uses of the function. This is becauseawk reads theentire program before starting to execute any of it.

The definition of a function named name looks like this:

     function name([parameter-list])
     {
          body-of-function
     }

Here,name is the name of the function to define. A valid functionname is like a valid variable name: a sequence of letters, digits, andunderscores that doesn't start with a digit. Within a singleawk program, any particular name can only beused as a variable, array, or function.

parameter-list is an optional list of the function's arguments and localvariable names, separated by commas. When the function is called,the argument names are used to hold the argument values given inthe call. The local variables are initialized to the empty string. A function cannot have two parameters with the same name, nor may ithave a parameter with the same name as the function itself.

In addition, according to the POSIX standard, function parameters cannot have the samename as one of the special built-in variables(seeBuilt-in Variables. Not all versions of awkenforce this restriction.

The body-of-function consists of awk statements. It is themost important part of the definition, because it says what the functionshould actuallydo. The argument names exist to give the body away to talk about the arguments; local variables exist to give the bodyplaces to keep temporary values.

Argument names are not distinguished syntactically from local variablenames. Instead, the number of arguments supplied when the function iscalled determines how many argument variables there are. Thus, if threeargument values are given, the first three names in parameter-listare arguments and the rest are local variables.

It follows that if the number of arguments is not the same in all callsto the function, some of the names inparameter-list may bearguments on some occasions and local variables on others. Anotherway to think of this is that omitted arguments default to thenull string.

Usually when you write a function, you know how many names you intend touse for arguments and how many you intend to use as local variables. It isconventional to place some extra space between the arguments andthe local variables, in order to document how your function is supposed to be used.

During execution of the function body, the arguments and local variablevalues hide, orshadow, any variables of the same names used in therest of the program. The shadowed variables are not accessible in thefunction definition, because there is no way to name them while theirnames have been taken away for the local variables. All other variablesused in the awk program can be referenced or set normally in thefunction's body.

The arguments and local variables last only as long as the function bodyis executing. Once the body finishes, you can once again access thevariables that were shadowed while the function was running.

The function body can contain expressions that call functions. Theycan even call this function, either directly or by way of anotherfunction. When this happens, we say the function is recursive. The act of a function calling itself is calledrecursion.

All the built-in functions return a value to their caller. User-defined functions can do also, using thereturn statement,which is described in detail in Return Statement. Many of the subsequent examples in this section usethe return statement.

In many awk implementations, including gawk,the keyword function may beabbreviatedfunc. (c.e.) However, POSIX only specifies the use ofthe keyword function. This actually has some practical implications. If gawk is in POSIX-compatibility mode(seeOptions), then the followingstatement does not define a function:

     func foo() { a = sqrt($1) ; print a }

Instead it defines a rule that, for each record, concatenates the valueof the variable ‘func’ with the return value of the function ‘foo’. If the resulting string is non-null, the action is executed. This is probably not what is desired. (awk accepts this input assyntactically valid, because functions may be used before they are definedinawk programs.52)

To ensure that yourawk programs are portable, always use thekeywordfunction when defining a function.


Next:  ,Previous:  Definition Syntax,Up:  User-defined

9.2.2 Function Definition Examples

Here is an example of a user-defined function, called myprint(), thattakes a number and prints it in a specific format:

     function myprint(num)
     {
          printf "%6.3g\n", num
     }

To illustrate, here is an awk rule that uses ourmyprintfunction:

     $3 > 0     { myprint($3) }

This program prints, in our special format, all the third fields thatcontain a positive number in our input. Therefore, when given the following input:

      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, prints:

        5.6
       21.2

This function deletes all the elements in an array:

     function delarray(a,    i)
     {
         for (i in a)
            delete a[i]
     }

When working with arrays, it is often necessary to delete all the elementsin an array and start over with a new list of elements(seeDelete). Instead of havingto repeat this loop everywhere that you need to clear outan array, your program can just calldelarray. (This guarantees portability. The use of ‘deletearray’ to deletethe contents of an entire array is a nonstandard extension.)

The following is an example of a recursive function. It takes a stringas an input parameter and returns the string in backwards order. Recursive functions must always have a test that stops the recursion. In this case, the recursion terminates when the starting positionis zero, i.e., when there are no more characters left in the string.

     function rev(str, start)
     {
         if (start == 0)
             return ""
     
         return (substr(str, start, 1) rev(str, start - 1))
     }

If this function is in a file named rev.awk, it can be testedthis way:

     $ echo "Don't Panic!" |
     > gawk --source '{ print rev($0, length($0)) }' -f rev.awk
     -| !cinaP t'noD

The C ctime() function takes a timestamp and returns it in a string,formatted in a well-known fashion. The following example uses the built-instrftime() function(see Time Functions)to create anawk version of ctime():

     
     # ctime.awk
     #
     # awk version of C ctime(3) function
     
     function ctime(ts,    format)
     {
         format = "%a %b %e %H:%M:%S %Z %Y"
         if (ts == 0)
             ts = systime()       # use current time as default
         return strftime(format, ts)
     }
     


Next:  ,Previous:  Function Example,Up:  User-defined

9.2.3 Calling User-Defined Functions

This section describes how to call a user-defined function.

9.2.3.1 Writing A Function Call

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 bythe function.

A function call consists of the function name followed by the argumentsin parentheses.awk expressions are what you write in thecall for the arguments. Each time the call is executed, theseexpressions are evaluated, and the values become the actual arguments. Forexample, here is a call tofoo() with three arguments (the firstbeing a string concatenation):

     foo(x y, "lose", 4 * z)
CAUTION: Whitespace characters (spaces and TABs) are not allowedbetween the function name and the open-parenthesis of the argument list. If you write whitespace by mistake, awk might think that you meanto concatenate a variable with an expression in parentheses. However, itnotices that you used a function name and not a variable name, and reportsan error.
9.2.3.2 Controlling Variable Scope

There is no way to make a variable local to a{ ... } block inawk, but you can make a variable local to a function. It isgood practice to do so whenever a variable is needed only in thatfunction.

To make a variable local to a function, simply declare the variable asan argument after the actual function arguments(seeDefinition Syntax). Look at the following example where variablei is a global variable used by both functionsfoo() andbar():

     function bar()
     {
         for (i = 0; i < 3; i++)
             print "bar's i=" i
     }
     
     function foo(j)
     {
         i = j + 1
         print "foo's i=" i
         bar()
         print "foo's i=" i
     }
     
     BEGIN {
           i = 10
           print "top's i=" i
           foo(0)
           print "top's i=" i
     }

Running this script produces the following, because the i infunctionsfoo() and bar() and at the top level refer to the samevariable instance:

     top's i=10
     foo's i=1
     bar's i=0
     bar's i=1
     bar's i=2
     foo's i=3
     top's i=3

If you want i to be local to both foo() and bar() do asfollows (the extra-space beforei is a coding convention toindicate that i is a local variable, not an argument):

     function bar(    i)
     {
         for (i = 0; i < 3; i++)
             print "bar's i=" i
     }
     
     function foo(j,    i)
     {
         i = j + 1
         print "foo's i=" i
         bar()
         print "foo's i=" i
     }
     
     BEGIN {
           i = 10
           print "top's i=" i
           foo(0)
           print "top's i=" i
     }

Running the corrected script produces the following:

     top's i=10
     foo's i=1
     bar's i=0
     bar's i=1
     bar's i=2
     foo's i=1
     top's i=10


Previous:  Variable Scope,Up:  Function Caveats

9.2.3.3 Passing Function Arguments By Value Or By Reference

In awk, when you declare a function, there is no way todeclare explicitly whether the arguments are passedby value orby reference.

Instead the passing convention is determined at runtime whenthe function is called according to the following rule:

  • If the argument is an array variable, then it is passed by reference,
  • Otherwise the argument is passed by value.

Passing an argument by value means that when a function is called, itis given acopy of the value of this argument. The caller may use a variable as the expression for the argument, butthe called function does not know this—it only knows what value theargument had. For example, if you write the following code:

     foo = "bar"
     z = myfunc(foo)

then you should not think of the argument to myfunc() as being“the variablefoo.” Instead, think of the argument as thestring value "bar". If the functionmyfunc() alters the values of its local variables,this has no effect on any other variables. Thus, ifmyfunc()does this:

     function myfunc(str)
     {
        print str
        str = "zzz"
        print str
     }

to change its first argument variable str, it doesnotchange the value of foo in the caller. The role of foo incalling myfunc() ended when its value ("bar") was computed. Ifstr also exists outside of myfunc(), the function bodycannot alter this outer value, because it is shadowed during theexecution ofmyfunc() and cannot be seen or changed from there.

However, when arrays are the parameters to functions, they arenotcopied. Instead, the array itself is made available for direct manipulationby the function. This is usually termedcall by reference. Changes made to an array parameter inside the body of a functionarevisible outside that function.

NOTE: Changing an array parameter inside a functioncan be very dangerous if you do not 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]
     }

prints ‘a[1] = 1, a[2] = two, a[3] = 3’, becausechangeit stores"two" in the second element of a.

Someawk implementations allow you to call a function thathas not been defined. They only report a problem at runtime when theprogram actually tries to call the function. For example:

     BEGIN {
         if (0)
             foo()
         else
             bar()
     }
     function bar() { ... }
     # note that `foo' is not defined

Because the ‘if’ statement will never be true, it is not really aproblem thatfoo() has not been defined. Usually, though, it is aproblem if a program calls an undefined function.

If --lint is specified(seeOptions),gawk reports calls to undefined functions.

Someawk implementations generate a runtimeerror if you use thenext statement(see Next Statement)inside a user-defined function.gawk does not have this limitation.


Next:  ,Previous:  Function Caveats,Up:  User-defined

9.2.4 The return Statement

As seen in several earlier examples,the body of a user-defined function can contain areturn statement. This statement returns control to the calling part of theawk program. Itcan also be used to return a value for use in the rest of theawkprogram. It looks like this:

     return [expression]

The expression part is optional. Due most likely to an oversight, POSIX does not define what the returnvalue is if you omit theexpression. Technically speaking, thismake the returned value undefined, and therefore, unpredictable. In practice, though, all versions ofawk simply return thenull string, which acts like zero if used in a numeric context.

A return statement with no value expression is assumed at the end ofevery function definition. So if control reaches the end of the functionbody, then technically, the function returns an unpredictable value. In practice, it returns the empty string. awkdoes not warn you if you use the return value of such a function.

Sometimes, you want to write a function for what it does, not forwhat it returns. Such a function corresponds to avoid functionin C, C++ or Java, or to a procedure in Ada. Thus, it may be appropriate to notreturn any value; simply bear in mind that you should not be using thereturn value of such a function.

The following is an example of a user-defined function that returns a valuefor 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 callmaxelt() with one argument, which is an array name. The localvariablesi and ret are not intended to be arguments;while there is nothing to stop you from passing more than one argumenttomaxelt(), the results would be strange. The extra space beforei in the function parameter list indicates thati andret are local variables. You should follow this convention when defining functions.

The following program uses the maxelt() function. It loads anarray, callsmaxelt(), and then reports the maximum number in thatarray:

     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

the program reports (predictably) that 99,385 is the largest valuein the array.


Previous:  Return Statement,Up:  User-defined

9.2.5 Functions and Their Effects on Variable Typing

awk is a very fluid language. It is possible thatawk can't tell if an identifierrepresents a scalar variable or an array until runtime. Here is an annotated sample program:

     function foo(a)
     {
         a[1] = 1   # parameter is an array
     }
     
     BEGIN {
         b = 1
         foo(b)  # invalid: fatal type mismatch
     
         foo(x)  # x uninitialized, becomes an array dynamically
         x = 1   # now not allowed, runtime error
     }

Usually, such things aren't a big issue, but it's worthbeing aware of them.


Previous:  User-defined,Up:  Functions

9.3 Indirect Function Calls

This section describes a gawk-specific extension.

Often, you may wish to defer the choice of function to call until runtime. For example, you may have different kinds of records, each of whichshould be processed differently.

Normally, you would have to use a series of if-elsestatements to decide which function to call. By usingindirectfunction calls, you can specify the name of the function to call as astring variable, and then call the function. Let's look at an example.

Suppose you have a file with your test scores for the classes youare taking. The first field is the class name. The following fieldsare the functions to call to process the data, up to a “marker”field ‘data:’. Following the marker, to the end of the record,are the various numeric test scores.

Here is the initial file; you wish to get the sum and the average ofyour test scores:

     
     Biology_101 sum average data: 87.0 92.4 78.5 94.9
     Chemistry_305 sum average data: 75.2 98.3 94.7 88.2
     English_401 sum average data: 100.0 95.6 87.1 93.4
     

To process the data, you might write initially:

     {
         class = $1
         for (i = 2; $i != "data:"; i++) {
             if ($i == "sum")
                 sum()   # processes the whole record
             else if ($i == "average")
                 average()
             ...           # and so on
         }
     }

This style of programming works, but can be awkward. With indirectfunction calls, you tell gawk to use thevalue of avariable as the name of the function to call.

The syntax is similar to that of a regular function call: an identifierimmediately followed by a left parenthesis, any arguments, and thena closing right parenthesis, with the addition of a leading ‘@’character:

     the_func = "sum"
     result = @the_func()   # calls the `sum' function

Here is a full program that processes the previously shown data,using indirect function calls.

     
     # indirectcall.awk --- Demonstrate indirect function calls
     
     
     
     # average --- return the average of the values in fields $first - $last
     
     function average(first, last,   sum, i)
     {
         sum = 0;
         for (i = first; i <= last; i++)
             sum += $i
     
         return sum / (last - first + 1)
     }
     
     # sum --- return the sum of the values in fields $first - $last
     
     function sum(first, last,   ret, i)
     {
         ret = 0;
         for (i = first; i <= last; i++)
             ret += $i
     
         return ret
     }
     

These two functions expect to work on fields; thus the parametersfirst andlast indicate where in the fields to start and end. Otherwise they perform the expected computations and are not unusual.

     
     # For each record, print the class name and the requested statistics
     
     {
         class_name = $1
         gsub(/_/, " ", class_name)  # Replace _ with spaces
     
         # find start
         for (i = 1; i <= NF; i++) {
             if ($i == "data:") {
                 start = i + 1
                 break
             }
         }
     
         printf("%s:\n", class_name)
         for (i = 2; $i != "data:"; i++) {
             the_function = $i
             printf("\t%s: <%s>\n", $i, @the_function(start, NF) "")
         }
         print ""
     }
     

This is the main processing for each record. It prints the class name (withunderscores replaced with spaces). It then finds the start of the actual data,saving it instart. The last part of the code loops through each function name (from$2 up tothe marker, ‘data:’), calling the function named by the field. The indirectfunction call itself occurs as a parameter in the call toprintf. (The printf format string uses ‘%s’ as the format specifier so that wecan use functions that return strings, as well as numbers. Note that the resultfrom the indirect call is concatenated with the empty string, in order to forceit to be a string value.)

Here is the result of running the program:

     $ gawk -f indirectcall.awk class_data1
     -| Biology 101:
     -|     sum: <352.8>
     -|     average: <88.2>
     -|
     -| Chemistry 305:
     -|     sum: <356.4>
     -|     average: <89.1>
     -|
     -| English 401:
     -|     sum: <376.1>
     -|     average: <94.025>

The ability to use indirect function calls is more powerful than you maythink at first. The C and C++ languages provide “function pointers,” whichare a mechanism for calling a function chosen at runtime. One of the mostwell-known uses of this ability is the C qsort() function, which sortsan array using the famous “quick sort” algorithm(seethe Wikipedia articlefor more information). To use this function, you supply a pointer to a comparisonfunction. This mechanism allows you to sort arbitrary data in an arbitraryfashion.

We can do something similar using gawk, like this:

     
     # quicksort.awk --- Quicksort algorithm, with user-supplied
     #                   comparison function
     
     
     # quicksort --- C.A.R. Hoare's quick sort algorithm. See Wikipedia
     #               or almost any algorithms or computer science text
     
     
     
     function quicksort(data, left, right, less_than,    i, last)
     {
         if (left >= right)  # do nothing if array contains fewer
             return          # than two elements
     
         quicksort_swap(data, left, int((left + right) / 2))
         last = left
         for (i = left + 1; i <= right; i++)
             if (@less_than(data[i], data[left]))
                 quicksort_swap(data, ++last, i)
         quicksort_swap(data, left, last)
         quicksort(data, left, last - 1, less_than)
         quicksort(data, last + 1, right, less_than)
     }
     
     # quicksort_swap --- helper function for quicksort, should really be inline
     
     function quicksort_swap(data, i, j, temp)
     {
         temp = data[i]
         data[i] = data[j]
         data[j] = temp
     }
     

The quicksort() function receives the data array, the starting and endingindices to sort (left andright), and the name of a function thatperforms a “less than” comparison. It then implements the quick sort algorithm.

To make use of the sorting function, we return to our previous example. Thefirst thing to do is write some comparison functions:

     
     # num_lt --- do a numeric less than comparison
     
     function num_lt(left, right)
     {
         return ((left + 0) < (right + 0))
     }
     
     # num_ge --- do a numeric greater than or equal to comparison
     
     function num_ge(left, right)
     {
         return ((left + 0) >= (right + 0))
     }
     

The num_ge() function is needed to perform a descending sort; when usedto perform a “less than” test, it actually does the opposite (greater thanor equal to), which yields data sorted in descending order.

Next comes a sorting function. It is parameterized with the starting andending field numbers and the comparison function. It builds an array withthe data and callsquicksort appropriately, and then formats theresults as a single string:

     
     # do_sort --- sort the data according to `compare'
     #             and return it as a string
     
     function do_sort(first, last, compare,      data, i, retval)
     {
         delete data
         for (i = 1; first <= last; first++) {
             data[i] = $first
             i++
         }
     
         quicksort(data, 1, i-1, compare)
     
         retval = data[1]
         for (i = 2; i in data; i++)
             retval = retval " " data[i]
     
         return retval
     }
     

Finally, the two sorting functions call do_sort(), passing in thenames of the two comparison functions:

     
     # sort --- sort the data in ascending order and return it as a string
     
     function sort(first, last)
     {
         return do_sort(first, last, "num_lt")
     }
     
     # rsort --- sort the data in descending order and return it as a string
     
     function rsort(first, last)
     {
         return do_sort(first, last, "num_ge")
     }
     

Here is an extended version of the data file:

     
     Biology_101 sum average sort rsort data: 87.0 92.4 78.5 94.9
     Chemistry_305 sum average sort rsort data: 75.2 98.3 94.7 88.2
     English_401 sum average sort rsort data: 100.0 95.6 87.1 93.4
     

Finally, here are the results when the enhanced program is run:

     $ gawk -f quicksort.awk -f indirectcall.awk class_data2
     -| Biology 101:
     -|     sum: <352.8>
     -|     average: <88.2>
     -|     sort: <78.5 87.0 92.4 94.9>
     -|     rsort: <94.9 92.4 87.0 78.5>
     -|
     -| Chemistry 305:
     -|     sum: <356.4>
     -|     average: <89.1>
     -|     sort: <75.2 88.2 94.7 98.3>
     -|     rsort: <98.3 94.7 88.2 75.2>
     -|
     -| English 401:
     -|     sum: <376.1>
     -|     average: <94.025>
     -|     sort: <87.1 93.4 95.6 100.0>
     -|     rsort: <100.0 95.6 93.4 87.1>

Remember that you must supply a leading ‘@’ in front of an indirect function call.

Unfortunately, indirect function calls cannot be used with the built-in functions. However,you can generally write “wrapper” functions which call the built-in ones, and those canbe called indirectly. (Other than, perhaps, the mathematical functions, there is not a lotof reason to try to call the built-in functions indirectly.)

gawk does its best to make indirect function calls efficient. For example, in the following case:

     for (i = 1; i <= n; i++)
         @the_func()

gawk will look up the actual function to call only once.


Next:  ,Previous:  Functions,Up:  Top

10 Internationalization with gawk

Once upon a time, computer makerswrote software that worked only in English. Eventually, hardware and software vendors noticed that if theirsystems worked in the native languages of non-English-speakingcountries, they were able to sell more systems. As a result, internationalization and localizationof programs and software systems became a common practice.

For many years, the ability to provide internationalizationwas largely restricted to programs written in C and C++. This chapter describes the underlying librarygawkuses for internationalization, as well as howgawk makes internationalizationfeatures available at theawk program level. Having internationalization available at theawk levelgives software developers additional flexibility—they are nolonger forced to write in C or C++ when internationalization isa requirement.

10.1 Internationalization and Localization

Internationalization means writing (or modifying) a program once,in such a way that it can use multiple languages without requiringfurther source-code changes.Localization means providing the data necessary for aninternationalized program to work in a particular language. Most typically, these terms refer to features such as the languageused for printing error messages, the language used to readresponses, and information related to how numerical andmonetary values are printed and read.

10.2 GNU gettext

The facilities in GNUgettext focus on messages; strings printedby a program, either directly or via formatting withprintf orsprintf().53

When using GNUgettext, each application has its owntext domain. This is a unique name, such as ‘kpilot’ or ‘gawk’,that identifies the application. A complete application may have multiple components—programs writtenin C or C++, as well as scripts written insh or awk. All of the components use the same text domain.

To make the discussion concrete, assume we're writing an applicationnamed guide. Internationalization consists of thefollowing steps, in this order:

  1. The programmer goesthrough the source for all of guide's componentsand marks each string that is a candidate for translation. For example,"`-F': option required" is a good candidate for translation. A table with strings of option names is not (e.g.,gawk's--profile option should remain the same, no matter what the locallanguage).

  2. The programmer indicates the application's text domain("guide") to thegettext library,by calling the textdomain() function.

  3. Messages from the application are extracted from the source code andcollected into a portable object template file (guide.pot),which lists the strings and their translations. The translations are initially empty. The original (usually English) messages serve as the key forlookup of the translations.

  4. For each language with a translator, guide.potis copied to a portable object file (.po)and translations are created and shipped with the application. For example, there might be afr.po for a French translation.

  5. Each language's .po file is converted into a binarymessage object (.mo) file. A message object file contains the original messages and theirtranslations in a binary format that allows fast lookup of translationsat runtime.
  6. When guide is built and installed, the binary translation filesare installed in a standard place.

  7. For testing and development, it is possible to tell gettextto use.mo files in a different directory than the standardone by using thebindtextdomain() function.

  8. At runtime, guide looks up each string via a calltogettext(). The returned string is the translated stringif available, or the original string if not.
  9. If necessary, it is possible to access messages from a differenttext domain than the one belonging to the application, withouthaving to switch the application's default text domain backand forth.

In C (or C++), the string marking and dynamic translation lookupare accomplished by wrapping each string in a call togettext():

     printf("%s", gettext("Don't Panic!\n"));

The tools that extract messages from source code pull out allstrings enclosed in calls togettext().

The GNUgettext developers, recognizing that typing‘gettext(...)’ over and over again is both painful and ugly to lookat, use the macro ‘_’ (an underscore) to make things easier:

     /* In the standard header file: */
     #define _(str) gettext(str)
     
     /* In the program text: */
     printf("%s", _("Don't Panic!\n"));

This reduces the typing overhead to just three extra characters per stringand is considerably easier to read as well.

There are locale categoriesfor different types of locale-related information. The defined locale categories thatgettext knows about are:

LC_MESSAGES
Text messages. This is the default category for gettextoperations, but it is possible to supply a different one explicitly,if necessary. (It is almost never necessary to supply a different category.)


LC_COLLATE
Text-collation information; i.e., how different charactersand/or groups of characters sort in a given language.


LC_CTYPE
Character-type information (alphabetic, digit, upper- or lowercase, andso on). This information is accessed via thePOSIX character classes in regular expressions,such as /[[:alnum:]]/(see Regexp Operators).


LC_MONETARY
Monetary information, such as the currency symbol, and whether thesymbol goes before or after a number.


LC_NUMERIC
Numeric information, such as which characters to use for the decimalpoint and the thousands separator. 54


LC_RESPONSE
Response information, such as how “yes” and “no” appear in thelocal language, and possibly other information as well.


LC_TIME
Time- and date-related information, such as 12- or 24-hour clock, month printedbefore or after the day in a date, local month abbreviations, and so on.


LC_ALL
All of the above. (Not too useful in the context of gettext.)

10.3 Internationalizing awk Programs

gawk provides the following variables and functions forinternationalization:

TEXTDOMAIN
This variable indicates the application's text domain. For compatibility with GNU gettext, the defaultvalue is "messages".


_"your message here"
String constants marked with a leading underscoreare candidates for translation at runtime. String constants without a leading underscore are not translated.


dcgettext( string [ , domain [ , category ]] )
Return the translation of string intext domain domain for locale category category. The default value for domain is the current value of TEXTDOMAIN. The default value for category is "LC_MESSAGES".

If you supply a value for category, it must be a string equal toone of the known locale categories described inthe previous section. You must also supply a text domain. UseTEXTDOMAIN ifyou want to use the current domain.

CAUTION: The order of arguments to the awk versionof the dcgettext() function is purposely different from the order forthe C version. The awk version's order waschosen to be simple and to allow for reasonable awk-styledefault arguments.


dcngettext( string1 , string2 , number [ , domain [ , category ]] )
Return the plural form used for number of thetranslation of string1 and string2 in text domain domain for locale category category. string1 is theEnglish singular variant of a message, and string2 the English pluralvariant of the same message. The default value for domain is the current value of TEXTDOMAIN. The default value for category is "LC_MESSAGES".

The same remarks about argument order as for the dcgettext() function apply.


bindtextdomain( directory [ , domain ] )
Change the directory in which gettext looks for .mo files, in case theywill not or cannot be placed in the standard locations(e.g., during testing). Return the directory in which domain is “bound.”

The default domain is the value of TEXTDOMAIN. If directory is the null string (""), thenbindtextdomain() returns the current binding for thegivendomain.

To use these facilities in your awk program, follow the stepsoutlined inthe previous section,like so:

  1. Set the variable TEXTDOMAIN to the text domain ofyour program. This is best done in aBEGIN rule(see BEGIN/END),or it can also be done via the-v command-lineoption (see Options):
              BEGIN {
                  TEXTDOMAIN = "guide"
                  ...
              }
    

  2. Mark all translatable strings with a leading underscore (‘_’)character. Itmust be adjacent to the openingquote of the string. For example:
              print _"hello, world"
              x = _"you goofed"
              printf(_"Number of users is %d\n", nusers)
    
  3. If you are creating strings dynamically, you canstill translate them, using thedcgettext()built-in function:
              message = nusers " users logged in"
              message = dcgettext(message, "adminprog")
              print message
    

    Here, the call to dcgettext() supplies a differenttext domain ("adminprog") in which to find themessage, but it uses the default"LC_MESSAGES" category.

  4. During development, you might want to put the .mofile in a private directory for testing. This is donewith thebindtextdomain() built-in function:
              BEGIN {
                 TEXTDOMAIN = "guide"   # our text domain
                 if (Testing) {
                     # where to find our files
                     bindtextdomain("testdir")
                     # joe is in charge of adminprog
                     bindtextdomain("../joe/testdir", "adminprog")
                 }
                 ...
              }
    

See I18N Example,for an example program showing the steps to createand use translations fromawk.

10.4 Translating awk Programs

Once a program's translatable strings have been marked, they mustbe extracted to create the initial .po file. As part of translation, it is often helpful to rearrange the orderin which arguments toprintf are output.

gawk's --gen-pot command-line option extractsthe messages and is discussed next. After that,printf's ability torearrange the order for printf arguments at runtimeis covered.

10.4.1 Extracting Marked Strings

Once your awk program is working, and all the strings havebeen marked and you've set (and perhaps bound) the text domain,it is time to produce translations. First, use the--gen-pot command-line option to createthe initial.pot file:

     $ gawk --gen-pot -f guide.awk > guide.pot

When run with --gen-pot, gawk does not execute yourprogram. Instead, it parses it as usual and prints all marked stringsto standard output in the format of a GNUgettext Portable Objectfile. Also included in the output are any constant strings thatappear as the first argument todcgettext() or as the first andsecond argument to dcngettext().55SeeI18N Example,for the full list of steps to go through to create and testtranslations forguide.

10.4.2 Rearranging printf Arguments

Format strings forprintf and sprintf()(see Printf)present a special problem for translation. Consider the following:56

     printf(_"String `%s' has %d characters\n",
               string, length(string)))

A possible German translation for this might be:

     "%d Zeichen lang ist die Zeichenkette `%s'\n"

The problem should be obvious: the order of the formatspecifications is different from the original! Even thoughgettext() can return the translated stringat runtime,it cannot change the argument order in the call toprintf.

To solve this problem, printf format specifiers may havean additional optional element, which we call apositional specifier. For example:

     "%2$d Zeichen lang ist die Zeichenkette `%1$s'\n"

Here, the positional specifier consists of an integer count, which indicates whichargument to use, and a ‘$’. Counts are one-based, and theformat string itself isnot included. Thus, in the followingexample, ‘string’ is the first argument and ‘length(string)’ is the second:

     $ gawk 'BEGIN {
     >     string = "Dont Panic"
     >     printf _"%2$d characters live in \"%1$s\"\n",
     >                         string, length(string)
     > }'
     -| 10 characters live in "Dont Panic"

If present, positional specifiers come first in the format specification,before the flags, the field width, and/or the precision.

Positional specifiers can be used with the dynamic field width andprecision capability:

     $ gawk 'BEGIN {
     >    printf("%*.*s\n", 10, 20, "hello")
     >    printf("%3$*2$.*1$s\n", 20, 10, "hello")
     > }'
     -|      hello
     -|      hello
NOTE: When using ‘ *’ with a positional specifier, the ‘ *’comes first, then the integer position, and then the ‘ $’. This is somewhat counterintuitive.

gawk does not allow you to mix regular format specifiersand those with positional specifiers in the same string:

     $ gawk 'BEGIN { printf _"%d %3$s\n", 1, 2, "hi" }'
     error--> gawk: cmd. line:1: fatal: must use `count$' on all formats or none
NOTE: There are some pathological cases that gawk may fail todiagnose. In such cases, the output may not be what you expect. It's still a bad idea to try mixing them, even if gawkdoesn't detect it.

Although positional specifiers can be used directly in awk programs,their primary purpose is to help in producing correct translations offormat strings into languages different from the one in which the programis first written.


Previous:  Printf Ordering,Up:  Translator i18n

10.4.3 awk Portability Issues

gawk's internationalization features were purposely chosen tohave as little impact as possible on the portability of awkprograms that use them to other versions ofawk. Consider this program:

     BEGIN {
         TEXTDOMAIN = "guide"
         if (Test_Guide)   # set with -v
             bindtextdomain("/test/guide/messages")
         print _"don't panic!"
     }

As written, it won't work on other versions of awk. However, it is actually almost portable, requiring very littlechange:

  • Assignments to TEXTDOMAIN won't have any effect,since TEXTDOMAIN is not special in otherawk implementations.
  • Non-GNU versions of awk treat marked stringsas the concatenation of a variable named_ with the stringfollowing it.57 Typically, the variable_ hasthe null string ("") as its value, leaving the original string constant asthe result.
  • By defining “dummy” functions to replace dcgettext(), dcngettext()andbindtextdomain(), the awk program can be made to run, butall the messages are output in the original language. For example:

              
              function bindtextdomain(dir, domain)
              {
                  return dir
              }
              
              function dcgettext(string, domain, category)
              {
                  return string
              }
              
              function dcngettext(string1, string2, number, domain, category)
              {
                  return (number == 1 ? string1 : string2)
              }
              
    
  • The use of positional specifications in printf orsprintf() isnot portable. To support gettext() at the C level, many systems' C versions ofsprintf() do support positional specifiers. But it works only ifenough arguments are supplied in the function call. Many versions ofawk pass printf formats and arguments unchanged to theunderlying C library version ofsprintf(), but only one format andargument at a time. What happens if a positional specification isused is anybody's guess. However, since the positional specifications are primarily for use intranslated format strings, and since non-GNUawks neverretrieve the translated string, this should not be a problem in practice.


Next:  ,Previous:  Translator i18n,Up:  Internationalization

10.5 A Simple Internationalization Example

Now let's look at a step-by-step example of how to internationalize andlocalize a simpleawk program, using guide.awk as ouroriginal source:

     
     BEGIN {
         TEXTDOMAIN = "guide"
         bindtextdomain(".")  # for testing
         print _"Don't Panic"
         print _"The Answer Is", 42
         print "Pardon me, Zaphod who?"
     }
     

Run ‘gawk --gen-pot’ to create the.pot file:

     $ gawk --gen-pot -f guide.awk > guide.pot

This produces:

     
     #: guide.awk:4
     msgid "Don't Panic"
     msgstr ""
     
     #: guide.awk:5
     msgid "The Answer Is"
     msgstr ""
     
     

This original portable object template file is saved and reused for each languageinto which the application is translated. Themsgidis the original string and the msgstr is the translation.

NOTE: Strings not marked with a leading underscore do notappear in the guide.pot file.

Next, the messages must be translated. Here is a translation to a hypothetical dialect of English,called “Mellow”:58

     $ cp guide.pot guide-mellow.po
     Add translations to guide-mellow.po ...

Following are the translations:

     
     #: guide.awk:4
     msgid "Don't Panic"
     msgstr "Hey man, relax!"
     
     #: guide.awk:5
     msgid "The Answer Is"
     msgstr "Like, the scoop is"
     
     

The next step is to make the directory to hold the binary message objectfile and then to create theguide.mo file. The directory layout shown here is standard for GNUgettext onGNU/Linux systems. Other versions of gettext may use a differentlayout:

     $ mkdir en_US en_US/LC_MESSAGES

Themsgfmt utility does the conversion from human-readable.po file to machine-readable.mo file. By default, msgfmt creates a file namedmessages. This file must be renamed and placed in the proper directory so thatgawk can find it:

     $ msgfmt guide-mellow.po
     $ mv messages en_US/LC_MESSAGES/guide.mo

Finally, we run the program to test it:

     $ gawk -f guide.awk
     -| Hey man, relax!
     -| Like, the scoop is 42
     -| Pardon me, Zaphod who?

If the three replacement functions for dcgettext(), dcngettext()andbindtextdomain()(see I18N Portability)are in a file namedlibintl.awk,then we can run guide.awk unchanged as follows:

     $ gawk --posix -f guide.awk -f libintl.awk
     -| Don't Panic
     -| The Answer Is 42
     -| Pardon me, Zaphod who?

10.6 gawk Can Speak Your Language

gawk itself has been internationalizedusing the GNUgettext package. (GNU gettext is described incomplete detail inGNU gettext tools.) As of this writing, the latest version of GNUgettext isversion 0.18.1.

If a translation of gawk's messages exists,thengawk produces usage messages, warnings,and fatal errors in the local language.


Next:  ,Previous:  Internationalization,Up:  Top

11 Advanced Features of gawk

Write documentation as if whoever reads it isa violent psychopath who knows where you live.
Steve English, as quoted by Peter Langston

This chapter discusses advanced features in gawk. It's a bit of a “grab bag” of items that are otherwise unrelatedto each other. First, a command-line option allowsgawk to recognizenondecimal numbers in input data, not just inawkprograms. Then, gawk's special features for sorting arrays are presented. Next, two-way I/O, discussed briefly in earlier parts of thisWeb page, is described in full detail, along with the basicsof TCP/IP networking. Finally, gawkcanprofile an awk program, making it possible to tuneit for performance.

Dynamic Extensions,discusses the ability to dynamically add new built-in functions togawk. As this feature is still immature and likely to change,its description is relegated to an appendix.

11.1 Allowing Nondecimal Input Data

If you run gawk with the --non-decimal-data option,you can have nondecimal constants in your input data:

     $ echo 0123 123 0x123 |
     > gawk --non-decimal-data '{ printf "%d, %d, %d\n",
     >                                         $1, $2, $3 }'
     -| 83, 123, 291

For this feature to work, write your program so thatgawk treats your data as numeric:

     $ echo 0123 123 0x123 | gawk '{ print $1, $2, $3 }'
     -| 0123 123 0x123

The print statement treats its expressions as strings. Although the fields can act as numbers when necessary,they are still strings, soprint does not try to treat themnumerically. You may need to add zero to a field to force it tobe treated as a number. For example:

     $ echo 0123 123 0x123 | gawk --non-decimal-data '
     > { print $1, $2, $3
     >   print $1 + 0, $2 + 0, $3 + 0 }'
     -| 0123 123 0x123
     -| 83 123 291

Because it is common to have decimal data with leading zeros, and becauseusing this facility could lead to surprising results, the default is to leave itdisabled. If you want it, you must explicitly request it.

CAUTION: Use of this option is not recommended.It can break old programs very badly. Instead, use the strtonum() function to convert your data(see Nondecimal-numbers). This makes your programs easier to write and easier to read, andleads to less surprising results.


Next:  ,Previous:  Nondecimal Data,Up:  Advanced Features

11.2 Controlling Array Traversal and Array Sorting

gawk lets you control the order in which ‘for (i in array)’ loopswill traverse an array.

In addition, two built-in functions, asort() and asorti(),let you sort arrays based on the array values and indices, respectively. These two functions also provide control over the sorting criteria usedto order the elements during sorting.

11.2.1 Controlling Array Traversal

By default, the order in which a ‘for (i in array)’ loopscans an array is not defined; it is generally based uponthe internal implementation of arrays insideawk.

Often, though, it is desirable to be able to loop over the elementsin a particular order that you, the programmer, choose.gawklets you do this; this subsection describes how.

11.2.1.1 Array Scanning Using A User-defined Function

The value of PROCINFO["sorted_in"] can be a function name. This lets you traverse an array based on any custom criterion. The array elements are ordered according to the return value of thisfunction. The comparison function should be defined with at leastfour arguments:

     function comp_func(i1, v1, i2, v2)
     {
         compare elements 1 and 2 in some fashion
         return < 0; 0; or > 0
     }

Here, i1 and i2 are the indices, and v1 and v2are the corresponding values of the two elements being compared. Either v1 or v2, or both, can be arrays if the array beingtraversed contains subarrays as values. The three possible return valuesare interpreted this way:

comp_func(i1, v1, i2, v2) < 0
Index i1 comes before index i2 during loop traversal.
comp_func(i1, v1, i2, v2) == 0
Indices i1 and i2come together but the relative order with respect to each other is undefined.
comp_func(i1, v1, i2, v2) > 0
Index i1 comes after index i2 during loop traversal.

Our first comparison function can be used to scan an array innumerical order of the indices:

     function cmp_num_idx(i1, v1, i2, v2)
     {
          # numerical index comparison, ascending order
          return (i1 - i2)
     }

Our second function traverses an array based on the string order ofthe element values rather than by indices:

     function cmp_str_val(i1, v1, i2, v2)
     {
         # string value comparison, ascending order
         v1 = v1 ""
         v2 = v2 ""
         if (v1 < v2)
             return -1
         return (v1 != v2)
     }

The thirdcomparison function makes all numbers, and numeric strings withoutany leading or trailing spaces, come out first during loop traversal:

     function cmp_num_str_val(i1, v1, i2, v2,   n1, n2)
     {
          # numbers before string value comparison, ascending order
          n1 = v1 + 0
          n2 = v2 + 0
          if (n1 == v1)
              return (n2 == v2) ? (n1 - n2) : -1
          else if (n2 == v2)
              return 1
          return (v1 < v2) ? -1 : (v1 != v2)
     }

Here is a main program to demonstrate how gawkbehaves using each of the previous functions:

     BEGIN {
         data["one"] = 10
         data["two"] = 20
         data[10] = "one"
         data[100] = 100
         data[20] = "two"
     
         f[1] = "cmp_num_idx"
         f[2] = "cmp_str_val"
         f[3] = "cmp_num_str_val"
         for (i = 1; i <= 3; i++) {
             printf("Sort function: %s\n", f[i])
             PROCINFO["sorted_in"] = f[i]
             for (j in data)
                 printf("\tdata[%s] = %s\n", j, data[j])
             print ""
         }
     }

Here are the results when the program is run:

     $ gawk -f compdemo.awk
     -| Sort function: cmp_num_idx      Sort by numeric index
     -|     data[two] = 20
     -|     data[one] = 10              Both strings are numerically zero
     -|     data[10] = one
     -|     data[20] = two
     -|     data[100] = 100
     -|
     -| Sort function: cmp_str_val      Sort by element values as strings
     -|     data[one] = 10
     -|     data[100] = 100             String 100 is less than string 20
     -|     data[two] = 20
     -|     data[10] = one
     -|     data[20] = two
     -|
     -| Sort function: cmp_num_str_val  Sort all numbers before all strings
     -|     data[one] = 10
     -|     data[two] = 20
     -|     data[100] = 100
     -|     data[10] = one
     -|     data[20] = two

Consider sorting the entries of a GNU/Linux system password fileaccording to login names. The following program sorts recordsby a specific field position and can be used for this purpose:

     # sort.awk --- simple program to sort by field position
     # field position is specified by the global variable POS
     
     function cmp_field(i1, v1, i2, v2)
     {
         # comparison by value, as string, and ascending order
         return v1[POS] < v2[POS] ? -1 : (v1[POS] != v2[POS])
     }
     
     {
         for (i = 1; i <= NF; i++)
             a[NR][i] = $i
     }
     
     END {
         PROCINFO["sorted_in"] = "cmp_field"
         if (POS < 1 || POS > NF)
             POS = 1
         for (i in a) {
             for (j = 1; j <= NF; j++)
                 printf("%s%c", a[i][j], j < NF ? ":" : "")
             print ""
         }
     }

The first field in each entry of the password file is the user's login name,and the fields are seperated by colons. Each record defines a subarray (seeArrays of Arrays),with each field as an element in the subarray. Running the program produces thefollowing output:

     $ gawk -vPOS=1 -F: -f sort.awk /etc/passwd
     -| adm:x:3:4:adm:/var/adm:/sbin/nologin
     -| apache:x:48:48:Apache:/var/www:/sbin/nologin
     -| avahi:x:70:70:Avahi daemon:/:/sbin/nologin
     ...

The comparison should normally always return the same value when given aspecific pair of array elements as its arguments. If inconsistentresults are returned then the order is undefined. This behavior can beexploited to introduce random order into otherwise seeminglyordered data:

     function cmp_randomize(i1, v1, i2, v2)
     {
         # random order
         return (2 - 4 * rand())
     }

As mentioned above, the order of the indices is arbitrary if twoelements compare equal. This is usually not a problem, but lettingthe tied elements come out in arbitrary order can be an issue, especiallywhen comparing item values. The partial ordering of the equal elementsmay change during the next loop traversal, if other elements are added orremoved from the array. One way to resolve ties when comparing elementswith otherwise equal values is to include the indices in the comparisonrules. Note that doing this may make the loop traversal less efficient,so consider it only if necessary. The following comparison functionsforce a deterministic order, and are based on the fact that theindices of two elements are never equal:

     function cmp_numeric(i1, v1, i2, v2)
     {
         # numerical value (and index) comparison, descending order
         return (v1 != v2) ? (v2 - v1) : (i2 - i1)
     }
     
     function cmp_string(i1, v1, i2, v2)
     {
         # string value (and index) comparison, descending order
         v1 = v1 i1
         v2 = v2 i2
         return (v1 > v2) ? -1 : (v1 != v2)
     }

A custom comparison function can often simplify ordered looptraversal, and the sky is really the limit when it comes todesigning such a function.

When string comparisons are made during a sort, either for elementvalues where one or both aren't numbers, or for element indiceshandled as strings, the value ofIGNORECASE(see Built-in Variables) controls whetherthe comparisons treat corresponding uppercase and lowercase letters asequivalent or distinct.

Another point to keep in mind is that in the case of subarraysthe element values can themselves be arrays; a production comparisonfunction should use theisarray() function(see Type Functions),to check for this, and choose a defined sorting order for subarrays.

All sorting based on PROCINFO["sorted_in"]is disabled in POSIX mode,since thePROCINFO array is not special in that case.

As a side note, sorting the array indices before traversingthe array has been reported to add 15% to 20% overhead to theexecution time ofawk programs. For this reason,sorted array traversal is not the default.

11.2.1.2 Controlling Array Scanning Order

As described inControlling Scanning With A Function,you can provide the name of a function as the value ofPROCINFO["sorted_in"] to specify custom sorting criteria.

Often, though, you may wish to do something simple, such as“sort based on comparing the indices in ascending order,”or “sort based on comparing the values in descending order.”Having to write a simple comparison function for this purposefor use in all of your programs becomes tedious. For the common simple cases, gawk providesthe option of supplying special names that do the requestedsorting for you. You can think of them as “predefined” sorting functions,if you like, although the names purposely include charactersthat are not valid in real awk function names.

The following special values are available:

"@ind_str_asc"
Order by indices compared as strings; this is the most basic sort. (Internally, array indices are always strings, so with ‘ a[2*5] = 1’the index is "10" rather than numeric 10.)
"@ind_num_asc"
Order by indices but force them to be treated as numbers in the process. Any index with a non-numeric value will end up positioned as if it were zero.
"@val_type_asc"
Order by element values rather than indices. Ordering is by the type assigned to the element(see Typing and Comparison). All numeric values come before all string values,which in turn come before all subarrays.
"@val_str_asc"
Order by element values rather than by indices. Scalar values arecompared as strings. Subarrays, if present, come out last.
"@val_num_asc"
Order by element values rather than by indices. Scalar values arecompared as numbers. Subarrays, if present, come out last. When numeric values are equal, the string values are used to providean ordering: this guarantees consistent results across differentversions of the C qsort() function. 59
"@ind_str_desc"
Reverse order from the most basic sort.
"@ind_num_desc"
Numeric indices ordered from high to low.
"@val_type_desc"
Element values, based on type, in descending order.
"@val_str_desc"
Element values, treated as strings, ordered from high to low. Subarrays, if present, come out first.
"@val_num_desc"
Element values, treated as numbers, ordered from high to low. Subarrays, if present, come out first.
"@unsorted"
Array elements are processed in arbitrary order, which is the normal awk behavior. You can also get the normal behavior by justdeleting the "sorted_in" element from the PROCINFO array,if it previously had a value assigned to it.

The array traversal order is determined before the for loopstarts to run. ChangingPROCINFO["sorted_in"] in the loop bodywill not affect the loop.

For example:

     $ gawk 'BEGIN {
     >    a[4] = 4
     >    a[3] = 3
     >    for (i in a)
     >        print i, a[i]
     > }'
     -| 4 4
     -| 3 3
     $ gawk 'BEGIN {
     >    PROCINFO["sorted_in"] = "@str_ind_asc"
     >    a[4] = 4
     >    a[3] = 3
     >    for (i in a)
     >        print i, a[i]
     > }'
     -| 3 3
     -| 4 4

When sorting an array by element values, if a value happens to bea subarray then it is considered to be greater than any string ornumeric value, regardless of what the subarray itself contains,and all subarrays are treated as being equal to each other. Theirorder relative to each other is determined by their index strings.

11.2.2 Sorting Array Values and Indices with gawk

In most awk implementations, sorting an array requireswriting asort function. While this can be educational for exploring different sorting algorithms,usually that's not the point of the program.gawk provides the built-in asort()andasorti() functions(see String Functions)for sorting arrays. For example:

     populate the array data
     n = asort(data)
     for (i = 1; i <= n; i++)
         do something with data[i]

After the call to asort(), the array data is indexed from 1to some numbern, the total number of elements in data. (This count is asort()'s return value.) data[1] <= data[2] <= data[3], and so on. The array elements are compared as strings.

An important side effect of callingasort() is thatthe array's original indices are irrevocably lost. As this isn't always desirable,asort() accepts asecond argument:

     populate the array source
     n = asort(source, dest)
     for (i = 1; i <= n; i++)
         do something with dest[i]

In this case, gawk copies the source array into thedest array and then sorts dest, destroying its indices. However, thesource array is not affected.

asort() accepts a third string argumentto control comparison of array elements. As withPROCINFO["sorted_in"], this argument may be thename of a user-defined function, or one of the predefined namesthatgawk provides(see Controlling Scanning With A Function).

NOTE: In all cases, the sorted element values consist of the originalarray's element values. The ability to control comparison merelyaffects the way in which they are sorted.

Often, what's needed is to sort on the values of the indicesinstead of the values of the elements. To do that, use theasorti() function. The interface is identical to that ofasort(), except that the index values are used for sorting, andbecome the values of the result array:

     { source[$0] = some_func($0) }
     
     END {
         n = asorti(source, dest)
         for (i = 1; i <= n; i++) {
             Work with sorted indices directly:
             do something with dest[i]
             ...
             Access original array via sorted indices:
             do something with source[dest[i]]
         }
     }

Similar to asort(),in all cases, the sorted element values consist of the originalarray's indices. The ability to control comparison merelyaffects the way in which they are sorted.

Sorting the array by replacing the indices provides maximal flexibility. To traverse the elements in decreasing order, use a loop that goes fromn down to 1, either over the elements or over the indices.60

Copying array indices and elements isn't expensive in terms of memory. Internally,gawk maintains reference counts to data. For example, whenasort() copies the first array to the second one,there is only one copy of the original array elements' data, even thoughboth arrays use the values.

BecauseIGNORECASE affects string comparisons, the valueof IGNORECASE also affects sorting for bothasort() and asorti(). Note also that the locale's sorting order doesnotcome into play; comparisons are based on character values only.61Caveat Emptor.

11.3 Two-Way Communications with Another Process

     
     From: brennan@whidbey.com (Mike Brennan)
     Newsgroups: comp.lang.awk
     Subject: Re: Learn the SECRET to Attract Women Easily
     Date: 4 Aug 1997 17:34:46 GMT
     
     
     Message-ID: <5s53rm$eca@news.whidbey.com>
     <!-- References: <5s20dn 2e1="" chronicle="" concentric="" net=""> -->
     
     
     
     
     
     On 3 Aug 1997 13:17:43 GMT, Want More Dates???
     <tracy78@kilgrona.com> wrote:
     >Learn the SECRET to Attract Women Easily
     >
     >The SCENT(tm)  Pheromone Sex Attractant For Men to Attract Women
     
     The scent of awk programmers is a lot more attractive to women than
     the scent of perl programmers.
     --
     Mike Brennan
     

It is often useful to be able tosend data to a separate program forprocessing and then read the result. This can always bedone with temporary files:

     # Write the data for processing
     tempfile = ("mydata." PROCINFO["pid"])
     while (not done with data)
         print data | ("subprogram > " tempfile)
     close("subprogram > " tempfile)
     
     # Read the results, remove tempfile when done
     while ((getline newdata < tempfile) > 0)
         process newdata appropriately
     close(tempfile)
     system("rm " tempfile)

This works, but not elegantly. Among other things, it requires thatthe program be run in a directory that cannot be shared among users;for example,/tmp will not do, as another user might happento be using a temporary file with the same name.

However, with gawk, it is possible toopen a two-way pipe to another process. The second process istermed a coprocess, since it runs in parallel withgawk. The two-way connection is created using the ‘|&’ operator(borrowed from the Korn shell,ksh):62

     do {
         print data |& "subprogram"
         "subprogram" |& getline results
     } while (data left to process)
     close("subprogram")

The first time an I/O operation is executed using the ‘|&’operator,gawk creates a two-way pipeline to a child processthat runs the other program. Output created withprintor printf is written to the program's standard input, andoutput from the program's standard output can be read by thegawkprogram using getline. As is the case with processes started by ‘|’, the subprogramcan be any program, or pipeline of programs, that can be started bythe shell.

There are some cautionary items to be aware of:

  • As the code inside gawk currently stands, the coprocess'sstandard error goes to the same place that the parentgawk'sstandard error goes. It is not possible to read the child'sstandard error separately.

  • I/O buffering may be a problem. gawk automaticallyflushes all output down the pipe to the coprocess. However, if the coprocess does not flush its output,gawk may hang when doing a getline in order to readthe coprocess's results. This could lead to a situationknown asdeadlock, where each process is waiting for theother one to do something.

It is possible to close just one end of the two-way pipe toa coprocess, by supplying a second argument to theclose()function of either "to" or "from"(seeClose Files And Pipes). These strings tell gawk to close the end of the pipethat sends data to the coprocess or the end that reads from it,respectively.

This is particularly necessary in order to usethe systemsort utility as part of a coprocess;sort must readall of its inputdata before it can produce any output. The sort program does not receive an end-of-file indicationuntilgawk closes the write end of the pipe.

When you have finished writing data to the sortutility, you can close the"to" end of the pipe, andthen start reading sorted data via getline. For example:

     BEGIN {
         command = "LC_ALL=C sort"
         n = split("abcdefghijklmnopqrstuvwxyz", a, "")
     
         for (i = n; i > 0; i--)
             print a[i] |& command
         close(command, "to")
     
         while ((command |& getline line) > 0)
             print "got", line
         close(command)
     }

This program writes the letters of the alphabet in reverse order, oneper line, down the two-way pipe tosort. It then closes thewrite end of the pipe, so thatsort receives an end-of-fileindication. This causessort to sort the data and write thesorted data back to thegawk program. Once all of the datahas been read,gawk terminates the coprocess and exits.

As a side note, the assignment ‘LC_ALL=C’ in thesortcommand ensures traditional Unix (ASCII) sorting fromsort.

You may also use pseudo-ttys (ptys) fortwo-way communication instead of pipes, if your system supports them. This is done on a per-command basis, by setting a special elementin the PROCINFO array(see Auto-set),like so:

     command = "sort -nr"           # command, save in convenience variable
     PROCINFO[command, "pty"] = 1   # update PROCINFO
     print ... |& command       # start two-way pipe
     ...

Using ptys avoids the buffer deadlock issues described earlier, at someloss in performance. If your system does not have ptys, or if all thesystem's ptys are in use,gawk automatically falls back tousing regular pipes.


Next:  ,Previous:  Two-way I/O,Up:  Advanced Features

11.4 Using gawk for Network Programming

EMISTERED:
A host is a host from coast to coast,
and no-one can talk to host that's close,
unless the host that isn't close
is busy hung or dead.

In addition to being able to open a two-way pipeline to a coprocesson the same system(seeTwo-way I/O),it is possible to make a two-way connection toanother process on another system across an IP network connection.

You can think of this as just a very long two-way pipeline toa coprocess. The waygawk decides that you want to use TCP/IP networking isby recognizing special file names that begin with one of ‘/inet/’,‘/inet4/’ or ‘/inet6’.

The full syntax of the special file name is/net-type/protocol/local-port/remote-host/remote-port. The components are:

net-type
Specifies the kind of Internet connection to make. Use ‘ /inet4/’ to force IPv4, and‘ /inet6/’ to force IPv6. Plain ‘ /inet/’ (which used to be the only option) usesthe system default, most likely IPv4.
protocol
The protocol to use over IP. This must be either ‘ tcp’, or‘ udp’, for a TCP or UDP IP connection,respectively. The use of TCP is recommended for most applications.
local-port
The local TCP or UDP port number to use. Use a port number of ‘ 0’when you want the system to pick a port. This is what you should dowhen writing a TCP or UDP client. You may also use a well-known service name, such as ‘ smtp’or ‘ http’, in which case gawk attempts to determinethe predefined port number using the C getaddrinfo() function.
remote-host
The IP address or fully-qualified domain name of the Internethost to which you want to connect.
remote-port
The TCP or UDP port number to use on the given remote-host. Again, use ‘ 0’ if you don't care, or else a well-knownservice name.

NOTE: Failure in opening a two-way socket will result in a non-fatal errorbeing returned to the calling code. The value of ERRNO indicatesthe error (see Auto-set).

Consider the following very simple example:

     BEGIN {
       Service = "/inet/tcp/0/localhost/daytime"
       Service |& getline
       print $0
       close(Service)
     }

This program reads the current date and time from the local system'sTCP ‘daytime’ server. It then prints the results and closes the connection.

Because this topic is extensive, the use of gawk forTCP/IP programming is documented separately. SeeTCP/IP Internetworking with gawk,which comes as part of thegawk distribution,for a much more complete introduction and discussion, as well asextensive examples.

11.5 Profiling Your awk Programs

You may produce executiontraces of your awk programs. This is done with a specially compiled version ofgawk,called pgawk (“profilinggawk”).

pgawk is identical in every way to gawk, except that whenit has finished running, it creates a profile of your program in a filenamedawkprof.out. Because it is profiling, it also executes up to 45% slower thangawk normally does.

As shown in the following example,the--profile option can be used to change the name of the filewherepgawk will write the profile:

     pgawk --profile=myprog.prof -f myprog.awk data1 data2

In the above example, pgawk places the profile inmyprog.prof instead of inawkprof.out.

Here is a samplesession showing a simple awk program, its input data, and theresults from runningpgawk. First, the awk program:

     BEGIN { print "First BEGIN rule" }
     
     END { print "First END rule" }
     
     /foo/ {
         print "matched /foo/, gosh"
         for (i = 1; i <= 3; i++)
             sing()
     }
     
     {
         if (/foo/)
             print "if is true"
         else
             print "else is true"
     }
     
     BEGIN { print "Second BEGIN rule" }
     
     END { print "Second END rule" }
     
     function sing(    dummy)
     {
         print "I gotta be me!"
     }

Following is the input data:

     foo
     bar
     baz
     foo
     junk

Here is the awkprof.out that results from runningpgawkon this program and data (this example also illustrates thatawkprogrammers sometimes have to work late):

             # gawk profile, created Sun Aug 13 00:00:15 2000
     
             # BEGIN block(s)
     
             BEGIN {
          1          print "First BEGIN rule"
          1          print "Second BEGIN rule"
             }
     
             # Rule(s)
     
          5  /foo/   { # 2
          2          print "matched /foo/, gosh"
          6          for (i = 1; i <= 3; i++) {
          6                  sing()
                     }
             }
     
          5  {
          5          if (/foo/) { # 2
          2                  print "if is true"
          3          } else {
          3                  print "else is true"
                     }
             }
     
             # END block(s)
     
             END {
          1          print "First END rule"
          1          print "Second END rule"
             }
     
             # Functions, listed alphabetically
     
          6  function sing(dummy)
             {
          6          print "I gotta be me!"
             }

This example illustrates many of the basic features of profiling output. They are as follows:

  • The program is printed in the order BEGIN rule,BEGINFILE rule,pattern/action rules,ENDFILE rule,END rule and functions, listedalphabetically. Multiple BEGIN andEND rules are merged together,as are multiple BEGINFILE andENDFILE rules.

  • Pattern-action rules have two counts. The first count, to the left of the rule, shows how many timesthe rule's pattern wastested. The second count, to the right of the rule's opening left bracein a comment,shows how many times the rule's action wasexecuted. The difference between the two indicates how many times the rule'spattern evaluated to false.
  • Similarly,the count for an if-else statement shows how many timesthe condition was tested. To the right of the opening left brace for theif's bodyis a count showing how many times the condition was true. The count for theelseindicates how many times the test failed.

  • The count for a loop header (such as foror while) shows how many times the loop test was executed. (Because of this, you can't just look at the count on the firststatement in a rule to determine how many times the rule was executed. If the first statement is a loop, the count is misleading.)

  • For user-defined functions, the count next to the functionkeyword indicates how many times the function was called. The counts next to the statements in the body show how many timesthose statements were executed.

  • The layout uses “K&R” style with TABs. Braces are used everywhere, even whenthe body of anif, else, or loop is only a single statement.

  • Parentheses are used only where needed, as indicated by the structureof the program and the precedence rules. For example, ‘(3 + 5) * 4’ means add three plus five, then multiplythe total by four. However, ‘3 + 5 * 4’ has no parentheses, andmeans ‘3 + (5 * 4)’.
  • Parentheses are used around the arguments to printand printf only whentheprint or printf statement is followed by a redirection. Similarly, ifthe target of a redirection isn't a scalar, it gets parenthesized.
  • pgawk supplies leading comments infront of theBEGIN and END rules,the pattern/action rules, and the functions.

The profiled version of your program may not look exactly like what youtyped when you wrote it. This is becausepgawk creates theprofiled version by “pretty printing” its internal representation ofthe program. The advantage to this is thatpgawk can producea standard representation. The disadvantage is that all source-codecomments are lost, as are the distinctions among multipleBEGIN,END, BEGINFILE, and ENDFILE rules. Also, things such as:

     /foo/

come out as:

     /foo/   {
         print $0
     }

which is correct, but possibly surprising.

Besides creating profiles when a program has completed,pgawk can produce a profile while it is running. This is useful if your awk program goes into aninfinite loop and you want to see what has been executed. To use this feature, runpgawk in the background:

     $ pgawk -f myprog &
     [1] 13992

The shell prints a job number and process ID number; in this case, 13992. Use the kill command to send the USR1 signaltopgawk:

     $ kill -USR1 13992

As usual, the profiled version of the program is written toawkprof.out, or to a different file if you use the--profileoption.

Along with the regular profile, as shown earlier, the profileincludes a trace of any active functions:

     # Function Call Stack:
     
     #   3. baz
     #   2. bar
     #   1. foo
     # -- main --

You may send pgawk the USR1 signal as many times as you like. Each time, the profile and function call trace are appended to the outputprofile file.

If you use theHUP signal instead of the USR1 signal,pgawk produces the profile and the function call trace and then exits.

Whenpgawk runs on MS-Windows systems, it uses theINT andQUIT signals for producing the profile and, inthe case of the INT signal, pgawk exits. This isbecause these systems don't support thekill command, so theonly signals you can deliver to a program are those generated by thekeyboard. TheINT signal is generated by theCtrl-<C> or Ctrl-<BREAK> key, while theQUIT signal is generated by theCtrl-<\> key.

Finally, regular gawk also accepts the--profile option. When called this way, gawk “pretty prints” the program intoawkprof.out, without any execution counts.


Next:  ,Previous:  Advanced Features,Up:  Top

12 A Library of awk Functions

User-defined, describes how to writeyour own awk functions. Writing functions is important, becauseit allows you to encapsulate algorithms and program tasks in a singleplace. It simplifies programming, making program development moremanageable, and making programs more readable.

One valuable way to learn a new programming language is to readprograms in that language. To that end, this chapterandSample Programs,provide a good-sized body of code for you to read,and hopefully, to learn from.

This chapter presents a library of useful awk functions. Many of the sample programs presented later in this Web pageuse these functions. The functions are presented here in a progression from simple to complex.

Extract Program,presents a program that you can use to extract the source code forthese example library functions and programs from the Texinfo sourcefor this Web page. (This has already been done as part of the gawk distribution.)

If you have written one or more useful, general-purpose awk functionsand would like to contribute them to theawk user community, seeHow To Contribute, for more information.

The programs in this chapter and inSample Programs,freely use features that aregawk-specific. Rewriting these programs for different implementations ofawkis pretty straightforward.

  • Diagnostic error messages are sent to /dev/stderr. Use ‘| "cat 1>&2"’ instead of ‘> "/dev/stderr"’ if your systemdoes not have a/dev/stderr, or if you cannot use gawk.
  • A number of programs use nextfile(see Nextfile Statement)to skip any remaining input in the input file.
  • Finally, some of the programs choose to ignore upper- and lowercasedistinctions in their input. They do so by assigning one to IGNORECASE. You can achieve almost the same effect63 by adding the following rule to thebeginning of the program:
              # ignore case
              { $0 = tolower($0) }
    

    Also, verify that all regexp and string constants used incomparisons use only lowercase letters.

12.1 Naming Library Function Global Variables

Due to the way the awk language evolved, variables are eitherglobal (usable by the entire program) orlocal (usable just bya specific function). There is no intermediate state analogous tostatic variables in C.

Library functions often need to have global variables that they can use topreserve state information between calls to the function—for example,getopt()'s variable_opti(see Getopt Function). Such variables are calledprivate, since the only functions that need touse them are the ones in the library.

When writing a library function, you should try to choose names for yourprivate variables that will not conflict with any variables used byeither another library function or a user's main program. For example, aname likei or j is not a good choice, because user programsoften use variable names like these for their own purposes.

The example programs shown in this chapter all start the names of theirprivate variables with an underscore (‘_’). Users generally don't useleading underscores in their variable names, so this convention immediatelydecreases the chances that the variable name will be accidentally sharedwith the user's program.

In addition, several of the library functions use a prefix that helpsindicate what function or set of functions use the variables—for example,_pw_byname in the user database routines(seePasswd Functions). This convention is recommended, since it even further decreases thechance of inadvertent conflict among variable names. Note that thisconvention is used equally well for variable names and for privatefunction names.64

As a final note on variable naming, if a function makes global variablesavailable for use by a main program, it is a good convention to start thatvariable's name with a capital letter—forexample,getopt()'s Opterr and Optind variables(seeGetopt Function). The leading capital letter indicates that it is global, while the fact thatthe variable name is not all capital letters indicates that the variable isnot one ofawk's built-in variables, such as FS.

It is also important thatall variables in libraryfunctions that do not need to save state are, in fact, declaredlocal.65 If this is not done, the variablecould accidentally be used in the user's program, leading to bugs thatare very difficult to track down:

     function lib_func(x, y,    l1, l2)
     {
         ...
         use variable some_var   # some_var should be local
         ...                     # but is not by oversight
     }

A different convention, common in the Tcl community, is to use a singleassociative array to hold the values needed by the library function(s), or“package.” This significantly decreases the number of actual global namesin use. For example, the functions described inPasswd Functions,might have used array elementsPW_data["inited"], PW_data["total"],PW_data["count"], andPW_data["awklib"], instead of_pw_inited, _pw_awklib,_pw_total,and _pw_count.

The conventions presented in this section are exactlythat: conventions. You are not required to write your programs thisway—we merely recommend that you do so.

12.2 General Programming

This section presents a number of functions that are of generalprogramming use.

12.2.1 Converting Strings To Numbers

The strtonum() function (see String Functions)is agawk extension. The following functionprovides an implementation for other versions ofawk:

     
     # mystrtonum --- convert string to number
     
     
     
     function mystrtonum(str,        ret, chars, n, i, k, c)
     {
         if (str ~ /^0[0-7]*$/) {
             # octal
             n = length(str)
             ret = 0
             for (i = 1; i <= n; i++) {
                 c = substr(str, i, 1)
                 if ((k = index("01234567", c)) > 0)
                     k-- # adjust for 1-basing in awk
     
                 ret = ret * 8 + k
             }
         } else if (str ~ /^0[xX][[:xdigit:]]+/) {
             # hexadecimal
             str = substr(str, 3)    # lop off leading 0x
             n = length(str)
             ret = 0
             for (i = 1; i <= n; i++) {
                 c = substr(str, i, 1)
                 c = tolower(c)
                 if ((k = index("0123456789", c)) > 0)
                     k-- # adjust for 1-basing in awk
                 else if ((k = index("abcdef", c)) > 0)
                     k += 9
     
                 ret = ret * 16 + k
             }
         } else if (str ~ \
       /^[-+]?([0-9]+([.][0-9]*([Ee][0-9]+)?)?|([.][0-9]+([Ee][-+]?[0-9]+)?))$/) {
             # decimal number, possibly floating point
             ret = str + 0
         } else
             ret = "NOT-A-NUMBER"
     
         return ret
     }
     
     # BEGIN {     # gawk test harness
     #     a[1] = "25"
     #     a[2] = ".31"
     #     a[3] = "0123"
     #     a[4] = "0xdeadBEEF"
     #     a[5] = "123.45"
     #     a[6] = "1.e3"
     #     a[7] = "1.32"
     #     a[7] = "1.32E2"
     #
     #     for (i = 1; i in a; i++)
     #         print a[i], strtonum(a[i]), mystrtonum(a[i])
     # }
     

The function first looks for C-style octal numbers (base 8). If the input string matches a regular expression describing octalnumbers, thenmystrtonum() loops through each character in thestring. It sets k to the index in "01234567" of the currentoctal digit. Since the return value is one-based, the ‘k--’adjustsk so it can be used in computing the return value.

Similar logic applies to the code that checks for and converts ahexadecimal value, which starts with ‘0x’ or ‘0X’. The use oftolower() simplifies the computation for findingthe correct numeric value for each hexadecimal digit.

Finally, if the string matches the (rather complicated) regexp for aregular decimal integer or floating-point number, the computation‘ret = str + 0’ letsawk convert the value to anumber.

A commented-out test program is included, so that the function canbe tested withgawk and the results compared to the built-instrtonum() function.

12.2.2 Assertions

When writing large programs, it is often useful to knowthat a condition or set of conditions is true. Before proceeding with aparticular computation, you make a statement about what you believe to bethe case. Such a statement is known as anassertion. The C language provides an <assert.h> header fileand corresponding assert() macro that the programmer can use to makeassertions. If an assertion fails, theassert() macro arranges toprint a diagnostic message describing the condition that should havebeen true but was not, and then it kills the program. In C, usingassert() looks this:

     #include <assert.h>
     
     int myfunc(int a, double b)
     {
          assert(a <= 5 && b >= 17.1);
          ...
     }

If the assertion fails, the program prints a message similar to this:

     prog.c:5: assertion failed: a <= 5 && b >= 17.1

The C language makes it possible to turn the condition into a string for usein printing the diagnostic message. This is not possible inawk, sothis assert() function also requires a string version of the conditionthat is being tested. Following is the function:

     
     # assert --- assert that a condition is true. Otherwise exit.
     
     
     
     function assert(condition, string)
     {
         if (! condition) {
             printf("%s:%d: assertion failed: %s\n",
                 FILENAME, FNR, string) > "/dev/stderr"
             _assert_exit = 1
             exit 1
         }
     }
     
     END {
         if (_assert_exit)
             exit 1
     }
     

The assert() function tests the condition parameter. If itis false, it prints a message to standard error, using thestringparameter to describe the failed condition. It then sets the variable_assert_exit to one and executes theexit statement. The exit statement jumps to the END rule. If theENDrules finds _assert_exit to be true, it exits immediately.

The purpose of the test in the END rule is tokeep any other END rules from running. When an assertion fails, theprogram should exit immediately. If no assertions fail, then_assert_exit is stillfalse when the END rule is run normally, and the rest of theprogram'sEND rules execute. For all of this to work correctly, assert.awk must be thefirst source file read byawk. The function can be used in a program in the following way:

     function myfunc(a, b)
     {
          assert(a <= 5 && b >= 17.1, "a <= 5 && b >= 17.1")
          ...
     }

If the assertion fails, you see a message similar to the following:

     mydata:1357: assertion failed: a <= 5 && b >= 17.1

There is a small problem with this version ofassert(). An END rule is automatically addedto the program callingassert(). Normally, if a program consistsof just a BEGIN rule, the input files and/or standard input arenot read. However, now that the program has anEND rule, awkattempts to read the input data files or standard input(seeUsing BEGIN/END),most likely causing the program to hang as it waits for input.

There is a simple workaround to this:make sure that such aBEGIN rule always endswith an exit statement.

12.2.3 Rounding Numbers

The way printf and sprintf()(see Printf)perform rounding often depends upon the system's Csprintf()subroutine. On many machines, sprintf() rounding is “unbiased,”which means it doesn't always round a trailing ‘.5’ up, contraryto naive expectations. In unbiased rounding, ‘.5’ rounds to even,rather than always up, so 1.5 rounds to 2 but 4.5 rounds to 4. This meansthat if you are using a format that does rounding (e.g.,"%.0f"),you should check what your system does. The following function doestraditional rounding; it might be useful if yourawk's printfdoes unbiased rounding:

     
     # round.awk --- do normal rounding
     
     
     
     function round(x,   ival, aval, fraction)
     {
        ival = int(x)    # integer part, int() truncates
     
        # see if fractional part
        if (ival == x)   # no fraction
           return ival   # ensure no decimals
     
        if (x < 0) {
           aval = -x     # absolute value
           ival = int(aval)
           fraction = aval - ival
           if (fraction >= .5)
              return int(x) - 1   # -2.5 --> -3
           else
              return int(x)       # -2.3 --> -2
        } else {
           fraction = x - ival
           if (fraction >= .5)
              return ival + 1
           else
              return ival
        }
     }
     
     
     
     # test harness
     { print $0, round($0) }
12.2.4 The Cliff Random Number Generator

TheCliff random number generatoris a very simple random number generator that “passes the noise sphere testfor randomness by showing no structure.”It is easily programmed, in less than 10 lines ofawk code:

     
     # cliff_rand.awk --- generate Cliff random numbers
     
     
     
     BEGIN { _cliff_seed = 0.1 }
     
     function cliff_rand()
     {
         _cliff_seed = (100 * log(_cliff_seed)) % 1
         if (_cliff_seed < 0)
             _cliff_seed = - _cliff_seed
         return _cliff_seed
     }
     

This algorithm requires an initial “seed” of 0.1. Each new valueuses the current seed as input for the calculation. If the built-inrand() function(see Numeric Functions)isn't random enough, you might try using this function instead.

12.2.5 Translating Between Characters and Numbers

One commercial implementation of awk supplies a built-in function,ord(), which takes a character and returns the numeric value for thatcharacter in the machine's character set. If the string passed toord() has more than one character, only the first one is used.

The inverse of this function is chr() (from the function of the samename in Pascal), which takes a number and returns the corresponding character. Both functions are written very nicely inawk; there is no realreason to build them into theawk interpreter:

     
     # ord.awk --- do ord and chr
     
     # Global identifiers:
     #    _ord_:        numerical values indexed by characters
     #    _ord_init:    function to initialize _ord_
     
     
     
     BEGIN    { _ord_init() }
     
     function _ord_init(    low, high, i, t)
     {
         low = sprintf("%c", 7) # BEL is ascii 7
         if (low == "\a") {    # regular ascii
             low = 0
             high = 127
         } else if (sprintf("%c", 128 + 7) == "\a") {
             # ascii, mark parity
             low = 128
             high = 255
         } else {        # ebcdic(!)
             low = 0
             high = 255
         }
     
         for (i = low; i <= high; i++) {
             t = sprintf("%c", i)
             _ord_[t] = i
         }
     }
     

Some explanation of the numbers used bychr is worthwhile. The most prominent character set in use today is ASCII.66Although an8-bit byte can hold 256 distinct values (from 0 to 255), ASCII onlydefines characters that use the values from 0 to 127.67In the now distant past,at least one minicomputer manufacturerused ASCII, but with mark parity, meaning that the leftmost bit in the byteis always 1. This means that on those systems, charactershave numeric values from 128 to 255. Finally, large mainframe systems use the EBCDIC character set, whichuses all 256 values. While there are other character sets in use on some older systems,they are not really worth worrying about:

     
     function ord(str,    c)
     {
         # only first character is of interest
         c = substr(str, 1, 1)
         return _ord_[c]
     }
     
     function chr(c)
     {
         # force c to be numeric by adding 0
         return sprintf("%c", c + 0)
     }
     
     
     #### test code ####
     # BEGIN    \
     # {
     #    for (;;) {
     #        printf("enter a character: ")
     #        if (getline var <= 0)
     #            break
     #        printf("ord(%s) = %d\n", var, ord(var))
     #    }
     # }
     

An obvious improvement to these functions is to move the code for the_ord_init function into the body of theBEGIN rule. It waswritten this way initially for ease of development. There is a “test program” in aBEGIN rule, to test thefunction. It is commented out for production use.

12.2.6 Merging an Array into a String

When doing string processing, it is often useful to be able to joinall the strings in an array into one long string. The following function,join(), accomplishes this task. It is used later in several ofthe application programs(seeSample Programs).

Good function design is important; this function needs to be general but itshould also have a reasonable default behavior. It is called with an arrayas well as the beginning and ending indices of the elements in the array to bemerged. This assumes that the array indices are numeric—a reasonableassumption since the array was likely created withsplit()(see String Functions):

     
     # join.awk --- join an array into a string
     
     
     
     function join(array, start, end, sep,    result, i)
     {
         if (sep == "")
            sep = " "
         else if (sep == SUBSEP) # magic value
            sep = ""
         result = array[start]
         for (i = start + 1; i <= end; i++)
             result = result sep array[i]
         return result
     }
     

An optional additional argument is the separator to use when joining thestrings back together. If the caller supplies a nonempty value,join() uses it; if it is not supplied, it has a nullvalue. In this case,join() uses a single space as a defaultseparator for the strings. If the value is equal toSUBSEP,then join() joins the strings with no separator between them.SUBSEP serves as a “magic” value to indicate that there shouldbe no separation between the component strings.68


Previous:  Join Function,Up:  General Functions

12.2.7 Managing the Time of Day

Thesystime() and strftime() functions described inTime Functions,provide the minimum functionality necessary for dealing with the time of dayin human readable form. Whilestrftime() is extensive, the controlformats are not necessarily easy to remember or intuitively obvious whenreading a program.

The following function, gettimeofday(), populates a user-supplied arraywith preformatted time information. It returns a string with the currenttime formatted in the same way as thedate utility:

     
     # gettimeofday.awk --- get the time of day in a usable format
     
     
     
     # Returns a string in the format of output of date(1)
     # Populates the array argument time with individual values:
     #    time["second"]       -- seconds (0 - 59)
     #    time["minute"]       -- minutes (0 - 59)
     #    time["hour"]         -- hours (0 - 23)
     #    time["althour"]      -- hours (0 - 12)
     #    time["monthday"]     -- day of month (1 - 31)
     #    time["month"]        -- month of year (1 - 12)
     #    time["monthname"]    -- name of the month
     #    time["shortmonth"]   -- short name of the month
     #    time["year"]         -- year modulo 100 (0 - 99)
     #    time["fullyear"]     -- full year
     #    time["weekday"]      -- day of week (Sunday = 0)
     #    time["altweekday"]   -- day of week (Monday = 0)
     #    time["dayname"]      -- name of weekday
     #    time["shortdayname"] -- short name of weekday
     #    time["yearday"]      -- day of year (0 - 365)
     #    time["timezone"]     -- abbreviation of timezone name
     #    time["ampm"]         -- AM or PM designation
     #    time["weeknum"]      -- week number, Sunday first day
     #    time["altweeknum"]   -- week number, Monday first day
     
     function gettimeofday(time,    ret, now, i)
     {
         # get time once, avoids unnecessary system calls
         now = systime()
     
         # return date(1)-style output
         ret = strftime("%a %b %e %H:%M:%S %Z %Y", now)
     
         # clear out target array
         delete time
     
         # fill in values, force numeric values to be
         # numeric by adding 0
         time["second"]       = strftime("%S", now) + 0
         time["minute"]       = strftime("%M", now) + 0
         time["hour"]         = strftime("%H", now) + 0
         time["althour"]      = strftime("%I", now) + 0
         time["monthday"]     = strftime("%d", now) + 0
         time["month"]        = strftime("%m", now) + 0
         time["monthname"]    = strftime("%B", now)
         time["shortmonth"]   = strftime("%b", now)
         time["year"]         = strftime("%y", now) + 0
         time["fullyear"]     = strftime("%Y", now) + 0
         time["weekday"]      = strftime("%w", now) + 0
         time["altweekday"]   = strftime("%u", now) + 0
         time["dayname"]      = strftime("%A", now)
         time["shortdayname"] = strftime("%a", now)
         time["yearday"]      = strftime("%j", now) + 0
         time["timezone"]     = strftime("%Z", now)
         time["ampm"]         = strftime("%p", now)
         time["weeknum"]      = strftime("%U", now) + 0
         time["altweeknum"]   = strftime("%W", now) + 0
     
         return ret
     }
     

The string indices are easier to use and read than the various formatsrequired bystrftime(). The alarm program presented inAlarm Program,uses this function. A more general design for thegettimeofday() function would haveallowed the user to supply an optional timestamp value to use insteadof the current time.

12.3 Data File Management

This section presents functions that are useful for managingcommand-line data files.

12.3.1 Noting Data File Boundaries

TheBEGIN and END rules are each executed exactly once atthe beginning and end of yourawk program, respectively(see BEGIN/END). We (the gawk authors) once had a user who mistakenly thought that theBEGIN rule is executed at the beginning of each data file and theEND rule is executed at the end of each data file.

When informedthat this was not the case, the user requested that we add new specialpatterns togawk, named BEGIN_FILE andEND_FILE, thatwould have the desired behavior. He even supplied us the code to do so.

Adding these special patterns to gawk wasn't necessary;the job can be done cleanly inawk itself, as illustratedby the following library program. It arranges to call two user-supplied functions,beginfile() andendfile(), at the beginning and end of each data file. Besides solving the problem in only nine(!) lines of code, it does soportably; this works with any implementation ofawk:

     # transfile.awk
     #
     # Give the user a hook for filename transitions
     #
     # The user must supply functions beginfile() and endfile()
     # that each take the name of the file being started or
     # finished, respectively.
     
     
     
     
     FILENAME != _oldfilename \
     {
         if (_oldfilename != "")
             endfile(_oldfilename)
         _oldfilename = FILENAME
         beginfile(FILENAME)
     }
     
     END   { endfile(FILENAME) }

This file must be loaded before the user's “main” program, so that therule it supplies is executed first.

This rule relies on awk's FILENAME variable thatautomatically changes for each new data file. The current file name issaved in a private variable,_oldfilename. If FILENAME doesnot equal _oldfilename, then a new data file is being processed andit is necessary to callendfile() for the old file. Becauseendfile() should only be called if a file has been processed, theprogram first checks to make sure that_oldfilename is not the nullstring. The program then assigns the current file name to_oldfilename and callsbeginfile() for the file. Because, like all awk variables,_oldfilename isinitialized to the null string, this rule executes correctly even for thefirst data file.

The program also supplies an END rule to do the final processing forthe last file. Because thisEND rule comes before any END rulessupplied in the “main” program,endfile() is called first. Onceagain the value of multiple BEGIN andEND rules should be clear.

If the same data file occurs twice in a row on the command line, thenendfile() and beginfile() are not executed at the end of thefirst pass and at the beginning of the second pass. The following version solves the problem:

     
     # ftrans.awk --- handle data file transitions
     #
     # user supplies beginfile() and endfile() functions
     
     
     
     FNR == 1 {
         if (_filename_ != "")
             endfile(_filename_)
         _filename_ = FILENAME
         beginfile(FILENAME)
     }
     
     END  { endfile(_filename_) }
     

Wc Program,shows how this library function can be used andhow it simplifies writing the main program.

Advanced Notes: So Why Does gawk haveBEGINFILE and ENDFILE?

You are probably wondering, if beginfile() and endfile()functions can do the job, why doesgawk haveBEGINFILE and ENDFILE patterns (see BEGINFILE/ENDFILE)?

Good question. Normally, if awk cannot open a file, thiscauses an immediate fatal error. In this case, there is no way for auser-defined function to deal with the problem, since the mechanism forcalling it relies on the file being open and at the first record. Thus,the main reason for BEGINFILE is to give you a “hook” to catchfiles that cannot be processed.ENDFILE exists for symmetry,and because it provides an easy way to do per-file cleanup processing.

12.3.2 Rereading the Current File

Another request for a new built-in function was for arewind()function that would make it possible to reread the current file. The requesting user didn't want to have to usegetline(see Getline)inside a loop.

However, as long as you are not in the END rule, it isquite easy to arrange to immediately close the current input fileand then start over with it from the top. For lack of a better name, we'll call itrewind():

     
     # rewind.awk --- rewind the current file and start over
     
     
     
     function rewind(    i)
     {
         # shift remaining arguments up
         for (i = ARGC; i > ARGIND; i--)
             ARGV[i] = ARGV[i-1]
     
         # make sure gawk knows to keep going
         ARGC++
     
         # make current file next to get done
         ARGV[ARGIND+1] = FILENAME
     
         # do it
         nextfile
     }
     

This code relies on the ARGIND variable(see Auto-set),which is specific to gawk. If you are not usinggawk, you can use ideas presented inthe previous sectionto either updateARGIND on your ownor modify this code as appropriate.

The rewind() function also relies on the nextfile keyword(seeNextfile Statement).

12.3.3 Checking for Readable Data Files

Normally, if you giveawk a data file that isn't readable,it stops with a fatal error. There are times when youmight want to just ignore such files and keep going. You cando this by prepending the following program to yourawkprogram:

     
     # readable.awk --- library file to skip over unreadable files
     
     
     
     BEGIN {
         for (i = 1; i < ARGC; i++) {
             if (ARGV[i] ~ /^[[:alpha:]_][[:alnum:]_]*=.*/ \
                 || ARGV[i] == "-" || ARGV[i] == "/dev/stdin")
                 continue    # assignment or standard input
             else if ((getline junk < ARGV[i]) < 0) # unreadable
                 delete ARGV[i]
             else
                 close(ARGV[i])
         }
     }
     

This works, because thegetline won't be fatal. Removing the element from ARGV withdeleteskips the file (since it's no longer in the list). See also ARGC and ARGV.

12.3.4 Checking For Zero-length Files

All known awk implementations silently skip over zero-length files. This is a by-product ofawk's implicitread-a-record-and-match-against-the-rules loop: whenawktries to read a record from an empty file, it immediately receives anend of file indication, closes the file, and proceeds on to the nextcommand-line data file,without executing any user-levelawk program code.

Using gawk's ARGIND variable(seeBuilt-in Variables), it is possible to detect when an emptydata file has been skipped. Similar to the library file presentedinFiletrans Function, the following library file calls a function namedzerofile() that the user must provide. The arguments passed arethe file name and the position inARGV where it was found:

     
     # zerofile.awk --- library file to process empty input files
     
     
     
     BEGIN { Argind = 0 }
     
     ARGIND > Argind + 1 {
         for (Argind++; Argind < ARGIND; Argind++)
             zerofile(ARGV[Argind], Argind)
     }
     
     ARGIND != Argind { Argind = ARGIND }
     
     END {
         if (ARGIND > Argind)
             for (Argind++; Argind <= ARGIND; Argind++)
                 zerofile(ARGV[Argind], Argind)
     }
     

The user-level variable Argind allows the awk programto track its progress throughARGV. Whenever the program detectsthat ARGIND is greater than ‘Argind + 1’, it means that one ormore empty files were skipped. The action then callszerofile() foreach such file, incrementing Argind along the way.

The ‘Argind != ARGIND’ rule simply keepsArgind up to datein the normal case.

Finally, the END rule catches the case of any empty files atthe end of the command-line arguments. Note that the test in thecondition of thefor loop uses the ‘<=’ operator,not ‘<’.

As an exercise, you might consider whether this same problem canbe solved without relying ongawk's ARGIND variable.

As a second exercise, revise this code to handle the case wherean intervening value inARGV is a variable assignment.


Previous:  Empty Files,Up:  Data File Management

12.3.5 Treating Assignments as File Names

Occasionally, you might not wantawk to process command-linevariable assignments(seeAssignment Options). In particular, if you have a file name that contain an ‘=’ character,awk treats the file name as an assignment, and does not process it.

Some users have suggested an additional command-line option for gawkto disable command-line assignments. However, some simple programming witha library file does the trick:

     
     # noassign.awk --- library file to avoid the need for a
     # special option that disables command-line assignments
     
     
     
     function disable_assigns(argc, argv,    i)
     {
         for (i = 1; i < argc; i++)
             if (argv[i] ~ /^[[:alpha:]_][[:alnum:]_]*=.*/)
                 argv[i] = ("./" argv[i])
     }
     
     BEGIN {
         if (No_command_assign)
             disable_assigns(ARGC, ARGV)
     }
     

You then run your program this way:

     awk -v No_command_assign=1 -f noassign.awk -f yourprog.awk *

The function works by looping through the arguments. It prepends ‘./’ toany argument that matches the formof a variable assignment, turning that argument into a file name.

The use of No_command_assign allows you to disable command-lineassignments at invocation time, by giving the variable a true value. When not set, it is initially zero (i.e., false), so the command-line argumentsare left alone.

12.4 Processing Command-Line Options

Most utilities on POSIX compatible systems take options onthe command line that can be used to change the way a program behaves.awk is an example of such a program(seeOptions). Often, options take arguments; i.e., data that the program needs tocorrectly obey the command-line option. For example,awk's-F option requires a string to use as the field separator. The first occurrence on the command line of either-- or astring that does not begin with ‘-’ ends the options.

Modern Unix systems provide a C function namedgetopt() for processingcommand-line arguments. The programmer provides a string describing theone-letter options. If an option requires an argument, it is followed in thestring with a colon.getopt() is also passed thecount and values of the command-line arguments and is called in a loop.getopt() processes the command-line arguments for option letters. Each time around the loop, it returns a single character representing thenext option letter that it finds, or ‘?’ if it finds an invalid option. When it returns −1, there are no options left on the command line.

When using getopt(), options that do not take arguments can begrouped together. Furthermore, options that take arguments require that theargument be present. The argument can immediately follow the option letter,or it can be a separate command-line argument.

Given a hypothetical program that takesthree command-line options, -a,-b, and -c, where-b requires an argument, all of the following are valid ways ofinvoking the program:

     prog -a -b foo -c data1 data2 data3
     prog -ac -bfoo -- data1 data2 data3
     prog -acbfoo data1 data2 data3

Notice that when the argument is grouped with its option, the rest ofthe argument is considered to be the option's argument. In this example,-acbfoo indicates that all of the-a,-b, and -c options were supplied,and that ‘foo’ is the argument to the-b option.

getopt() provides four external variables that the programmer can use:

optind
The index in the argument value array ( argv) where the firstnonoption command-line argument can be found.
optarg
The string value of the argument to an option.
opterr
Usually getopt() prints an error message when it finds an invalidoption. Setting opterr to zero disables this feature. (Anapplication might want to print its own error message.)
optopt
The letter representing the command-line option.

The following C fragment shows how getopt() might process command-linearguments forawk:

     int
     main(int argc, char *argv[])
     {
         ...
         /* print our own message */
         opterr = 0;
         while ((c = getopt(argc, argv, "v:f:F:W:")) != -1) {
             switch (c) {
             case 'f':    /* file */
                 ...
                 break;
             case 'F':    /* field separator */
                 ...
                 break;
             case 'v':    /* variable assignment */
                 ...
                 break;
             case 'W':    /* extension */
                 ...
                 break;
             case '?':
             default:
                 usage();
                 break;
             }
         }
         ...
     }

As a side point, gawk actually uses the GNUgetopt_long()function to process both normal and GNU-style long options(seeOptions).

The abstraction provided by getopt() is very useful and is quitehandy inawk programs as well. Following is an awkversion of getopt(). This function highlights one of thegreatest weaknesses inawk, which is that it is very poor atmanipulating single characters. Repeated calls tosubstr() arenecessary for accessing individual characters(see String Functions).69

The discussion that follows walks through the code a bit at a time:

     
     # getopt.awk --- Do C library getopt(3) function in awk
     
     
     
     # External variables:
     #    Optind -- index in ARGV of first nonoption argument
     #    Optarg -- string value of argument to current option
     #    Opterr -- if nonzero, print our own diagnostic
     #    Optopt -- current option letter
     
     # Returns:
     #    -1     at end of options
     #    "?"    for unrecognized option
     #    <c>    a character representing the current option
     
     # Private Data:
     #    _opti  -- index in multi-flag option, e.g., -abc
     

The function starts out with comments presentinga list of the global variables it uses,what the return values are, what they mean, and any global variables thatare “private” to this library function. Such documentation is essentialfor any program, and particularly for library functions.

The getopt() function first checks that it was indeed called witha string of options (theoptions parameter). If optionshas a zero length, getopt() immediately returns −1:

     
     function getopt(argc, argv, options,    thisopt, i)
     {
         if (length(options) == 0)    # no options given
             return -1
     
         if (argv[Optind] == "--") {  # all done
             Optind++
             _opti = 0
             return -1
         } else if (argv[Optind] !~ /^-[^:[:space:]]/) {
             _opti = 0
             return -1
         }
     

The next thing to check for is the end of the options. A --ends the command-line options, as does any command-line argument thatdoes not begin with a ‘-’.Optind is used to step throughthe array of command-line arguments; it retains its value across callstogetopt(), because it is a global variable.

The regular expression that is used, /^-[^:[:space:]/,checks for a ‘-’ followed by anythingthat is not whitespace and not a colon. If the current command-line argument does not match this pattern,it is not an option, and it ends option processing. Continuing on:

     
         if (_opti == 0)
             _opti = 2
         thisopt = substr(argv[Optind], _opti, 1)
         Optopt = thisopt
         i = index(options, thisopt)
         if (i == 0) {
             if (Opterr)
                 printf("%c -- invalid option\n",
                                       thisopt) > "/dev/stderr"
             if (_opti >= length(argv[Optind])) {
                 Optind++
                 _opti = 0
             } else
                 _opti++
             return "?"
         }
     

The _opti variable tracks the position in the current command-lineargument (argv[Optind]). If multiple options aregrouped together with one ‘-’ (e.g.,-abx), it is necessaryto return them to the user one at a time.

If _opti is equal to zero, it is set to two, which is the index inthe string of the next character to look at (we skip the ‘-’, whichis at position one). The variablethisopt holds the character,obtained with substr(). It is saved inOptopt for the mainprogram to use.

If thisopt is not in the options string, then it is aninvalid option. IfOpterr is nonzero, getopt() prints an errormessage on the standard error that is similar to the message from the Cversion ofgetopt().

Because the option is invalid, it is necessary to skip it and move on to thenext option character. If_opti is greater than or equal to thelength of the current command-line argument, it is necessary to move onto the next argument, soOptind is incremented and _opti is resetto zero. Otherwise,Optind is left alone and _opti is merelyincremented.

In any case, because the option is invalid, getopt() returns "?". The main program can examine Optopt if it needs to know what theinvalid option letter actually is. Continuing on:

     
         if (substr(options, i + 1, 1) == ":") {
             # get option argument
             if (length(substr(argv[Optind], _opti + 1)) > 0)
                 Optarg = substr(argv[Optind], _opti + 1)
             else
                 Optarg = argv[++Optind]
             _opti = 0
         } else
             Optarg = ""
     

If the option requires an argument, the option letter is followed by a colonin theoptions string. If there are remaining characters in thecurrent command-line argument (argv[Optind]), then the rest of thatstring is assigned toOptarg. Otherwise, the next command-lineargument is used (‘-xFOO’ versus ‘-x FOO’). In either case,_opti is reset to zero, because there are no more characters left toexamine in the current command-line argument. Continuing:

     
         if (_opti == 0 || _opti >= length(argv[Optind])) {
             Optind++
             _opti = 0
         } else
             _opti++
         return thisopt
     }
     

Finally, if _opti is either zero or greater than the length of thecurrent command-line argument, it means this element inargv isthrough being processed, so Optind is incremented to point to thenext element inargv. If neither condition is true, then only_opti is incremented, so that the next option letter can be processedon the next call togetopt().

The BEGIN rule initializes both Opterr and Optind to one.Opterr is set to one, since the default behavior is for getopt()to print a diagnostic message upon seeing an invalid option.Optindis set to one, since there's no reason to look at the program name, which isinARGV[0]:

     
     BEGIN {
         Opterr = 1    # default is to diagnose
         Optind = 1    # skip ARGV[0]
     
         # test program
         if (_getopt_test) {
             while ((_go_c = getopt(ARGC, ARGV, "ab:cd")) != -1)
                 printf("c = <%c>, optarg = <%s>\n",
                                            _go_c, Optarg)
             printf("non-option arguments:\n")
             for (; Optind < ARGC; Optind++)
                 printf("\tARGV[%d] = <%s>\n",
                                         Optind, ARGV[Optind])
         }
     }
     

The rest of the BEGIN rule is a simple test program. Here is theresult of two sample runs of the test program:

     $ awk -f getopt.awk -v _getopt_test=1 -- -a -cbARG bax -x
     -| c = <a>, optarg = <>
     -| c = <c>, optarg = <>
     -| c = <b>, optarg = <ARG>
     -| non-option arguments:
     -|         ARGV[3] = <bax>
     -|         ARGV[4] = <-x>
     
     $ awk -f getopt.awk -v _getopt_test=1 -- -a -x -- xyz abc
     -| c = <a>, optarg = <>
     error--> x -- invalid option
     -| c = <?>, optarg = <>
     -| non-option arguments:
     -|         ARGV[4] = <xyz>
     -|         ARGV[5] = <abc>

In both runs,the first -- terminates the arguments toawk, so that it doesnot try to interpret the-a, etc., as its own options.

NOTE: After getopt() is through, it is the responsibility of the user levelcode toclear out all the elements of ARGV from 1 to Optind,so that awk does not try to process the command-line optionsas file names.

Several of the sample programs presented inSample Programs,usegetopt() to process their arguments.

12.5 Reading the User Database

ThePROCINFO array(see Built-in Variables)provides access to the current user's real and effective user and group IDnumbers, and if available, the user's supplementary group set. However, because these are numbers, they do not provide very usefulinformation to the average user. There needs to be some way to find theuser information associated with the user and group ID numbers. Thissection presents a suite of functions for retrieving information from theuser database. See Group Functions,for a similar suite that retrieves information from the group database.

The POSIX standard does not define the file where user information iskept. Instead, it provides the<pwd.h> header fileand several C language subroutines for obtaining user information. The primary function isgetpwent(), for “get password entry.”The “password” comes from the original user database file,/etc/passwd, which stores user information, along with theencrypted passwords (hence the name).

While an awk program could simply read /etc/passwddirectly, this file may not contain complete information about thesystem's set of users.70 To be sure you are able toproduce a readable and complete version of the user database, it is necessaryto write a small C program that callsgetpwent(). getpwent()is defined as returning a pointer to astruct passwd. Each time itis called, it returns the next entry in the database. When there areno more entries, it returnsNULL, the null pointer. When thishappens, the C program should call endpwent() to close the database. Following is pwcat, a C program that “cats” the password database:

     
     /*
      * pwcat.c
      *
      * Generate a printable version of the password database
      */
     
     
     #include <stdio.h>
     #include <pwd.h>
     
     
     
     int
     main(int argc, char **argv)
     {
         struct passwd *p;
     
         while ((p = getpwent()) != NULL)
     
     
             printf("%s:%s:%ld:%ld:%s:%s:%s\n",
                 p->pw_name, p->pw_passwd, (long) p->pw_uid,
                 (long) p->pw_gid, p->pw_gecos, p->pw_dir, p->pw_shell);
     
     
     
         endpwent();
         return 0;
     }
     

If you don't understand C, don't worry about it. The output from pwcat is the user database, in the traditional/etc/passwd format of colon-separated fields. The fields are:

Login name
The user's login name.
Encrypted password
The user's encrypted password. This may not be available on some systems.
User-ID
The user's numeric user ID number. (On some systems it's a C long, and not an int. Thuswe cast it to long for all cases.)
Group-ID
The user's numeric group ID number. (Similar comments about long vs. int apply here.)
Full name
The user's full name, and perhaps other information associated with theuser.
Home directory
The user's login (or “home”) directory (familiar to shell programmers as $HOME).
Login shell
The program that is run when the user logs in. This is usually ashell, such as Bash.

A few lines representative of pwcat's output are as follows:

     $ pwcat
     -| root:3Ov02d5VaUPB6:0:1:Operator:/:/bin/sh
     -| nobody:*:65534:65534::/:
     -| daemon:*:1:1::/:
     -| sys:*:2:2::/:/bin/csh
     -| bin:*:3:3::/bin:
     -| arnold:xyzzy:2076:10:Arnold Robbins:/home/arnold:/bin/sh
     -| miriam:yxaay:112:10:Miriam Robbins:/home/miriam:/bin/sh
     -| andy:abcca2:113:10:Andy Jacobs:/home/andy:/bin/sh
     ...

With that introduction, following is a group of functions for getting userinformation. There are several functions here, corresponding to the Cfunctions of the same names:

     
     # passwd.awk --- access password file information
     
     
     
     BEGIN {
         # tailor this to suit your system
         _pw_awklib = "/usr/local/libexec/awk/"
     }
     
     function _pw_init(    oldfs, oldrs, olddol0, pwcat, using_fw, using_fpat)
     {
         if (_pw_inited)
             return
     
         oldfs = FS
         oldrs = RS
         olddol0 = $0
         using_fw = (PROCINFO["FS"] == "FIELDWIDTHS")
         using_fpat = (PROCINFO["FS"] == "FPAT")
         FS = ":"
         RS = "\n"
     
         pwcat = _pw_awklib "pwcat"
         while ((pwcat | getline) > 0) {
             _pw_byname[$1] = $0
             _pw_byuid[$3] = $0
             _pw_bycount[++_pw_total] = $0
         }
         close(pwcat)
         _pw_count = 0
         _pw_inited = 1
         FS = oldfs
         if (using_fw)
             FIELDWIDTHS = FIELDWIDTHS
         else if (using_fpat)
             FPAT = FPAT
         RS = oldrs
         $0 = olddol0
     }
     

TheBEGIN rule sets a private variable to the directory wherepwcat is stored. Because it is used to help out anawk libraryroutine, we have chosen to put it in/usr/local/libexec/awk;however, you might want it to be in a different directory on your system.

The function _pw_init() keeps three copies of the user informationin three associative arrays. The arrays are indexed by username(_pw_byname), by user ID number (_pw_byuid), and by order ofoccurrence (_pw_bycount). The variable _pw_inited is used for efficiency, since _pw_init()needs to be called only once.

Because this function usesgetline to read information frompwcat, it first saves the values ofFS, RS, and $0. It notes in the variable using_fw whether field splittingwith FIELDWIDTHS is in effect or not. Doing so is necessary, since these functions could be calledfrom anywhere within a user's program, and the user may have hisor herown way of splitting records and fields.

The using_fw variable checksPROCINFO["FS"], whichis "FIELDWIDTHS" if field splitting is being done withFIELDWIDTHS. This makes it possible to restore the correctfield-splitting mechanism later. The test can only be true forgawk. It is false if using FS or FPAT,or on some other awk implementation.

The code that checks for using FPAT, using using_fpatandPROCINFO["FS"] is similar.

The main part of the function uses a loop to read database lines, splitthe line into fields, and then store the line into each array as necessary. When the loop is done,_pw_init() cleans up by closing the pipeline,setting _pw_inited to one, and restoringFS(and FIELDWIDTHS or FPATif necessary), RS, and $0. The use of _pw_count is explained shortly.

Thegetpwnam() function takes a username as a string argument. If thatuser is in the database, it returns the appropriate line. Otherwise, itrelies on the array reference to a nonexistentelement to create the element with the null string as its value:

     
     function getpwnam(name)
     {
         _pw_init()
         return _pw_byname[name]
     }
     

Similarly,thegetpwuid function takes a user ID number argument. If thatuser number is in the database, it returns the appropriate line. Otherwise, itreturns the null string:

     
     function getpwuid(uid)
     {
         _pw_init()
         return _pw_byuid[uid]
     }
     

Thegetpwent() function simply steps through the database, one entry ata time. It uses_pw_count to track its current position in the_pw_bycount array:

     
     function getpwent()
     {
         _pw_init()
         if (_pw_count < _pw_total)
             return _pw_bycount[++_pw_count]
         return ""
     }
     

Theendpwent() function resets _pw_count to zero, so thatsubsequent calls togetpwent() start over again:

     
     function endpwent()
     {
         _pw_count = 0
     }
     

A conscious design decision in this suite is that each subroutine calls_pw_init() to initialize the database arrays. The overhead of runninga separate process to generate the user database, and the I/O to scan it,are only incurred if the user's main program actually calls one of thesefunctions. If this library file is loaded along with a user's program, butnone of the routines are ever called, then there is no extra runtime overhead. (The alternative is move the body of_pw_init() into aBEGIN rule, which always runs pwcat. This simplifies thecode but runs an extra process that may never be needed.)

In turn, calling _pw_init() is not too expensive, because the_pw_inited variable keeps the program from reading the data more thanonce. If you are worried about squeezing every last cycle out of yourawk program, the check of _pw_inited could be moved out of_pw_init() and duplicated in all the other functions. In practice,this is not necessary, since mostawk programs are I/O-bound,and such a change would clutter up the code.

The id program in Id Program,uses these functions.

12.6 Reading the Group Database

Much of the discussion presented inPasswd Functions,applies to the group database as well. Although there has traditionallybeen a well-known file (/etc/group) in a well-known format, the POSIXstandard only provides a set of C library routines(<grp.h> and getgrent())for accessing the information. Even though this file may exist, it may not havecomplete information. Therefore, as with the user database, it is necessaryto have a small C program that generates the group database as its output. grcat, a C program that “cats” the group database,is as follows:

     
     /*
      * grcat.c
      *
      * Generate a printable version of the group database
      */
     
     
     #include <stdio.h>
     #include <grp.h>
     
     int
     main(int argc, char **argv)
     {
         struct group *g;
         int i;
     
         while ((g = getgrent()) != NULL) {
     
     
             printf("%s:%s:%ld:", g->gr_name, g->gr_passwd,
                                          (long) g->gr_gid);
     
     
             for (i = 0; g->gr_mem[i] != NULL; i++) {
                 printf("%s", g->gr_mem[i]);
                 if (g->gr_mem[i+1] != NULL)
                     putchar(',');
             }
             putchar('\n');
         }
         endgrent();
         return 0;
     }
     

Each line in the group database represents one group. The fields areseparated with colons and represent the following information:

Group Name
The group's name.
Group Password
The group's encrypted password. In practice, this field is never used;it is usually empty or set to ‘ *’.
Group ID Number
The group's numeric group ID number;this number must be unique within the file. (On some systems it's a C long, and not an int. Thuswe cast it to long for all cases.)
Group Member List
A comma-separated list of user names. These users are members of the group. Modern Unix systems allow users to be members of several groupssimultaneously. If your system does, then there are elements "group1" through "group N " in PROCINFOfor those group ID numbers. (Note that PROCINFO is a gawk extension;see Built-in Variables.)

Here is what running grcat might produce:

     $ grcat
     -| wheel:*:0:arnold
     -| nogroup:*:65534:
     -| daemon:*:1:
     -| kmem:*:2:
     -| staff:*:10:arnold,miriam,andy
     -| other:*:20:
     ...

Here are the functions for obtaining information from the group database. There are several, modeled after the C library functions of the same names:

     
     # group.awk --- functions for dealing with the group file
     
     
     
     
     BEGIN    \
     {
         # Change to suit your system
         _gr_awklib = "/usr/local/libexec/awk/"
     }
     
     function _gr_init(    oldfs, oldrs, olddol0, grcat,
                                  using_fw, using_fpat, n, a, i)
     {
         if (_gr_inited)
             return
     
         oldfs = FS
         oldrs = RS
         olddol0 = $0
         using_fw = (PROCINFO["FS"] == "FIELDWIDTHS")
         using_fpat = (PROCINFO["FS"] == "FPAT")
         FS = ":"
         RS = "\n"
     
         grcat = _gr_awklib "grcat"
         while ((grcat | getline) > 0) {
             if ($1 in _gr_byname)
                 _gr_byname[$1] = _gr_byname[$1] "," $4
             else
                 _gr_byname[$1] = $0
             if ($3 in _gr_bygid)
                 _gr_bygid[$3] = _gr_bygid[$3] "," $4
             else
                 _gr_bygid[$3] = $0
     
             n = split($4, a, "[ \t]*,[ \t]*")
             for (i = 1; i <= n; i++)
                 if (a[i] in _gr_groupsbyuser)
                     _gr_groupsbyuser[a[i]] = \
                         _gr_groupsbyuser[a[i]] " " $1
                 else
                     _gr_groupsbyuser[a[i]] = $1
     
             _gr_bycount[++_gr_count] = $0
         }
         close(grcat)
         _gr_count = 0
         _gr_inited++
         FS = oldfs
         if (using_fw)
             FIELDWIDTHS = FIELDWIDTHS
         else if (using_fpat)
             FPAT = FPAT
         RS = oldrs
         $0 = olddol0
     }
     

The BEGIN rule sets a private variable to the directory wheregrcat is stored. Because it is used to help out anawk libraryroutine, we have chosen to put it in/usr/local/libexec/awk. You mightwant it to be in a different directory on your system.

These routines follow the same general outline as the user database routines(seePasswd Functions). The _gr_inited variable is used toensure that the database is scanned no more than once. The_gr_init() function first saves FS,RS, and$0, and then setsFS and RS to the correct values forscanning the group information. It also takes care to note whetherFIELDWIDTHS or FPATis being used, and to restore the appropriate field splitting mechanism.

The group information is stored is several associative arrays. The arrays are indexed by group name (_gr_byname), by group ID number(_gr_bygid), and by position in the database (_gr_bycount). There is an additional array indexed by user name (_gr_groupsbyuser),which is a space-separated list of groups to which each user belongs.

Unlike the user database, it is possible to have multiple records in thedatabase for the same group. This is common when a group has a large numberof members. A pair of such entries might look like the following:

     tvpeople:*:101:johnny,jay,arsenio
     tvpeople:*:101:david,conan,tom,joan

For this reason, _gr_init() looks to see if a group name orgroup ID number is already seen. If it is, then the user names aresimply concatenated onto the previous list of users. (There is actually asubtle problem with the code just presented. Suppose thatthe first time there were no names. This code adds the names witha leading comma. It also doesn't check that there is a$4.)

Finally, _gr_init() closes the pipeline to grcat, restoresFS (andFIELDWIDTHS or FPAT if necessary), RS, and$0,initializes _gr_count to zero(it is used later), and makes_gr_inited nonzero.

Thegetgrnam() function takes a group name as its argument, and if thatgroup exists, it is returned. Otherwise, itrelies on the array reference to a nonexistentelement to create the element with the null string as its value:

     
     function getgrnam(group)
     {
         _gr_init()
         return _gr_byname[group]
     }
     

Thegetgrgid() function is similar; it takes a numeric group ID andlooks up the information associated with that group ID:

     
     function getgrgid(gid)
     {
         _gr_init()
         return _gr_bygid[gid]
     }
     

Thegetgruser() function does not have a C counterpart. It takes auser name and returns the list of groups that have the user as a member:

     
     function getgruser(user)
     {
         _gr_init()
         return _gr_groupsbyuser[user]
     }
     

Thegetgrent() function steps through the database one entry at a time. It uses_gr_count to track its position in the list:

     
     function getgrent()
     {
         _gr_init()
         if (++_gr_count in _gr_bycount)
             return _gr_bycount[_gr_count]
         return ""
     }
     

Theendgrent() function resets _gr_count to zero so that getgrent() canstart over again:

     
     function endgrent()
     {
         _gr_count = 0
     }
     

As with the user database routines, each function calls _gr_init() toinitialize the arrays. Doing so only incurs the extra overhead of runninggrcat if these functions are used (as opposed to moving the body of_gr_init() into a BEGIN rule).

Most of the work is in scanning the database and building the variousassociative arrays. The functions that the user calls are themselves verysimple, relying onawk's associative arrays to do work.

The id program in Id Program,uses these functions.

12.7 Traversing Arrays of Arrays

Arrays of Arrays, described how gawkprovides arrays of arrays. In particular, any element ofan array may be either a scalar, or another array. Theisarray() function (seeType Functions)lets you distinguish an arrayfrom a scalar. The following function,walk_array(), recursively traversesan array, printing each element's indices and value. You call it with the array and a string representing the nameof the array:

     
     function walk_array(arr, name,      i)
     {
         for (i in arr) {
             if (isarray(arr[i]))
                 walk_array(arr[i], (name "[" i "]"))
             else
                 printf("%s[%s] = %s\n", name, i, arr[i])
         }
     }
     

It works by looping over each element of the array. If any givenelement is itself an array, the function calls itself recursively,passing the subarray and a new string representing the current index. Otherwise, the function simply prints the element's name, index, and value. Here is a main program to demonstrate:

     BEGIN {
         a[1] = 1
         a[2][1] = 21
         a[2][2] = 22
         a[3] = 3
         a[4][1][1] = 411
         a[4][2] = 42
     
         walk_array(a, "a")
     }

When run, the program produces the following output:

     $ gawk -f walk_array.awk
     -| a[4][1][1] = 411
     -| a[4][2] = 42
     -| a[1] = 1
     -| a[2][1] = 21
     -| a[2][2] = 22
     -| a[3] = 3


Next:  ,Previous:  Library Functions,Up:  Top

13 Practical awk Programs

Library Functions,presents the idea that reading programs in a language contributes tolearning that language. This chapter continues that theme,presenting a potpourri of awk programs for your readingenjoyment. There are three sections. The first describes how to run the programs presentedin this chapter.

The second presents awkversions of several common POSIX utilities. These are programs that you are hopefully already familiar with,and therefore, whose problems are understood. By reimplementing these programs inawk,you can focus on the awk-related aspects of solvingthe programming problem.

The third is a grab bag of interesting programs. These solve a number of different data-manipulation and managementproblems. Many of the programs are short, which emphasizesawk'sability to do a lot in just a few lines of code.

Many of these programs use library functions presented inLibrary Functions.


Next:  ,Up:  Sample Programs

13.1 Running the Example Programs

To run a given program, you would typically do something like this:

     awk -f program -- options files

Here, program is the name of the awk program (such ascut.awk),options are any command-line options for theprogram that start with a ‘-’, andfiles are the actual data files.

If your system supports the ‘#!’ executable interpreter mechanism(seeExecutable Scripts),you can instead run your program directly:

     cut.awk -c1-8 myfiles > results

If your awk is not gawk, you may instead need to use this:

     cut.awk -- -c1-8 myfiles > results

13.2 Reinventing Wheels for Fun and Profit

This section presents a number of POSIX utilities implemented inawk. Reinventing these programs inawk is often enjoyable,because the algorithms can be very clearly expressed, and the code is usuallyvery concise and simple. This is true becauseawk does so much for you.

It should be noted that these programs are not necessarily intended toreplace the installed versions on your system. Nor may all of these programs be fully compliant with the most recentPOSIX standard. This is not a problem; theirpurpose is to illustrateawk language programming for “real world”tasks.

The programs are presented in alphabetical order.


Next:  ,Up:  Clones

13.2.1 Cutting out Fields and Columns

Thecut utility selects, or “cuts,” characters or fieldsfrom its standard input and sends them to its standard output. Fields are separated by TABs by default,but you may supply a command-line option to change the fielddelimiter (i.e., the field-separator character). cut'sdefinition of fields is less general thanawk's.

A common use of cut might be to pull out just the login name oflogged-on users from the output ofwho. For example, the followingpipeline generates a sorted, unique list of the logged-on users:

     who | cut -c1-8 | sort | uniq

The options for cut are:

-c list
Use list as the list of characters to cut out. Items within the listmay be separated by commas, and ranges of characters can be separated withdashes. The list ‘ 1-8,15,22-35’ specifies characters 1 through8, 15, and 22 through 35.
-f list
Use list as the list of fields to cut out.
-d delim
Use delim as the field-separator character instead of the TABcharacter.
-s
Suppress printing of lines that do not contain the field delimiter.

The awk implementation of cut uses thegetopt() libraryfunction (see Getopt Function)and thejoin() library function(see Join Function).

The program begins with a comment describing the options, the libraryfunctions needed, and ausage() function that prints out a usagemessage and exits. usage() is called if invalid arguments aresupplied:

     
     # cut.awk --- implement cut in awk
     
     
     
     # Options:
     #    -f list     Cut fields
     #    -d c        Field delimiter character
     #    -c list     Cut characters
     #
     #    -s          Suppress lines without the delimiter
     #
     # Requires getopt() and join() library functions
     
     function usage(    e1, e2)
     {
         e1 = "usage: cut [-f list] [-d c] [-s] [files...]"
         e2 = "usage: cut [-c list] [files...]"
         print e1 > "/dev/stderr"
         print e2 > "/dev/stderr"
         exit 1
     }
     

The variables e1 and e2 are used so that the functionfits nicely on thepage. screen.

Next comes aBEGIN rule that parses the command-line options. It sets FS to a single TAB character, because that iscut'sdefault field separator. The rule then sets the output field separator to be thesame as the input field separator. A loop usinggetopt() stepsthrough the command-line options. Exactly one of the variablesby_fields orby_chars is set to true, to indicate thatprocessing should be done by fields or by characters, respectively. When cutting by characters, the output field separator is set to the nullstring:

     
     BEGIN    \
     {
         FS = "\t"    # default
         OFS = FS
         while ((c = getopt(ARGC, ARGV, "sf:c:d:")) != -1) {
             if (c == "f") {
                 by_fields = 1
                 fieldlist = Optarg
             } else if (c == "c") {
                 by_chars = 1
                 fieldlist = Optarg
                 OFS = ""
             } else if (c == "d") {
                 if (length(Optarg) > 1) {
                     printf("Using first character of %s" \
                            " for delimiter\n", Optarg) > "/dev/stderr"
                     Optarg = substr(Optarg, 1, 1)
                 }
                 FS = Optarg
                 OFS = FS
                 if (FS == " ")    # defeat awk semantics
                     FS = "[ ]"
             } else if (c == "s")
                 suppress++
             else
                 usage()
         }
     
         # Clear out options
         for (i = 1; i < Optind; i++)
             ARGV[i] = ""
     

The code must takespecial care when the field delimiter is a space. Usinga single space (" ") for the value ofFS isincorrect—awk would separate fields with runs of spaces,TABs, and/or newlines, and we want them to be separated with individualspaces. Also remember that aftergetopt() is through(as described in Getopt Function),we have toclear out all the elements ofARGV from 1 to Optind,so that awk does not try to process the command-line optionsas file names.

After dealing with the command-line options, the program verifies that theoptions make sense. Only one or the other of-c and -fshould be used, and both require a field list. Then the program callseitherset_fieldlist() or set_charlist() to pull apart thelist of fields or characters:

     
         if (by_fields && by_chars)
             usage()
     
         if (by_fields == 0 && by_chars == 0)
             by_fields = 1    # default
     
         if (fieldlist == "") {
             print "cut: needs list for -c or -f" > "/dev/stderr"
             exit 1
         }
     
         if (by_fields)
             set_fieldlist()
         else
             set_charlist()
     }
     

set_fieldlist() splits the field list apart at the commasinto an array. Then, for each element of the array, it looks tosee if the element is actually a range, and if so, splits it apart. The function checks the rangeto make sure that the first number is smaller than the second. Each number in the list is added to the flist array, whichsimply lists the fields that will be printed. Normal field splittingis used. The program letsawk handle the job of doing thefield splitting:

     
     function set_fieldlist(        n, m, i, j, k, f, g)
     {
         n = split(fieldlist, f, ",")
         j = 1    # index in flist
         for (i = 1; i <= n; i++) {
             if (index(f[i], "-") != 0) { # a range
                 m = split(f[i], g, "-")
                 if (m != 2 || g[1] >= g[2]) {
                     printf("bad field list: %s\n",
                                       f[i]) > "/dev/stderr"
                     exit 1
                 }
                 for (k = g[1]; k <= g[2]; k++)
                     flist[j++] = k
             } else
                 flist[j++] = f[i]
         }
         nfields = j - 1
     }
     

The set_charlist() function is more complicated thanset_fieldlist(). The idea here is to usegawk's FIELDWIDTHS variable(seeConstant Size),which describes constant-width input. When using a character list, that isexactly what we have.

Setting up FIELDWIDTHS is more complicated than simply listing thefields that need to be printed. We have to keep track of the fields toprint and also the intervening characters that have to be skipped. For example, suppose you wanted characters 1 through 8, 15, and22 through 35. You would use ‘-c 1-8,15,22-35’. The necessary valueforFIELDWIDTHS is "8 6 1 6 14". This yields fivefields, and the fields to printare$1, $3, and $5. The intermediate fields arefiller,which is stuff in between the desired data. flist lists the fields to print, andt tracks thecomplete field list, including filler fields:

     
     function set_charlist(    field, i, j, f, g, t,
                               filler, last, len)
     {
         field = 1   # count total fields
         n = split(fieldlist, f, ",")
         j = 1       # index in flist
         for (i = 1; i <= n; i++) {
             if (index(f[i], "-") != 0) { # range
                 m = split(f[i], g, "-")
                 if (m != 2 || g[1] >= g[2]) {
                     printf("bad character list: %s\n",
                                    f[i]) > "/dev/stderr"
                     exit 1
                 }
                 len = g[2] - g[1] + 1
                 if (g[1] > 1)  # compute length of filler
                     filler = g[1] - last - 1
                 else
                     filler = 0
                 if (filler)
                     t[field++] = filler
                 t[field++] = len  # length of field
                 last = g[2]
                 flist[j++] = field - 1
             } else {
                 if (f[i] > 1)
                     filler = f[i] - last - 1
                 else
                     filler = 0
                 if (filler)
                     t[field++] = filler
                 t[field++] = 1
                 last = f[i]
                 flist[j++] = field - 1
             }
         }
         FIELDWIDTHS = join(t, 1, field - 1)
         nfields = j - 1
     }
     

Next is the rule that actually processes the data. If the -s optionis given, thensuppress is true. The first if statementmakes sure that the input record does have the field separator. Ifcut is processing fields,suppress is true, and the fieldseparator character is not in the record, then the record is skipped.

If the record is valid, then gawk has split the datainto fields, either using the character inFS or using fixed-lengthfields and FIELDWIDTHS. The loop goes through the list of fieldsthat should be printed. The corresponding field is printed if it contains data. If the next field also has data, then the separator character iswritten out between the fields:

     
     {
         if (by_fields && suppress && index($0, FS) != 0)
             next
     
         for (i = 1; i <= nfields; i++) {
             if ($flist[i] != "") {
                 printf "%s", $flist[i]
                 if (i < nfields && $flist[i+1] != "")
                     printf "%s", OFS
             }
         }
         print ""
     }
     

This version of cut relies on gawk's FIELDWIDTHSvariable to do the character-based cutting. While it is possible inotherawk implementations to use substr()(seeString Functions),it is also extremely painful. TheFIELDWIDTHS variable supplies an elegant solution to the problemof picking the input line apart by characters.


Next:  ,Previous:  Cut Program,Up:  Clones

13.2.2 Searching for Regular Expressions in Files

Theegrep utility searches files for patterns. It uses regularexpressions that are almost identical to those available inawk(see Regexp). You invoke it as follows:

     egrep [ options ] 'pattern' files ...

The pattern is a regular expression. In typical usage, the regularexpression is quoted to prevent the shell from expanding any of thespecial characters as file name wildcards. Normally,egrepprints the lines that matched. If multiple file names are provided onthe command line, each output line is preceded by the name of the fileand a colon.

The options to egrep are as follows:

-c
Print out a count of the lines that matched the pattern, instead of thelines themselves.
-s
Be silent. No output is produced and the exit value indicates whetherthe pattern was matched.
-v
Invert the sense of the test. egrep prints the lines that do not match the pattern and exits successfully if the pattern is notmatched.
-i
Ignore case distinctions in both the pattern and the input data.
-l
Only print (list) the names of the files that matched, not the lines that matched.
-e pattern
Use pattern as the regexp to match. The purpose of the -eoption is to allow patterns that start with a ‘ -’.

This version uses the getopt() library function(see Getopt Function)and the file transition library program(see Filetrans Function).

The program begins with a descriptive comment and then a BEGIN rulethat processes the command-line arguments withgetopt(). The -i(ignore case) option is particularly easy withgawk; we just use theIGNORECASE built-in variable(seeBuilt-in Variables):

     
     # egrep.awk --- simulate egrep in awk
     #
     
     
     # Options:
     #    -c    count of lines
     #    -s    silent - use exit value
     #    -v    invert test, success if no match
     #    -i    ignore case
     #    -l    print filenames only
     #    -e    argument is pattern
     #
     # Requires getopt and file transition library functions
     
     BEGIN {
         while ((c = getopt(ARGC, ARGV, "ce:svil")) != -1) {
             if (c == "c")
                 count_only++
             else if (c == "s")
                 no_print++
             else if (c == "v")
                 invert++
             else if (c == "i")
                 IGNORECASE = 1
             else if (c == "l")
                 filenames_only++
             else if (c == "e")
                 pattern = Optarg
             else
                 usage()
         }
     

Next comes the code that handles the egrep-specific behavior. If nopattern is supplied with-e, the first nonoption on thecommand line is used. Theawk command-line arguments up to ARGV[Optind]are cleared, so that awk won't try to process them as files. If nofiles are specified, the standard input is used, and if multiple files arespecified, we make sure to note this so that the file names can precede thematched lines in the output:

     
         if (pattern == "")
             pattern = ARGV[Optind++]
     
         for (i = 1; i < Optind; i++)
             ARGV[i] = ""
         if (Optind >= ARGC) {
             ARGV[1] = "-"
             ARGC = 2
         } else if (ARGC - Optind > 1)
             do_filenames++
     
     #    if (IGNORECASE)
     #        pattern = tolower(pattern)
     }
     

The last two lines are commented out, since they are not needed ingawk. They should be uncommented if you have to use another versionofawk.

The next set of lines should be uncommented if you are not usinggawk. This rule translates all the characters in the input lineinto lowercase if the-i option is specified.71The rule iscommented out since it is not necessary withgawk:

     
     #{
     #    if (IGNORECASE)
     #        $0 = tolower($0)
     #}
     

The beginfile() function is called by the rule in ftrans.awkwhen each new file is processed. In this case, it is very simple; all itdoes is initialize a variablefcount to zero. fcount trackshow many lines in the current file matched the pattern. Naming the parameterjunk shows we know that beginfile()is called with a parameter, but that we're not interested in its value:

     
     function beginfile(junk)
     {
         fcount = 0
     }
     

The endfile() function is called after each file has been processed. It affects the output only when the user wants a count of the number of lines thatmatched.no_print is true only if the exit status is desired. count_only is true if line counts are desired.egreptherefore only prints line counts if printing and counting are enabled. The output format must be adjusted depending upon the number of files toprocess. Finally,fcount is added to total, so that weknow the total number of lines that matched the pattern:

     
     function endfile(file)
     {
         if (! no_print && count_only) {
             if (do_filenames)
                 print file ":" fcount
             else
                 print fcount
         }
     
         total += fcount
     }
     

The following rule does most of the work of matching lines. The variablematches is true if the line matched the pattern. If the userwants lines that did not match, the sense ofmatches is invertedusing the ‘!’ operator.fcount is incremented with the value ofmatches, which is either one or zero, depending upon asuccessful or unsuccessful match. If the line does not match, thenext statement just moves on to the next record.

A number of additional tests are made, but they are only done if weare not counting lines. First, if the user only wants exit status(no_print is true), then it is enough to know thatoneline in this file matched, and we can skip on to the next file withnextfile. Similarly, if we are only printing file names, we canprint the file name, and then skip to the next file withnextfile. Finally, each line is printed, with a leading file name and colonif necessary:

     
     {
         matches = ($0 ~ pattern)
         if (invert)
             matches = ! matches
     
         fcount += matches    # 1 or 0
     
         if (! matches)
             next
     
         if (! count_only) {
             if (no_print)
                 nextfile
     
             if (filenames_only) {
                 print FILENAME
                 nextfile
             }
     
             if (do_filenames)
                 print FILENAME ":" $0
             else
                 print
         }
     }
     

The END rule takes care of producing the correct exit status. Ifthere are no matches, the exit status is one; otherwise it is zero:

     
     END    \
     {
         if (total == 0)
             exit 1
         exit 0
     }
     

The usage() function prints a usage message in case of invalid options,and then exits:

     
     function usage(    e)
     {
         e = "Usage: egrep [-csvil] [-e pat] [files ...]"
         e = e "\n\tegrep [-csvil] pat [files ...]"
         print e > "/dev/stderr"
         exit 1
     }
     

The variable e is used so that the function fits nicelyon the printed page.

Just a note on programming style: you may have noticed that the ENDrule uses backslash continuation, with the open brace on a line byitself. This is so that it more closely resembles the way functionsare written. Many of the examplesin this chapteruse this style. You can decide for yourself if you like writingyour BEGIN andEND rules this wayor not.


Next:  ,Previous:  Egrep Program,Up:  Clones

13.2.3 Printing out User Information

Theid utility lists a user's real and effective user ID numbers,real and effective group ID numbers, and the user's group set, if any.id only prints the effective user ID and group ID if they aredifferent from the real ones. If possible,id also supplies thecorresponding user and group names. The output might look like this:

     $ id
     -| uid=500(arnold) gid=500(arnold) groups=6(disk),7(lp),19(floppy)

This information is part of what is provided bygawk'sPROCINFO array (see Built-in Variables). However, the id utility provides a more palatable output than justindividual numbers.

Here is a simple version of id written inawk. It uses the user database library functions(seePasswd Functions)and the group database library functions(seeGroup Functions):

The program is fairly straightforward. All the work is done in theBEGIN rule. The user and group ID numbers are obtained fromPROCINFO. The code is repetitive. The entry in the user database for the real user IDnumber is split into parts at the ‘:’. The name is the first field. Similar code is used for the effective user ID number and the groupnumbers:

     
     # id.awk --- implement id in awk
     #
     # Requires user and group library functions
     
     
     # output is:
     # uid=12(foo) euid=34(bar) gid=3(baz) \
     #             egid=5(blat) groups=9(nine),2(two),1(one)
     
     BEGIN    \
     {
         uid = PROCINFO["uid"]
         euid = PROCINFO["euid"]
         gid = PROCINFO["gid"]
         egid = PROCINFO["egid"]
     
         printf("uid=%d", uid)
         pw = getpwuid(uid)
         if (pw != "") {
             split(pw, a, ":")
             printf("(%s)", a[1])
         }
     
         if (euid != uid) {
             printf(" euid=%d", euid)
             pw = getpwuid(euid)
             if (pw != "") {
                 split(pw, a, ":")
                 printf("(%s)", a[1])
             }
         }
     
         printf(" gid=%d", gid)
         pw = getgrgid(gid)
         if (pw != "") {
             split(pw, a, ":")
             printf("(%s)", a[1])
         }
     
         if (egid != gid) {
             printf(" egid=%d", egid)
             pw = getgrgid(egid)
             if (pw != "") {
                 split(pw, a, ":")
                 printf("(%s)", a[1])
             }
         }
     
         for (i = 1; ("group" i) in PROCINFO; i++) {
             if (i == 1)
                 printf(" groups=")
             group = PROCINFO["group" i]
             printf("%d", group)
             pw = getgrgid(group)
             if (pw != "") {
                 split(pw, a, ":")
                 printf("(%s)", a[1])
             }
             if (("group" (i+1)) in PROCINFO)
                 printf(",")
         }
     
         print ""
     }
     

The test in the for loop is worth noting. Any supplementary groups in the PROCINFO array have theindices"group1" through "groupN" for someN, i.e., the total number of supplementary groups. However, we don't know in advance how many of these groupsthere are.

This loop works by starting at one, concatenating the value with"group", and then usingin to see if that value isin the array. Eventually, i is incremented pastthe last group in the array and the loop exits.

The loop is also correct if there are no supplementarygroups; then the condition is false the first time it'stested, and the loop body never executes.


Next:  ,Previous:  Id Program,Up:  Clones

13.2.4 Splitting a Large File into Pieces

Thesplit program splits large text files into smaller pieces. Usage is as follows:72

     split [-count] file [ prefix ]

By default,the output files are named xaa,xab, and so on. Each file has1000 lines in it, with the likely exception of the last file. To change thenumber of lines in each file, supply a number on the command linepreceded with a minus; e.g., ‘-500’ for files with 500 lines in theminstead of 1000. To change the name of the output files to something likemyfileaa,myfileab, and so on, supply an additionalargument that specifies the file name prefix.

Here is a version of split in awk. It uses theord() and chr() functions presented inOrdinal Functions.

The program first sets its defaults, and then tests to make sure there arenot too many arguments. It then looks at each argument in turn. Thefirst argument could be a minus sign followed by a number. If it is, this happensto look like a negative number, so it is made positive, and that is thecount of lines. The data file name is skipped over and the final argumentis used as the prefix for the output file names:

     
     # split.awk --- do split in awk
     #
     # Requires ord() and chr() library functions
     
     
     # usage: split [-num] [file] [outname]
     
     BEGIN {
         outfile = "x"    # default
         count = 1000
         if (ARGC > 4)
             usage()
     
         i = 1
         if (ARGV[i] ~ /^-[[:digit:]]+$/) {
             count = -ARGV[i]
             ARGV[i] = ""
             i++
         }
         # test argv in case reading from stdin instead of file
         if (i in ARGV)
             i++    # skip data file name
         if (i in ARGV) {
             outfile = ARGV[i]
             ARGV[i] = ""
         }
     
         s1 = s2 = "a"
         out = (outfile s1 s2)
     }
     

The next rule does most of the work. tcount (temporary count) trackshow many lines have been printed to the output file so far. If it is greaterthancount, it is time to close the current file and start a new one. s1 and s2 track the current suffixes for the file name. Ifthey are both ‘z’, the file is just too big. Otherwise,s1moves to the next letter in the alphabet and s2 starts over again at‘a’:

     
     {
         if (++tcount > count) {
             close(out)
             if (s2 == "z") {
                 if (s1 == "z") {
                     printf("split: %s is too large to split\n",
                            FILENAME) > "/dev/stderr"
                     exit 1
                 }
                 s1 = chr(ord(s1) + 1)
                 s2 = "a"
             }
             else
                 s2 = chr(ord(s2) + 1)
             out = (outfile s1 s2)
             tcount = 1
         }
         print > out
     }
     

The usage() function simply prints an error message and exits:

     
     function usage(   e)
     {
         e = "usage: split [-num] [file] [outname]"
         print e > "/dev/stderr"
         exit 1
     }
     

The variable e is used so that the functionfits nicely on thepage.

This program is a bit sloppy; it relies on awk to automatically close the last fileinstead of doing it in anEND rule. It also assumes that letters are contiguous in the character set,which isn't true for EBCDIC systems.


Next:  ,Previous:  Split Program,Up:  Clones

13.2.5 Duplicating Output into Multiple Files

Thetee program is known as a “pipe fitting.” tee copiesits standard input to its standard output and also duplicates it to thefiles named on the command line. Its usage is as follows:

     tee [-a] file ...

The -a option tells tee to append to the named files, instead oftruncating them and starting over.

The BEGIN rule first makes a copy of all the command-line argumentsinto an array namedcopy. ARGV[0] is not copied, since it is not needed. tee cannot use ARGV directly, since awk attempts toprocess each file name inARGV as input data.

If the first argument is -a, then the flag variableappend is set to true, and bothARGV[1] andcopy[1] are deleted. If ARGC is less than two, then nofile names were supplied andtee prints a usage message and exits. Finally, awk is forced to read the standard input by settingARGV[1] to"-" and ARGC to two:

     
     # tee.awk --- tee in awk
     #
     # Copy standard input to all named output files.
     # Append content if -a option is supplied.
     #
     
     
     BEGIN    \
     {
         for (i = 1; i < ARGC; i++)
             copy[i] = ARGV[i]
     
         if (ARGV[1] == "-a") {
             append = 1
             delete ARGV[1]
             delete copy[1]
             ARGC--
         }
         if (ARGC < 2) {
             print "usage: tee [-a] file ..." > "/dev/stderr"
             exit 1
         }
         ARGV[1] = "-"
         ARGC = 2
     }
     

The following single rule does all the work. Since there is no pattern, it isexecuted for each line of input. The body of the rule simply prints theline into each file on the command line, and then to the standard output:

     
     {
         # moving the if outside the loop makes it run faster
         if (append)
             for (i in copy)
                 print >> copy[i]
         else
             for (i in copy)
                 print > copy[i]
         print
     }
     

It is also possible to write the loop this way:

     for (i in copy)
         if (append)
             print >> copy[i]
         else
             print > copy[i]

This is more concise but it is also less efficient. The ‘if’ istested for each record and for each output file. By duplicating the loopbody, the ‘if’ is only tested once for each input record. If there areN input records and M output files, the first method onlyexecutesNif’ statements, while the second executesN*Mif’ statements.

Finally, the END rule cleans up by closing all the output files:

     
     END    \
     {
         for (i in copy)
             close(copy[i])
     }
     


Next:  ,Previous:  Tee Program,Up:  Clones

13.2.6 Printing Nonduplicated Lines of Text

Theuniq utility reads sorted lines of data on its standardinput, and by default removes duplicate lines. In other words, it onlyprints unique lines—hence the name.uniq has a number ofoptions. The usage is as follows:

     uniq [-udc [-n]] [+n] [ input file [ output file ]]

The options for uniq are:

-d
Print only repeated lines.
-u
Print only nonrepeated lines.
-c
Count lines. This option overrides -d and -u. Both repeatedand nonrepeated lines are counted.
- n
Skip n fields before comparing lines. The definition of fieldsis similar to awk's default: nonwhitespace characters separatedby runs of spaces and/or TABs.
+ n
Skip n characters before comparing lines. Any fields specified with‘ -n’ are skipped first.
input file
Data is read from the input file named on the command line, instead of fromthe standard input.
output file
The generated output is sent to the named output file, instead of to thestandard output.

Normally uniq behaves as if both the-d and-u options are provided.

uniq uses thegetopt() library function(seeGetopt Function)and the join() library function(seeJoin Function).

The program begins with a usage() function and then a brief outline ofthe options and their meanings in comments. TheBEGIN rule deals with the command-line arguments and options. Ituses a trick to getgetopt() to handle options of the form ‘-25’,treating such an option as the option letter ‘2’ with an argument of‘5’. If indeed two or more digits are supplied (Optarg lookslike a number), Optarg isconcatenated with the option digit and then the result is added to zero to makeit into a number. If there is only one digit in the option, thenOptarg is not needed. In this case,Optind must be decremented so thatgetopt() processes it next time. This code is admittedly a bittricky.

If no options are supplied, then the default is taken, to print bothrepeated and nonrepeated lines. The output file, if provided, is assignedtooutputfile. Early on, outputfile is initialized to thestandard output,/dev/stdout:

     
     # uniq.awk --- do uniq in awk
     #
     # Requires getopt() and join() library functions
     
     
     
     function usage(    e)
     {
         e = "Usage: uniq [-udc [-n]] [+n] [ in [ out ]]"
         print e > "/dev/stderr"
         exit 1
     }
     
     # -c    count lines. overrides -d and -u
     # -d    only repeated lines
     # -u    only nonrepeated lines
     # -n    skip n fields
     # +n    skip n characters, skip fields first
     
     BEGIN   \
     {
         count = 1
         outputfile = "/dev/stdout"
         opts = "udc0:1:2:3:4:5:6:7:8:9:"
         while ((c = getopt(ARGC, ARGV, opts)) != -1) {
             if (c == "u")
                 non_repeated_only++
             else if (c == "d")
                 repeated_only++
             else if (c == "c")
                 do_count++
             else if (index("0123456789", c) != 0) {
                 # getopt requires args to options
                 # this messes us up for things like -5
                 if (Optarg ~ /^[[:digit:]]+$/)
                     fcount = (c Optarg) + 0
                 else {
                     fcount = c + 0
                     Optind--
                 }
             } else
                 usage()
         }
     
         if (ARGV[Optind] ~ /^\+[[:digit:]]+$/) {
             charcount = substr(ARGV[Optind], 2) + 0
             Optind++
         }
     
         for (i = 1; i < Optind; i++)
             ARGV[i] = ""
     
         if (repeated_only == 0 && non_repeated_only == 0)
             repeated_only = non_repeated_only = 1
     
         if (ARGC - Optind == 2) {
             outputfile = ARGV[ARGC - 1]
             ARGV[ARGC - 1] = ""
         }
     }
     

The following function, are_equal(), compares the current line,$0, to theprevious line,last. It handles skipping fields and characters. If no field count and no character count are specified,are_equal()simply returns one or zero depending upon the result of a simple stringcomparison oflast and $0. Otherwise, things get morecomplicated. If fields have to be skipped, each line is broken into an array usingsplit()(seeString Functions);the desired fields are then joined back into a line usingjoin(). The joined lines are stored in clast and cline. If no fields are skipped, clast and cline are set tolast and$0, respectively. Finally, if characters are skipped, substr() is used to strip off theleadingcharcount characters in clast and cline. Thetwo strings are then compared andare_equal() returns the result:

     
     function are_equal(    n, m, clast, cline, alast, aline)
     {
         if (fcount == 0 && charcount == 0)
             return (last == $0)
     
         if (fcount > 0) {
             n = split(last, alast)
             m = split($0, aline)
             clast = join(alast, fcount+1, n)
             cline = join(aline, fcount+1, m)
         } else {
             clast = last
             cline = $0
         }
         if (charcount) {
             clast = substr(clast, charcount + 1)
             cline = substr(cline, charcount + 1)
         }
     
         return (clast == cline)
     }
     

The following two rules are the body of the program. The first one isexecuted only for the very first line of data. It setslast equal to$0, so that subsequent lines of text have something to be compared to.

The second rule does the work. The variable equal is one or zero,depending upon the results ofare_equal()'s comparison. If uniqis counting repeated lines, and the lines are equal, then it increments thecount variable. Otherwise, it prints the line and resets count,since the two lines are not equal.

If uniq is not counting, and if the lines are equal,count is incremented. Nothing is printed, since the point is to remove duplicates. Otherwise, ifuniq is counting repeated lines and more thanone line is seen, or ifuniq is counting nonrepeated linesand only one line is seen, then the line is printed, andcountis reset.

Finally, similar logic is used in the END rule to print the finalline of input data:

     
     NR == 1 {
         last = $0
         next
     }
     
     {
         equal = are_equal()
     
         if (do_count) {    # overrides -d and -u
             if (equal)
                 count++
             else {
                 printf("%4d %s\n", count, last) > outputfile
                 last = $0
                 count = 1    # reset
             }
             next
         }
     
         if (equal)
             count++
         else {
             if ((repeated_only && count > 1) ||
                 (non_repeated_only && count == 1))
                     print last > outputfile
             last = $0
             count = 1
         }
     }
     
     END {
         if (do_count)
             printf("%4d %s\n", count, last) > outputfile
         else if ((repeated_only && count > 1) ||
                 (non_repeated_only && count == 1))
             print last > outputfile
         close(outputfile)
     }
     


Previous:  Uniq Program,Up:  Clones

13.2.7 Counting Things

Thewc (word count) utility counts lines, words, and characters inone or more input files. Its usage is as follows:

     wc [-lwc] [ files ... ]

If no files are specified on the command line, wc reads its standardinput. If there are multiple files, it also prints total counts for allthe files. The options and their meanings are shown in the following list:

-l
Count only lines.
-w
Count only words. A “word” is a contiguous sequence of nonwhitespace characters, separatedby spaces and/or TABs. Luckily, this is the normal way awk separatesfields in its input data.
-c
Count only characters.

Implementing wc in awk is particularly elegant,sinceawk does a lot of the work for us; it splits lines intowords (i.e., fields) and counts them, it counts lines (i.e., records),and it can easily tell us how long a line is.

This program uses the getopt() library function(see Getopt Function)and the file-transition functions(see Filetrans Function).

This version has one notable difference from traditional versions ofwc: it always prints the counts in the order lines, words,and characters. Traditional versions note the order of the-l,-w, and-c options on the command line, and print thecounts in that order.

The BEGIN rule does the argument processing. The variableprint_total is true if more than one file is named on thecommand line:

     
     # wc.awk --- count lines, words, characters
     
     
     
     # Options:
     #    -l    only count lines
     #    -w    only count words
     #    -c    only count characters
     #
     # Default is to count lines, words, characters
     #
     # Requires getopt() and file transition library functions
     
     BEGIN {
         # let getopt() print a message about
         # invalid options. we ignore them
         while ((c = getopt(ARGC, ARGV, "lwc")) != -1) {
             if (c == "l")
                 do_lines = 1
             else if (c == "w")
                 do_words = 1
             else if (c == "c")
                 do_chars = 1
         }
         for (i = 1; i < Optind; i++)
             ARGV[i] = ""
     
         # if no options, do all
         if (! do_lines && ! do_words && ! do_chars)
             do_lines = do_words = do_chars = 1
     
         print_total = (ARGC - i > 2)
     }
     

The beginfile() function is simple; it just resets the counts of lines,words, and characters to zero, and saves the current file name infname:

     
     function beginfile(file)
     {
         lines = words = chars = 0
         fname = FILENAME
     }
     

The endfile() function adds the current file's numbers to the runningtotals of lines, words, and characters.73 It then prints out those numbersfor the file that was just read. It relies on beginfile() to reset thenumbers for the following data file:

     
     function endfile(file)
     {
         tlines += lines
         twords += words
         tchars += chars
         if (do_lines)
             printf "\t%d", lines
         if (do_words)
             printf "\t%d", words
         if (do_chars)
             printf "\t%d", chars
         printf "\t%s\n", fname
     }
     

There is one rule that is executed for each line. It adds the length ofthe record, plus one, tochars.74Adding one plus the record lengthis needed because the newline character separating records (the valueofRS) is not part of the record itself, and thus not includedin its length. Next,lines is incremented for each line read,and words is incremented by the value ofNF, which is thenumber of “words” on this line:

     
     # do per line
     {
         chars += length($0) + 1    # get newline
         lines++
         words += NF
     }
     

Finally, the END rule simply prints the totals for all the files:

     
     END {
         if (print_total) {
             if (do_lines)
                 printf "\t%d", tlines
             if (do_words)
                 printf "\t%d", twords
             if (do_chars)
                 printf "\t%d", tchars
             print "\ttotal"
         }
     }
     


Previous:  Clones,Up:  Sample Programs

13.3 A Grab Bag of awk Programs

This section is a large “grab bag” of miscellaneous programs. We hope you find them both interesting and enjoyable.

13.3.1 Finding Duplicated Words in a Document

A common error when writing large amounts of prose is to accidentallyduplicate words. Typically you will see this in text as something like “thethe program does the following...” When the text is online, oftenthe duplicated words occur at the end of one line and thebeginning ofanother, making them very difficult to spot.

This program, dupword.awk, scans through a file one line at a timeand looks for adjacent occurrences of the same word. It also saves the lastword on a line (in the variableprev) for comparison with the firstword on the next line.

The first two statements make sure that the line is all lowercase,so that, for example, “The” and “the” compare equal to each other. The next statement replaces nonalphanumeric and nonwhitespace characterswith spaces, so that punctuation does not affect the comparison either. The characters are replaced with spaces so that formatting controlsdon't create nonsense words (e.g., the Texinfo ‘@code{NF}’becomes ‘codeNF’ if punctuation is simply deleted). The record isthen resplit into fields, yielding just the actual words on the line,and ensuring that there are no empty fields.

If there are no fields left after removing all the punctuation, thecurrent record is skipped. Otherwise, the program loops through eachword, comparing it to the previous one:

     
     # dupword.awk --- find duplicate words in text
     
     
     {
         $0 = tolower($0)
         gsub(/[^[:alnum:][:blank:]]/, " ");
         $0 = $0         # re-split
         if (NF == 0)
             next
         if ($1 == prev)
             printf("%s:%d: duplicate %s\n",
                 FILENAME, FNR, $1)
         for (i = 2; i <= NF; i++)
             if ($i == $(i-1))
                 printf("%s:%d: duplicate %s\n",
                     FILENAME, FNR, $i)
         prev = $NF
     }
     
13.3.2 An Alarm Clock Program

Nothing cures insomnia like a ringing alarm clock.
Arnold Robbins

The following program is a simple “alarm clock” program. You give it a time of day and an optional message. At the specified time,it prints the message on the standard output. In addition, you can give itthe number of times to repeat the message as well as a delay betweenrepetitions.

This program uses the gettimeofday() function fromGettimeofday Function.

All the work is done in the BEGIN rule. The first part is argumentchecking and setting of defaults: the delay, the count, and the message toprint. If the user supplied a message without the ASCII BELcharacter (known as the “alert” character,"\a"), then it is added tothe message. (On many systems, printing the ASCII BEL generates anaudible alert. Thus when the alarm goes off, the system calls attentionto itself in case the user is not looking at the computer.) Just for a change, this program uses a switch statement(see Switch Statement), but the processing could be done with a series ofif-else statements instead. Here is the program:

     
     # alarm.awk --- set an alarm
     #
     # Requires gettimeofday() library function
     
     
     # usage: alarm time [ "message" [ count [ delay ] ] ]
     
     BEGIN    \
     {
         # Initial argument sanity checking
         usage1 = "usage: alarm time ['message' [count [delay]]]"
         usage2 = sprintf("\t(%s) time ::= hh:mm", ARGV[1])
     
         if (ARGC < 2) {
             print usage1 > "/dev/stderr"
             print usage2 > "/dev/stderr"
             exit 1
         }
         switch (ARGC) {
         case 5:
             delay = ARGV[4] + 0
             # fall through
         case 4:
             count = ARGV[3] + 0
             # fall through
         case 3:
             message = ARGV[2]
             break
         default:
             if (ARGV[1] !~ /[[:digit:]]?[[:digit:]]:[[:digit:]]{2}/) {
                 print usage1 > "/dev/stderr"
                 print usage2 > "/dev/stderr"
                 exit 1
             }
             break
         }
     
         # set defaults for once we reach the desired time
         if (delay == 0)
             delay = 180    # 3 minutes
         if (count == 0)
             count = 5
         if (message == "")
             message = sprintf("\aIt is now %s!\a", ARGV[1])
         else if (index(message, "\a") == 0)
             message = "\a" message "\a"
     

The next section of code turns the alarm time into hours and minutes,converts it (if necessary) to a 24-hour clock, and then turns thattime into a count of the seconds since midnight. Next it turns the currenttime into a count of seconds since midnight. The difference between the twois how long to wait before setting off the alarm:

     
         # split up alarm time
         split(ARGV[1], atime, ":")
         hour = atime[1] + 0    # force numeric
         minute = atime[2] + 0  # force numeric
     
         # get current broken down time
         gettimeofday(now)
     
         # if time given is 12-hour hours and it's after that
         # hour, e.g., `alarm 5:30' at 9 a.m. means 5:30 p.m.,
         # then add 12 to real hour
         if (hour < 12 && now["hour"] > hour)
             hour += 12
     
         # set target time in seconds since midnight
         target = (hour * 60 * 60) + (minute * 60)
     
         # get current time in seconds since midnight
         current = (now["hour"] * 60 * 60) + \
                    (now["minute"] * 60) + now["second"]
     
         # how long to sleep for
         naptime = target - current
         if (naptime <= 0) {
             print "time is in the past!" > "/dev/stderr"
             exit 1
         }
     

Finally, the program uses thesystem() function(see I/O Functions)to call thesleep utility. The sleep utility simply pausesfor the given number of seconds. If the exit status is not zero,the program assumes thatsleep was interrupted and exits. Ifsleep exited with an OK status (zero), then the program prints themessage in a loop, again usingsleep to delay for however manyseconds are necessary:

     
         # zzzzzz..... go away if interrupted
         if (system(sprintf("sleep %d", naptime)) != 0)
             exit 1
     
         # time to notify!
         command = sprintf("sleep %d", delay)
         for (i = 1; i <= count; i++) {
             print message
             # if sleep command interrupted, go away
             if (system(command) != 0)
                 break
         }
     
         exit 0
     }
     
13.3.3 Transliterating Characters

The systemtr utility transliterates characters. For example, it isoften used to map uppercase letters into lowercase for further processing:

     generate data | tr 'A-Z' 'a-z' | process data ...

tr requires two lists of characters.75 When processing the input, the first character in thefirst list is replaced with the first character in the second list,the second character in the first list is replaced with the secondcharacter in the second list, and so on. If there are more charactersin the “from” list than in the “to” list, the last character of the“to” list is used for the remaining characters in the “from” list.

Some time ago,a user proposed that a transliteration function shouldbe added togawk. The following program was written toprove that character transliteration could be done with a user-levelfunction. This program is not as complete as the systemtr utilitybut it does most of the job.

The translate program demonstrates one of the few weaknessesof standardawk: dealing with individual characters is verypainful, requiring repeated use of thesubstr(), index(),and gsub() built-in functions(seeString Functions).76There are two functions. The first,stranslate(), takes threearguments:

from
A list of characters from which to translate.
to
A list of characters to which to translate.
target
The string on which to do the translation.

Associative arrays make the translation part fairly easy. t_ar holdsthe “to” characters, indexed by the “from” characters. Then a simpleloop goes throughfrom, one character at a time. For each characterin from, if the character appears intarget,it is replaced with the corresponding to character.

The translate() function simply calls stranslate() using$0as the target. The main program sets two global variables, FROM andTO, from the command line, and then changesARGV so thatawk reads from the standard input.

Finally, the processing rule simply calls translate() for each record:

     
     # translate.awk --- do tr-like stuff
     
     
     # Bugs: does not handle things like: tr A-Z a-z, it has
     # to be spelled out. However, if `to' is shorter than `from',
     # the last character in `to' is used for the rest of `from'.
     
     function stranslate(from, to, target,     lf, lt, ltarget, t_ar, i, c,
                                                                    result)
     {
         lf = length(from)
         lt = length(to)
         ltarget = length(target)
         for (i = 1; i <= lt; i++)
             t_ar[substr(from, i, 1)] = substr(to, i, 1)
         if (lt < lf)
             for (; i <= lf; i++)
                 t_ar[substr(from, i, 1)] = substr(to, lt, 1)
         for (i = 1; i <= ltarget; i++) {
             c = substr(target, i, 1)
             if (c in t_ar)
                 c = t_ar[c]
             result = result c
         }
         return result
     }
     
     function translate(from, to)
     {
         return $0 = stranslate(from, to, $0)
     }
     
     # main program
     BEGIN {
         if (ARGC < 3) {
             print "usage: translate from to" > "/dev/stderr"
             exit
         }
         FROM = ARGV[1]
         TO = ARGV[2]
         ARGC = 2
         ARGV[1] = "-"
     }
     
     {
         translate(FROM, TO)
         print
     }
     

While it is possible to do character transliteration in a user-levelfunction, it is not necessarily efficient, and we (thegawkauthors) started to consider adding a built-in function. However,shortly after writing this program, we learned that the System V Release 4awk had added thetoupper() and tolower() functions(see String Functions). These functions handle the vast majority of thecases where character transliteration is necessary, and so we chose tosimply add those functions togawk as well and then leave wellenough alone.

An obvious improvement to this program would be to set up thet_ar array only once, in aBEGIN rule. However, thisassumes that the “from” and “to” listswill never change throughout the lifetime of the program.

13.3.4 Printing Mailing Labels

Here is a “real world”77program. Thisscript reads lists of names andaddresses and generates mailing labels. Each page of labels has 20 labelson it, two across and 10 down. The addresses are guaranteed to be no morethan five lines of data. Each address is separated from the next by a blankline.

The basic idea is to read 20 labels worth of data. Each line of each labelis stored in theline array. The single rule takes care of fillingthe line array and printing the page when 20 labels have been read.

The BEGIN rule simply sets RS to the empty string, so thatawk splits records at blank lines(seeRecords). It sets MAXLINES to 100, since 100 is the maximum numberof lines on the page (20 * 5 = 100).

Most of the work is done in the printpage() function. The label lines are stored sequentially in theline array. But theyhave to print horizontally; line[1] next toline[6],line[2] next to line[7], and so on. Two loops are used toaccomplish this. The outer loop, controlled byi, steps throughevery 10 lines of data; this is each row of labels. The inner loop,controlled byj, goes through the lines within the row. As j goes from 0 to 4, ‘i+j’ is thej-th line inthe row, and ‘i+j+5’ is the entry next to it. The output ends uplooking something like this:

     line 1          line 6
     line 2          line 7
     line 3          line 8
     line 4          line 9
     line 5          line 10
     ...

The printf format string ‘%-41s’ left-alignsthe data and prints it within a fixed-width field.

As a final note, an extra blank line is printed at lines 21 and 61, to keepthe output lined up on the labels. This is dependent on the particularbrand of labels in use when the program was written. You will also notethat there are two blank lines at the top and two blank lines at the bottom.

The END rule arranges to flush the final page of labels; there maynot have been an even multiple of 20 labels in the data:

     
     # labels.awk --- print mailing labels
     
     
     
     # Each label is 5 lines of data that may have blank lines.
     # The label sheets have 2 blank lines at the top and 2 at
     # the bottom.
     
     BEGIN    { RS = "" ; MAXLINES = 100 }
     
     function printpage(    i, j)
     {
         if (Nlines <= 0)
             return
     
         printf "\n\n"        # header
     
         for (i = 1; i <= Nlines; i += 10) {
             if (i == 21 || i == 61)
                 print ""
             for (j = 0; j < 5; j++) {
                 if (i + j > MAXLINES)
                     break
                 printf "   %-41s %s\n", line[i+j], line[i+j+5]
             }
             print ""
         }
     
         printf "\n\n"        # footer
     
         delete line
     }
     
     # main rule
     {
         if (Count >= 20) {
             printpage()
             Count = 0
             Nlines = 0
         }
         n = split($0, a, "\n")
         for (i = 1; i <= n; i++)
             line[++Nlines] = a[i]
         for (; i <= 5; i++)
             line[++Nlines] = ""
         Count++
     }
     
     END    \
     {
         printpage()
     }
     
13.3.5 Generating Word-Usage Counts

When working with large amounts of text, it can be interesting to knowhow often different words appear. For example, an author may overusecertain words, in which case she might wish to find synonyms to substitutefor words that appear too often. This subsection develops aprogram for counting words and presenting the frequency informationin a useful format.

At first glance, a program like this would seem to do the job:

     # 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 program relies on awk's default field splittingmechanism to break each line up into “words,” and uses anassociative array namedfreq, indexed by each word, to countthe number of times the word occurs. In theEND rule,it prints the counts.

This program has several problems that prevent it from beinguseful on real text files:

  • The awk language considers upper- and lowercase characters to bedistinct. Therefore, “bartender” and “Bartender” are not treatedas the same word. This is undesirable, since in normal text, wordsare capitalized if they begin sentences, and a frequency analyzer should notbe sensitive to capitalization.
  • Words are detected using the awk convention that fields areseparated just by whitespace. Other characters in the input (exceptnewlines) don't have any special meaning toawk. This means thatpunctuation characters count as part of words.
  • The output does not come out in any useful order. You're more likely to beinterested in which words occur most frequently or in having an alphabetizedtable of how frequently each word occurs.

The first problem can be solved by usingtolower() to remove casedistinctions. The second problem can be solved by usinggsub()to remove punctuation characters. Finally, we solve the third problemby using the systemsort utility to process the output of theawk script. Here is the new version of the program:

     
     # wordfreq.awk --- print list of word frequencies
     
     {
         $0 = tolower($0)    # remove case distinctions
         # remove punctuation
         gsub(/[^[:alnum:]_[:blank:]]/, "", $0)
         for (i = 1; i <= NF; i++)
             freq[$i]++
     }
     
     
     END {
         for (word in freq)
             printf "%s\t%d\n", word, freq[word]
     }

Assuming we have saved this program in a file named wordfreq.awk,and that the data is infile1, the following pipeline:

     awk -f wordfreq.awk file1 | sort -k 2nr

produces a table of the words appearing in file1 in order ofdecreasing frequency.

The awk program suitably massages thedata and produces a word frequency table, which is not ordered. Theawk script's output is then sorted by thesortutility and printed on the screen.

The options given to sortspecify a sort that uses the second field of each input line (skippingone field), that the sort keys should be treated as numeric quantities(otherwise ‘15’ would come before ‘5’), and that the sortingshould be done in descending (reverse) order.

The sort could even be done from within the program, by changingtheEND action to:

     
     END {
         sort = "sort -k 2nr"
         for (word in freq)
             printf "%s\t%d\n", word, freq[word] | sort
         close(sort)
     }
     

This way of sorting must be used on systems that do nothave true pipes at the command-line (or batch-file) level. See the general operating system documentation for more information on howto use thesort program.

13.3.6 Removing Duplicates from Unsorted Text

Theuniq program(see Uniq Program),removes duplicate lines from sorted data.

Suppose, however, you need to remove duplicate lines from a data file butthat you want to preserve the order the lines are in. A good example ofthis might be a shell history file. The history file keeps a copy of allthe commands you have entered, and it is not unusual to repeat a commandseveral times in a row. Occasionally you might want to compact the historyby removing duplicate entries. Yet it is desirable to maintain the orderof the original commands.

This simple program does the job. It uses two arrays. The dataarray is indexed by the text of each line. For each line,data[$0] is incremented. If a particular line has notbeen seen before, thendata[$0] is zero. In this case, the text of the line is stored in lines[count]. Each element of lines is a unique command, and the indices oflines indicate the order in which those lines are encountered. TheEND rule simply prints out the lines, in order:

     
     # histsort.awk --- compact a shell history file
     # Thanks to Byron Rakitzis for the general idea
     
     
     
     {
         if (data[$0]++ == 0)
             lines[++count] = $0
     }
     
     END {
         for (i = 1; i <= count; i++)
             print lines[i]
     }
     

This program also provides a foundation for generating other usefulinformation. For example, using the followingprint statement in theEND rule indicates how often a particular command is used:

     print data[lines[i]], lines[i]

This works because data[$0] is incremented each time a line isseen.

13.3.7 Extracting Programs from Texinfo Source Files

Both this chapter and the previous chapter(Library Functions)present a large number of awk programs. If you want to experiment with these programs, it is tedious to have to typethem in by hand. Here we present a program that can extract parts of aTexinfo input file into separate files.

This Web page is written in Texinfo,the GNU project's document formatting language. A single Texinfo source file can be used to produce bothprinted and online documentation. Texinfo is fully documented in the bookTexinfo—The GNU Documentation Format,available from the Free Software Foundation.

For our purposes, it is enough to know three things about Texinfo inputfiles:

  • The “at” symbol (‘@’) is special in Texinfo, much asthe backslash (‘\’) is in Corawk. Literal ‘@’ symbols are represented in Texinfo sourcefiles as ‘@@’.
  • Comments start with either ‘@c’ or ‘@comment’. The file-extraction program works by using special comments that startat the beginning of a line.
  • Lines containing ‘@group’ and ‘@end group’ commands bracketexample text that should not be split across a page boundary. (Unfortunately, TeX isn't always smart enough to do things exactly right,so we have to give it some help.)

The following program, extract.awk, reads through a Texinfo sourcefile and does two things, based on the special comments. Upon seeing ‘@c system ...’,it runs a command, by extracting the command text from thecontrol line and passing it on to the system() function(seeI/O Functions). Upon seeing ‘@c filefilename’, each subsequent line is sent tothe file filename, until ‘@c endfile’ is encountered. The rules inextract.awk match either ‘@c’ or‘@comment’ by letting the ‘omment’ part be optional. Lines containing ‘@group’ and ‘@end group’ are simply removed.extract.awk uses the join() library function(seeJoin Function).

The example programs in the online Texinfo source for GAWK: Effective AWK Programming(gawk.texi) have all been bracketed inside ‘file’ and‘endfile’ lines. The gawk distribution uses a copy ofextract.awk to extract the sample programs and install manyof them in a standard directory wheregawk can find them. The Texinfo file looks something like this:

     ...
     This program has a @code{BEGIN} rule,
     that prints a nice message:
     
     @example
     @c file examples/messages.awk
     BEGIN @{ print "Don't panic!" @}
     @c end file
     @end example
     
     It also prints some final advice:
     
     @example
     @c file examples/messages.awk
     END @{ print "Always avoid bored archeologists!" @}
     @c end file
     @end example
     ...

extract.awk begins by setting IGNORECASE to one, so thatmixed upper- and lowercase letters in the directives won't matter.

The first rule handles calling system(), checking that a command isgiven (NF is at least three) and also checking that the commandexits with a zero exit status, signifying OK:

     
     # extract.awk --- extract files and run programs
     #                 from texinfo files
     
     
     
     BEGIN    { IGNORECASE = 1 }
     
     /^@c(omment)?[ \t]+system/    \
     {
         if (NF < 3) {
             e = (FILENAME ":" FNR)
             e = (e  ": badly formed `system' line")
             print e > "/dev/stderr"
             next
         }
         $1 = ""
         $2 = ""
         stat = system($0)
         if (stat != 0) {
             e = (FILENAME ":" FNR)
             e = (e ": warning: system returned " stat)
             print e > "/dev/stderr"
         }
     }
     

The variable e is used so that the rulefits nicely on thepage. screen.

The second rule handles moving data into files. It verifies that afile name is given in the directive. If the file named is not thecurrent file, then the current file is closed. Keeping the current fileopen until a new file is encountered allows the use of the ‘>’redirection for printing the contents, keeping open file managementsimple.

The for loop does the work. It reads lines using getline(seeGetline). For an unexpected end of file, it calls the unexpected_eof()function. If the line is an “endfile” line, then it breaks out ofthe loop. If the line is an ‘@group’ or ‘@end group’ line, then itignores it and goes on to the next line. Similarly, comments within examples are also ignored.

Most of the work is in the following few lines. If the line has no ‘@’symbols, the program can print it directly. Otherwise, each leading ‘@’ must be stripped off. To remove the ‘@’ symbols, the line is split into separate elements ofthe arraya, using the split() function(see String Functions). The ‘@’ symbol is used as the separator character. Each element ofa that is empty indicates two successive ‘@’symbols in the original line. For each two empty elements (‘@@’ inthe original file), we have to add a single ‘@’ symbol backin.78

When the processing of the array is finished, join() is called with thevalue ofSUBSEP, to rejoin the pieces back into a singleline. That line is then printed to the output file:

     
     /^@c(omment)?[ \t]+file/    \
     {
         if (NF != 3) {
             e = (FILENAME ":" FNR ": badly formed `file' line")
             print e > "/dev/stderr"
             next
         }
         if ($3 != curfile) {
             if (curfile != "")
                 close(curfile)
             curfile = $3
         }
     
         for (;;) {
             if ((getline line) <= 0)
                 unexpected_eof()
             if (line ~ /^@c(omment)?[ \t]+endfile/)
                 break
             else if (line ~ /^@(end[ \t]+)?group/)
                 continue
             else if (line ~ /^@c(omment+)?[ \t]+/)
                 continue
             if (index(line, "@") == 0) {
                 print line > curfile
                 continue
             }
             n = split(line, a, "@")
             # if a[1] == "", means leading @,
             # don't add one back in.
             for (i = 2; i <= n; i++) {
                 if (a[i] == "") { # was an @@
                     a[i] = "@"
                     if (a[i+1] == "")
                         i++
                 }
             }
             print join(a, 1, n, SUBSEP) > curfile
         }
     }
     

An important thing to note is the use of the ‘>’ redirection. Output done with ‘>’ only opens the file once; it stays open andsubsequent output is appended to the file(seeRedirection). This makes it easy to mix program text and explanatory prose for the samesample source file (as has been done here!) without any hassle. The file isonly closed when a new data file name is encountered or at the end of theinput file.

Finally, the function unexpected_eof() prints an appropriateerror message and then exits. TheEND rule handles the final cleanup, closing the open file:

     
     function unexpected_eof()
     {
         printf("%s:%d: unexpected EOF or error\n",
             FILENAME, FNR) > "/dev/stderr"
         exit 1
     }
     
     END {
         if (curfile)
             close(curfile)
     }
     
13.3.8 A Simple Stream Editor

Thesed utility is a stream editor, a program that reads astream of data, makes changes to it, and passes it on. It is often used to make global changes to a large file or to a streamof data generated by a pipeline of commands. While sed is a complicated program in its own right, its most commonuse is to perform global substitutions in the middle of a pipeline:

     command1 < orig.data | sed 's/old/new/g' | command2 > result

Here, ‘s/old/new/g’ tells sed to look for the regexp‘old’ on each input line and globally replace it with the text‘new’, i.e., all the occurrences on a line. This is similar toawk'sgsub() function(see String Functions).

The following program, awksed.awk, accepts at least two command-linearguments: the pattern to look for and the text to replace it with. Anyadditional arguments are treated as data file names to process. If noneare provided, the standard input is used:

     
     # awksed.awk --- do s/foo/bar/g using just print
     #    Thanks to Michael Brennan for the idea
     
     
     
     function usage()
     {
         print "usage: awksed pat repl [files...]" > "/dev/stderr"
         exit 1
     }
     
     BEGIN {
         # validate arguments
         if (ARGC < 3)
             usage()
     
         RS = ARGV[1]
         ORS = ARGV[2]
     
         # don't use arguments as files
         ARGV[1] = ARGV[2] = ""
     }
     
     # look ma, no hands!
     {
         if (RT == "")
             printf "%s", $0
         else
             print
     }
     

The program relies on gawk's ability to haveRS be a regexp,as well as on the setting of RT to the actual text that terminates therecord (seeRecords).

The idea is to have RS be the pattern to look for. gawkautomatically sets$0 to the text between matches of the pattern. This is text that we want to keep, unmodified. Then, by settingORSto the replacement text, a simple print statement outputs thetext we want to keep, followed by the replacement text.

There is one wrinkle to this scheme, which is what to do if the last recorddoesn't end with text that matchesRS. Using a printstatement unconditionally prints the replacement text, which is not correct. However, if the file did not end in text that matchesRS, RTis set to the null string. In this case, we can print$0 usingprintf(see Printf).

The BEGIN rule handles the setup, checking for the right numberof arguments and callingusage() if there is a problem. Then it setsRS and ORS from the command-line arguments and setsARGV[1] and ARGV[2] to the null string, so that they arenot treated as file names(see ARGC and ARGV).

The usage() function prints an error message and exits. Finally, the single rule handles the printing scheme outlined above,usingprint or printf as appropriate, depending upon thevalue ofRT.

13.3.9 An Easy Way to Use Library Functions

InInclude Files, we saw how gawk provides a built-infile-inclusion capability. However, this is agawk extension. This section provides the motivation for making file inclusionavailable for standardawk, and shows how to do it using acombination of shell andawk programming.

Using library functions in awk can be very beneficial. Itencourages code reuse and the writing of general functions. Programs aresmaller and therefore clearer. However, using library functions is only easy when writingawkprograms; it is painful when running them, requiring multiple-foptions. If gawk is unavailable, then so too is theAWKPATHenvironment variable and the ability to putawk functions into alibrary directory (seeOptions). It would be nice to be able to write programs in the following manner:

     # library functions
     @include getopt.awk
     @include join.awk
     ...
     
     # main program
     BEGIN {
         while ((c = getopt(ARGC, ARGV, "a:b:cde")) != -1)
             ...
         ...
     }

The following program, igawk.sh, provides this service. It simulatesgawk's searching of the AWKPATH variableand also allowsnested includes; i.e., a file that is includedwith ‘@include’ can contain further ‘@include’ statements.igawk makes an effort to only include files once, so that nestedincludes don't accidentally include a library function twice.

igawk should behave just like gawk externally. Thismeans it should accept all ofgawk's command-line arguments,including the ability to have multiple source files specified via-f, and the ability to mix command-line and library source files.

The program is written using the POSIX Shell (sh) commandlanguage.79 It works as follows:

  1. Loop through the arguments, saving anything that doesn't representawk source code for later, when the expanded program is run.
  2. For any arguments that do represent awk text, put the arguments intoa shell variable that will be expanded. There are two cases:
    1. Literal text, provided with --source or--source=. Thistext is just appended directly.
    2. Source file names, provided with -f. We use a neat trick and append‘@includefilename’ to the shell variable's contents. Since the file-inclusionprogram works the waygawk does, this gets the textof the file included into the program at the correct point.
  3. Run an awk program (naturally) over the shell variable's contents to expand‘@include’ statements. The expanded program is placed in a secondshell variable.
  4. Run the expanded program with gawk and any other original command-linearguments that the user supplied (such as the data file names).

This program uses shell variables extensively: for storing command-line arguments,the text of theawk program that will expand the user's program, for theuser's original program, and for the expanded program. Doing so removes somepotential problems that might arise were we to use temporary files instead,at the cost of making the script somewhat more complicated.

The initial part of the program turns on shell tracing if the firstargument is ‘debug’.

The next part loops through all the command-line arguments. There are several cases of interest:

--
This ends the arguments to igawk. Anything else should be passed onto the user's awk program without being evaluated.
-W
This indicates that the next option is specific to gawk. To makeargument processing easier, the -W is appended to the front of theremaining arguments and the loop continues. (This is an shprogramming trick. Don't worry about it if you are not familiar with sh.)
-v , -F
These are saved and passed on to gawk.
-f , --file , --file= , -Wfile=
The file name is appended to the shell variable program with an‘ @include’ statement. The expr utility is used to remove the leading option part of theargument (e.g., ‘ --file=’). (Typical sh usage would be to use the echo and sedutilities to do this work. Unfortunately, some versions of echo evaluateescape sequences in their arguments, possibly mangling the program text. Using expr avoids this problem.)
--source , --source= , -Wsource=
The source text is appended to program.
--version , -Wversion
igawk prints its version number, runs ‘ gawk --version’to get the gawk version information, and then exits.

If none of the -f, --file,-Wfile, --source,or-Wsource arguments are supplied, then the first nonoption argumentshould be theawk program. If there are no command-linearguments left,igawk prints an error message and exits. Otherwise, the first argument is appended toprogram. In any case, after the arguments have been processed,program contains the complete text of the originalawkprogram.

The program is as follows:

     
     #! /bin/sh
     # igawk --- like gawk but do @include processing
     
     
     
     if [ "$1" = debug ]
     then
         set -x
         shift
     fi
     
     # A literal newline, so that program text is formatted correctly
     n='
     '
     
     # Initialize variables to empty
     program=
     opts=
     
     while [ $# -ne 0 ] # loop over arguments
     do
         case $1 in
         --)     shift
                 break ;;
     
         -W)     shift
                 # The ${x?'message here'} construct prints a
                 # diagnostic if $x is the null string
                 set -- -W"${@?'missing operand'}"
                 continue ;;
     
         -[vF])  opts="$opts $1 '${2?'missing operand'}'"
                 shift ;;
     
         -[vF]*) opts="$opts '$1'" ;;
     
         -f)     program="$program$n@include ${2?'missing operand'}"
                 shift ;;
     
         -f*)    f=$(expr "$1" : '-f\(.*\)')
                 program="$program$n@include $f" ;;
     
         -[W-]file=*)
                 f=$(expr "$1" : '-.file=\(.*\)')
                 program="$program$n@include $f" ;;
     
         -[W-]file)
                 program="$program$n@include ${2?'missing operand'}"
                 shift ;;
     
         -[W-]source=*)
                 t=$(expr "$1" : '-.source=\(.*\)')
                 program="$program$n$t" ;;
     
         -[W-]source)
                 program="$program$n${2?'missing operand'}"
                 shift ;;
     
         -[W-]version)
                 echo igawk: version 3.0 1>&2
                 gawk --version
                 exit 0 ;;
     
         -[W-]*) opts="$opts '$1'" ;;
     
         *)      break ;;
         esac
         shift
     done
     
     if [ -z "$program" ]
     then
          program=${1?'missing program'}
          shift
     fi
     
     # At this point, `program' has the program.
     

The awk program to process ‘@include’ directivesis stored in the shell variableexpand_prog. Doing this keepsthe shell script readable. The awk programreads through the user's program, one line at a time, usinggetline(see Getline). The inputfile names and ‘@include’ statements are managed using a stack. As each ‘@include’ is encountered, the current file name is“pushed” onto the stack and the file named in the ‘@include’directive becomes the current file name. As each file is finished,the stack is “popped,” and the previous input file becomes the currentinput file again. The process is started by making the original filethe first one on the stack.

The pathto() function does the work of finding the full path toa file. It simulatesgawk's behavior when searching theAWKPATH environment variable(seeAWKPATH Variable). If a file name has a ‘/’ in it, no path search is done. Similarly, if the file name is"-", then that string isused as-is. Otherwise,the file name is concatenated with the name of each directory inthe path, and an attempt is made to open the generated file name. The only way to test if a file can be read inawk is to goahead and try to read it withgetline; this is what pathto()does.80 If the file can be read, it is closed and the file nameis returned:

     
     expand_prog='
     
     function pathto(file,    i, t, junk)
     {
         if (index(file, "/") != 0)
             return file
     
         if (file == "-")
             return file
     
         for (i = 1; i <= ndirs; i++) {
             t = (pathlist[i] "/" file)
             if ((getline junk < t) > 0) {
                 # found it
                 close(t)
                 return t
             }
         }
         return ""
     }
     

The main program is contained inside one BEGIN rule. The first thing itdoes is set up thepathlist array that pathto() uses. Aftersplitting the path on ‘:’, null elements are replaced with".",which represents the current directory:

     
     BEGIN {
         path = ENVIRON["AWKPATH"]
         ndirs = split(path, pathlist, ":")
         for (i = 1; i <= ndirs; i++) {
             if (pathlist[i] == "")
                 pathlist[i] = "."
         }
     

The stack is initialized with ARGV[1], which will be /dev/stdin. The main loop comes next. Input lines are read in succession. Lines thatdo not start with ‘@include’ are printed verbatim. If the line does start with ‘@include’, the file name is in$2. pathto() is called to generate the full path. If it cannot, then the programprints an error message and continues.

The next thing to check is if the file is included already. Theprocessed array is indexed by the full file name of each includedfile and it tracks this information for us. If the file isseen again, a warning message is printed. Otherwise, the new file name ispushed onto the stack and processing continues.

Finally, when getline encounters the end of the input file, the fileis closed and the stack is popped. Whenstackptr is less than zero,the program is done:

     
         stackptr = 0
         input[stackptr] = ARGV[1] # ARGV[1] is first file
     
         for (; stackptr >= 0; stackptr--) {
             while ((getline < input[stackptr]) > 0) {
                 if (tolower($1) != "@include") {
                     print
                     continue
                 }
                 fpath = pathto($2)
                 if (fpath == "") {
                     printf("igawk:%s:%d: cannot find %s\n",
                         input[stackptr], FNR, $2) > "/dev/stderr"
                     continue
                 }
                 if (! (fpath in processed)) {
                     processed[fpath] = input[stackptr]
                     input[++stackptr] = fpath  # push onto stack
                 } else
                     print $2, "included in", input[stackptr],
                         "already included in",
                         processed[fpath] > "/dev/stderr"
             }
             close(input[stackptr])
         }
     }'  # close quote ends `expand_prog' variable
     
     processed_program=$(gawk -- "$expand_prog" /dev/stdin << EOF
     $program
     EOF
     )
     

The shell construct ‘command << marker’ is called ahere document. Everything in the shell script up to the marker is fed tocommand as input. The shell processes the contents of the here document for variable and command substitution(and possibly other things as well, depending upon the shell).

The shell construct ‘$(...)’ is called command substitution. The output of the command inside the parentheses is substitutedinto the command line. Because the result is used in a variable assignment,it is saved as a single string, even if the results contain whitespace.

The expanded program is saved in the variable processed_program. It's done in these steps:

  1. Run gawk with the ‘@include’-processing program (thevalue of theexpand_prog shell variable) on standard input.
  2. Standard input is the contents of the user's program, from the shell variableprogram. Its contents are fed to gawk via a here document.
  3. The results of this processing are saved in the shell variable processed_program by using command substitution.

The last step is to call gawk with the expanded program,along with the originaloptions and command-line arguments that the user supplied.

     
     eval gawk $opts -- '"$processed_program"' '"$@"'
     

The eval command is a shell construct that reruns the shell's parsingprocess. This keeps things properly quoted.

This version of igawk represents my fifth version of this program. There are four key simplifications that make the program work better:

  • Using ‘@include’ even for the files named with-f makes buildingthe initial collected awk program much simpler; all the‘@include’ processing can be done once.
  • Not trying to save the line read with getlinein the pathto() function when testing for thefile's accessibility for use with the main program simplifies thingsconsiderably.
  • Using a getline loop in the BEGIN rule does it all in oneplace. It is not necessary to call out to a separate loop for processingnested ‘@include’ statements.
  • Instead of saving the expanded program in a temporary file, putting it in a shell variableavoids some potential security problems. This has the disadvantage that the script relies upon more featuresof thesh language, making it harder to follow for those whoaren't familiar withsh.

Also, this program illustrates that it is often worthwhile to combinesh andawk programming together. You can usuallyaccomplish quite a lot, without having to resort to low-level programmingin C or C++, and it is frequently easier to do certain kinds of stringand argument manipulation using the shell than it is in awk.

Finally, igawk shows that it is not always necessary to add newfeatures to a program; they can often be layered on top.

As an additional example of this, consider the idea of having twofiles in a directory in the search path:

default.awk
This file contains a set of default library functions, suchas getopt() and assert().
site.awk
This file contains library functions that are specific to a site orinstallation; i.e., locally developed functions. Having a separate file allows default.awk to change withnew gawk releases, without requiring the system administrator toupdate it each time by adding the local functions.

One usersuggested that gawk be modified to automatically read these filesupon startup. Instead, it would be very simple to modifyigawkto do this. Since igawk can process nested ‘@include’directives,default.awk could simply contain ‘@include’statements for the desired library functions.

13.3.10 Finding Anagrams From A Dictionary

An interesting programming challenge is tosearch for anagrams in aword list (such as/usr/share/dict/words on many GNU/Linux systems). One word is an anagram of another if both words containthe same letters(for example, “babbling” and “blabbing”).

An elegant algorithm is presented in Column 2, Problem C ofJon Bentley's Programming Pearls, second edition. The idea is to give words that are anagrams a common signature,sort all the words together by their signature, and then print them. Dr. Bentley observes that taking the letters in each word andsorting them produces that common signature.

The following program uses arrays of arrays to bring togetherwords with the same signature and array sorting to print the wordsin sorted order.

     
     # anagram.awk --- An implementation of the anagram finding algorithm
     #                 from Jon Bentley's "Programming Pearls", 2nd edition.
     #                 Addison Wesley, 2000, ISBN 0-201-65788-0.
     #                 Column 2, Problem C, section 2.8, pp 18-20.
     
     
     
     /'s$/   { next }        # Skip possessives
     

The program starts with a header, and then a rule to skippossessives in the dictionary file. The next rule buildsup the data structure. The first dimension of the arrayis indexed by the signature; the second dimension is the worditself:

     
     {
         key = word2key($1)  # Build signature
         data[key][$1] = $1  # Store word with signature
     }
     

The word2key() function creates the signature. It splits the word apart into individual letters,sorts the letters, and then joins them back together:

     
     # word2key --- split word apart into letters, sort, joining back together
     
     function word2key(word,     a, i, n, result)
     {
         n = split(word, a, "")
         asort(a)
     
         for (i = 1; i <= n; i++)
             result = result a[i]
     
         return result
     }
     

Finally, the END rule traverses the arrayand prints out the anagram lists. It sends the outputto the systemsort command, since otherwisethe anagrams would appear in arbitrary order:

     
     END {
         sort = "sort"
         for (key in data) {
             # Sort words with same key
             nwords = asorti(data[key], words)
             if (nwords == 1)
                 continue
     
             # And print. Minor glitch: trailing space at end of each line
             for (j = 1; j <= nwords; j++)
                 printf("%s ", words[j]) | sort
             print "" | sort
         }
         close(sort)
     }
     

Here is some partial output when the program is run:

     $ gawk -f anagram.awk /usr/share/dict/words | grep '^b'
     ...
     babbled blabbed
     babbler blabber brabble
     babblers blabbers brabbles
     babbling blabbing
     babbly blabby
     babel bable
     babels beslab
     babery yabber
     ...
13.3.11 And Now For Something Completely Different

The following program was written by Davide Briniand is published on his website. It serves as his signature in the Usenet group comp.lang.awk. He supplies the following copyright terms:

Copyright © 2008 Davide Brini

Copying and distribution of the code published in this page, with or withoutmodification, are permitted in any medium without royalty provided the copyrightnotice and this notice are preserved.

Here is the program:

     awk 'BEGIN{O="~"~"~";o="=="=="==";o+=+o;x=O""O;while(X++<=x+o+o)c=c"%c";
     printf c,(x-O)*(x-O),x*(x-o)-o,x*(x-O)+x-O-o,+x*(x-O)-x+o,X*(o*o+O)+x-O,
     X*(X-x)-o*o,(x+X)*o*o+o,x*(X-x)-O-O,x-O+(O+o+X+x)*(o+O),X*X-X*(x-O)-x+O,
     O+X*(o*(o+O)+O),+x+O+X*o,x*(x-o),(o+X+x)*o*o-(x-O-O),O+(X-x)*(X+O),x-O}'

We leave it to you to determine what the program does.


Next:  ,Previous:  Sample Programs,Up:  Top

14 dgawk: The awk Debugger

It would be nice if computer programs worked perfectly the first time theywere run, but in real life, this rarely happens for programs ofany complexity. Thus, most programming languages have facilities availablefor “debugging” programs, and now awk is no exception.

The dgawk debugger is purposely modeled afterthe GNU Debugger (GDB)command-line debugger. If you are familiar with GDB, learningdgawk is easy.

14.1 Introduction to dgawk

This section introduces debugging in general and beginsthe discussion of debugging ingawk.


Next:  ,Up:  Debugging

14.1.1 Debugging In General

(If you have used debuggers in other languages, you may want to skipahead to the next section on the specific features of theawkdebugger.)

Of course, a debugging program cannot remove bugs for you, since it hasno way of knowing what you or your users consider a “bug” and what is a“feature.” (Sometimes, we humans have a hard time with this ourselves.) In that case, what can you expect from such a tool? The answer to thatdepends on the language being debugged, but in general, you can expect atleast the following:

  • The ability to watch a program execute its instructions one by one,giving you, the programmer, the opportunity to think about what is happeningon a time scale of seconds, minutes, or hours, rather than the nanosecondtime scale at which the code usually runs.
  • The opportunity to not only passively observe the operation of yourprogram, but to control it and try different paths of execution, withouthaving to change your source files.
  • The chance to see the values of data in the program at any point inexecution, and also to change that data on the fly, to see how thataffects what happens afterwards. (This often includes the abilityto look at internal data structures besides the variables you actuallydefined in your code.)
  • The ability to obtain additional information about your program's stateor even its internal structure.

All of these tools provide a great amount of help in using your ownskills and understanding of the goals of your program to find where itis going wrong (or, for that matter, to better comprehend a perfectlyfunctional program that you or someone else wrote).


Next:  ,Previous:  Debugging Concepts,Up:  Debugging

14.1.2 Additional Debugging Concepts

Before diving in to the details, we need to introduce severalimportant concepts that apply to just about all debuggers, includingdgawk. The following list defines terms used throughout the rest ofthis chapter.

Stack Frame
Programs generally call functions during the course of their execution. One function can call another, or a function can call itself (recursion). You can view the chain of called functions (main program calls A, whichcalls B, which calls C), as a stack of executing functions: the currentlyrunning function is the topmost one on the stack, and when it finishes(returns), the next one down then becomes the active function. Such a stack is termed a call stack.

For each function on the call stack, the system maintains a data areathat contains the function's parameters, local variables, and return value,as well as any other “bookkeeping” information needed to manage thecall stack. This data area is termed astack frame.

gawk also follows this model, and dgawk gives youaccess to the call stack and to each stack frame. You can see thecall stack, as well as from where each function on the stack wasinvoked. Commands that print the call stack print information abouteach stack frame (as detailed later on).

Breakpoint
During debugging, you often wish to let the program run until itreaches a certain point, and then continue execution from there onestatement (or instruction) at a time. The way to do this is to seta breakpoint within the program. A breakpoint is where theexecution of the program should break off (stop), so that you cantake over control of the program's execution. You can add and removeas many breakpoints as you like.
Watchpoint
A watchpoint is similar to a breakpoint. The difference is thatbreakpoints are oriented around the code: stop when a certain point in thecode is reached. A watchpoint, however, specifies that program executionshould stop when a data value is changed. This is useful, sincesometimes it happens that a variable receives an erroneous value, and it'shard to track down where this happens just by looking at the code. By using a watchpoint, you can stop whenever a variable is assigned to,and usually find the errant code quite quickly.


Previous:  Debugging Terms,Up:  Debugging

14.1.3 Awk Debugging

Debugging an awk program has some specific aspects that arenot shared with other programming languages.

First of all, the fact that awk programs usually take inputline-by-line from a file or files and operate on those lines using specificrules makes it especially useful to organize viewing the execution ofthe program in terms of these rules. As we will see, each awkrule is treated almost like a function call, with its own specific blockof instructions.

In addition, since awk is by design a very concise language,it is easy to lose sight of everything that is going on “inside”each line ofawk code. The debugger provides the opportunityto look at the individual primitive instructions carried outby the higher-levelawk commands.


Next:  ,Previous:  Debugging,Up:  Debugger

14.2 Sample dgawk session

In order to illustrate the use of dgawk, let's look at a sampledebugging session. We will use theawk implementation of thePOSIX uniq command described earlier (seeUniq Program)as our example.

14.2.1 dgawk Invocation

Starting dgawk is exactly like runningawk. Thefile(s) containing the program and any supporting code are given on thecommand line as arguments to one or more-f options. (dgawk is not designed to debug command-lineprograms, only programs contained in files.) In our case,we calldgawk like this:

     $ dgawk -f getopt.awk -f join.awk -f uniq.awk inputfile

where both getopt.awk anduniq.awk are in $AWKPATH. (Experienced users of GDB or similar debuggers should note thatthis syntax is slightly different from what they are used to. Withdgawk, the arguments for running the program are givenin the command line to the debugger rather than as part of theruncommand at the debugger prompt.)

Instead of immediately running the program on inputfile, asgawk would ordinarily do,dgawk merely loads allthe program source files, compiles them internally, and then givesus a prompt:

     dgawk>

from which we can issue commands to the debugger. At this point, nocode has been executed.

14.2.2 Finding The Bug

Let's say that we are having a problem using (a faulty version of)uniq.awk in the “field-skipping” mode, and it doesn't seem to becatching lines which should be identical when skipping the first field,such as:

     awk is a wonderful program!
     gawk is a wonderful program!

This could happen if we were thinking (C-like) of the fields in a recordas being numbered in a zero-based fashion, so instead of the lines:

     clast = join(alast, fcount+1, n)
     cline = join(aline, fcount+1, m)

we wrote:

     clast = join(alast, fcount, n)
     cline = join(aline, fcount, m)

The first thing we usually want to do when trying to investigate aproblem like this is to put a breakpoint in the program so that we canwatch it at work and catch what it is doing wrong. A reasonable spot fora breakpoint inuniq.awk is at the beginning of the functionare_equal(), which compares the current line with the previous one. To setthe breakpoint, use theb (breakpoint) command:

     dgawk> b are_equal
     -| Breakpoint 1 set at file `awklib/eg/prog/uniq.awk', line 64

The debugger tells us the file and line number where the breakpoint is. Now type ‘r’ or ‘run’ and the program runs until it hitsthe breakpoint for the first time:

     dgawk> r
     -| Starting program:
     -| Stopping in Rule ...
     -| Breakpoint 1, are_equal(n, m, clast, cline, alast, aline)
              at `awklib/eg/prog/uniq.awk':64
     -| 64          if (fcount == 0 && charcount == 0)
     dgawk>

Now we can look at what's going on inside our program. First of all,let's see how we got to where we are. At the prompt, we type ‘bt’(short for “backtrace”), anddgawk responds with alisting of the current stack frames:

     dgawk> bt
     -| #0  are_equal(n, m, clast, cline, alast, aline)
              at `awklib/eg/prog/uniq.awk':69
     -| #1  in main() at `awklib/eg/prog/uniq.awk':89

This tells us that are_equal() was called by the main program atline 89 ofuniq.awk. (This is not a big surprise, since thisis the only call toare_equal() in the program, but in more complexprograms, knowing who called a function and with what parameters can bethe key to finding the source of the problem.)

Now that we're in are_equal(), we can start looking at the valuesof some variables. Let's say we type ‘p n’(p is short for “print”). We would expect to see the value ofn, a parameter to are_equal(). Actually, dgawkgives us:

     dgawk> p n
     -| n = untyped variable

In this case, n is an uninitialized local variable, since thefunction was called without arguments (seeFunction Calls).

A more useful variable to display might be the current record:

     dgawk> p $0
     -| $0 = string ("gawk is a wonderful program!")

This might be a bit puzzling at first since this is the second line ofour test input above. Let's look atNR:

     dgawk> p NR
     -| NR = number (2)

So we can see that are_equal() was only called for the second recordof the file. Of course, this is because our program contained a rule for‘NR == 1’:

     NR == 1 {
         last = $0
         next
     }

OK, let's just check that that rule worked correctly:

     dgawk> p last
     -| last = string ("awk is a wonderful program!")

Everything we have done so far has verified that the program has worked asplanned, up to and including the call toare_equal(), so the problem mustbe inside this function. To investigate further, we must begin“stepping through” the lines ofare_equal(). We start by typing‘n’ (for “next”):

     dgawk> n
     -| 67          if (fcount > 0) {

This tells us that gawk is now ready to execute line 67, whichdecides whether to give the lines the special “field skipping” treatmentindicated by the-f command-line option. (Notice that we skippedfrom where we were before at line 64 to here, since the condition in line 64

     if (fcount == 0 && charcount == 0)

was false.)

Continuing to step, we now get to the splitting of the current andlast records:

     dgawk> n
     -| 68              n = split(last, alast)
     dgawk> n
     -| 69              m = split($0, aline)

At this point, we should be curious to see what our records were splitinto, so we try to look:

     dgawk> p n m alast aline
     -| n = number (5)
     -| m = number (5)
     -| alast = array, 5 elements
     -| aline = array, 5 elements

(The p command can take more than one argument, similar toawk'sprint statement.)

This is kind of disappointing, though. All we found out is that thereare five elements in each of our arrays. Useful enough (we now know thatnone of the words were accidentally left out), but what if we want to seeinside the array?

The first choice would be to use subscripts:

     dgawk> p alast[0]
     -| "0" not in array `alast'

Oops!

     dgawk> p alast[1]
     -| alast["1"] = string ("awk")

This would be kind of slow for a 100-member array, though, sodgawk provides a shortcut (reminiscent of another languagenot to be mentioned):

     dgawk> p @alast
     -| alast["1"] = string ("awk")
     -| alast["2"] = string ("is")
     -| alast["3"] = string ("a")
     -| alast["4"] = string ("wonderful")
     -| alast["5"] = string ("program!")

It looks like we got this far OK. Let's take another stepor two:

     dgawk> n
     -| 70              clast = join(alast, fcount, n)
     dgawk> n
     -| 71              cline = join(aline, fcount, m)

Well, here we are at our error (sorry to spoil the suspense). What wehad in mind was to join the fields starting from the second one to makethe virtual record to compare, and if the first field was numbered zero,this would work. Let's look at what we've got:

     dgawk> p cline clast
     -| cline = string ("gawk is a wonderful program!")
     -| clast = string ("awk is a wonderful program!")

Hey, those look pretty familiar! They're just our original, unaltered,input records. A little thinking (the human brain is still the bestdebugging tool), and we realize that we were off by one!

We get out of dgawk:

     dgawk> q
     -| The program is running. Exit anyway (y/n)? y

Then we get into an editor:

     clast = join(alast, fcount+1, n)
     cline = join(aline, fcount+1, m)

and problem solved!


Next:  ,Previous:  Sample dgawk session,Up:  Debugger

14.3 Main dgawk Commands

The dgawk command set can be divided into thefollowing categories:

  • Breakpoint control
  • Execution control
  • Viewing and changing data
  • Working with the stack
  • Getting information
  • Miscellaneous

Each of these are discussed in the following subsections. In the following descriptions, commands which may be abbreviatedshow the abbreviation on a second description line. Adgawk command name may also be truncated if that partialname is unambiguous.dgawk has the built-in capability toautomatically repeat the previous command when just hitting <Enter>. This works for the commandslist, next, nexti, step, stepiand continue executed without any argument.

14.3.1 Control Of Breakpoints

As we saw above, the first thing you probably want to do in a debuggingsession is to get your breakpoints set up, since otherwise your programwill just run as if it was not under the debugger. The commands forcontrolling breakpoints are:

break [[ filename :] n | function] [ " expression "] b [[ filename :] n | function] [ " expression "]
Without any argument, set a breakpoint at the next instructionto be executed in the selected stack frame. Arguments can be one of the following:
n
Set a breakpoint at line number n in the current source file.
filename : n
Set a breakpoint at line number n in source file filename.
function
Set a breakpoint at entry to (the first instruction of)function function.

Each breakpoint is assigned a number which can be used to delete it fromthe breakpoint list using thedelete command.

With a breakpoint, you may also supply a condition. This is anawk expression (enclosed in double quotes) thatdgawkevaluates whenever the breakpoint is reached. If the condition is true,thendgawk stops execution and prompts for a command. Otherwise,dgawk continues executing the program.


clear [[ filename :] n | function]
Without any argument, delete any breakpoint at the next instructionto be executed in the selected stack frame. If the program stops ata breakpoint, this deletes that breakpoint so that the programdoes not stop at that location again. Arguments can be one of the following:
n
Delete breakpoint(s) set at line number n in the current source file.
filename : n
Delete breakpoint(s) set at line number n in source file filename.
function
Delete breakpoint(s) set at entry to function function.


condition n " expression "
Add a condition to existing breakpoint or watchpoint n. Thecondition is an awk expression that dgawk evaluateswhenever the breakpoint or watchpoint is reached. If the condition is true, then dgawk stops execution and prompts for a command. Otherwise, dgawk continues executing the program. If the condition expression isnot specified, any existing condition is removed; i.e., the breakpoint orwatchpoint is made unconditional.


delete [ n1 n2 ...] [ nm] d [ n1 n2 ...] [ nm]
Delete specified breakpoints or a range of breakpoints. Deletesall defined breakpoints if no argument is supplied.


disable [ n1 n2 ... | nm]
Disable specified breakpoints or a range of breakpoints. Withoutany argument, disables all breakpoints.


enable [ del | once] [ n1 n2 ...] [ nm] e [ del | once] [ n1 n2 ...] [ nm]
Enable specified breakpoints or a range of breakpoints. Withoutany argument, enables all breakpoints. Optionally, you can specify how to enable the breakpoint:
del
Enable the breakpoint(s) temporarily, then delete it whenthe program stops at the breakpoint.
once
Enable the breakpoint(s) temporarily, then disable it whenthe program stops at the breakpoint.


ignore n count
Ignore breakpoint number n the next count times it ishit.


tbreak [[ filename :] n | function] t [[ filename :] n | function]
Set a temporary breakpoint (enabled for only one stop). The arguments are the same as for break.

14.3.2 Control of Execution

Now that your breakpoints are ready, you can start running the programand observing its behavior. There are more commands for controllingexecution of the program than we saw in our earlier example:

commands [ n] silent ... end
Set a list of commands to be executed upon stopping ata breakpoint or watchpoint. n is the breakpoint or watchpoint number. Without a number, the last one set is used. The actual commands follow,starting on the next line, and terminated by the end command. If the command silent is in the list, the usual messages aboutstopping at a breakpoint and the source line are not printed. Any commandin the list that resumes execution (e.g., continue) terminates the list(an implicit end), and subsequent commands are ignored. For example:
          dgawk> commands
          > silent
          > printf "A silent breakpoint; i = %d\n", i
          > info locals
          > set i = 10
          > continue
          > end
          dgawk>


continue [ count] c [ count]
Resume program execution. If continued from a breakpoint and count isspecified, ignores the breakpoint at that location the next count timesbefore stopping.


finish
Execute until the selected stack frame returns. Print the returned value.


next [ count] n [ count]
Continue execution to the next source line, stepping over function calls. The argument count controls how many times to repeat the action, asin step.


nexti [ count] ni [ count]
Execute one (or count) instruction(s), stepping over function calls.


return [ value]
Cancel execution of a function call. If value (either a string or anumber) is specified, it is used as the function's return value. If used in aframe other than the innermost one (the currently executing function, i.e.,frame number 0), discard all inner frames in addition to the selected one,and the caller of that frame becomes the innermost frame.


run r
Start/restart execution of the program. When restarting, dgawkretains the current breakpoints, watchpoints, command history,automatic display variables, and debugger options.


step [ count] s [ count]
Continue execution until control reaches a different source line in thecurrent stack frame. step steps inside any function called withinthe line. If the argument count is supplied, steps that many times beforestopping, unless it encounters a breakpoint or watchpoint.


stepi [ count] si [ count]
Execute one (or count) instruction(s), stepping inside function calls. (For illustration of what is meant by an “instruction” in gawk,see the output shown under dump in Miscellaneous Dgawk Commands.)


until [[ filename :] n | function] u [[ filename :] n | function]
Without any argument, continue execution until a line past the currentline in current stack frame is reached. With an argument,continue execution until the specified location is reached, or the currentstack frame returns.

14.3.3 Viewing and Changing Data

The commands for viewing and changing variables inside of gawk are:

display [ var | $ n]
Add variable var (or field $ n) to the display list. The value of the variable or field is displayed each time the program stops. Each variable added to the list is identified by a unique number:
          dgawk> display x
          -| 10: x = 1

displays the assigned item number, the variable name and its current value. If the display variable refers to a function parameter, it is silentlydeleted from the list as soon as the execution reaches a context whereno such variable of the given name exists. Without argument, display displays the current values ofitems on the list.


eval " awk statements "
Evaluate awk statements in the context of the running program. You can do anything that an awk program would do: assignvalues to variables, call functions, and so on.
eval param, ... awk statements end
This form of eval is similar, but it allows you to define“local variables” that exist in the context of the awk statements, instead of using variables or functionparameters defined by the program.


print var1[ , var2 ...] p var1[ , var2 ...]
Print the value of a gawk variable or field. Fields must be referenced by constants:
          dgawk> print $3

This prints the third field in the input record (if the specified field does notexist, it prints ‘Null field’). A variable can be an array element, withthe subscripts being constant values. To print the contents of an array,prefix the name of the array with the ‘@’ symbol:

          gawk> print @a

This prints the indices and the corresponding values for all elements inthe arraya.


printf format [ , arg ...]
Print formatted text. The format may include escape sequences,such as ‘ \n’(see Escape Sequences). No newline is printed unless one is specified.


set var = value
Assign a constant (number or string) value to an awk variableor field. String values must be enclosed between double quotes ( "...").

You can also set special awk variables, such asFS,NF, NR, etc.


watch var | $ n [ " expression "] w var | $ n [ " expression "]
Add variable var (or field $ n) to the watch list. dgawk then stops wheneverthe value of the variable or field changes. Each watched item is assigned anumber which can be used to delete it from the watch list using the unwatch command.

With a watchpoint, you may also supply a condition. This is anawk expression (enclosed in double quotes) thatdgawkevaluates whenever the watchpoint is reached. If the condition is true,thendgawk stops execution and prompts for a command. Otherwise,dgawk continues executing the program.


undisplay [ n]
Remove item number n (or all items, if no argument) from theautomatic display list.


unwatch [ n]
Remove item number n (or all items, if no argument) from thewatch list.

14.3.4 Dealing With The Stack

Whenever you run a program which contains any function calls,gawk maintains a stack of all of the function calls leading upto where the program is right now. You can see how you got to where you are,and also move around in the stack to see what the state of things was in thefunctions which called the one you are in. The commands for doing this are:

backtrace [ count] bt [ count]
Print a backtrace of all function calls (stack frames), or innermost countframes if count > 0. Print the outermost count frames if count < 0. The backtrace displays the name and arguments to eachfunction, the source file name, and the line number.


down [ count]
Move count (default 1) frames down the stack toward the innermost frame. Then select and print the frame.


frame [ n] f [ n]
Select and print (frame number, function and argument names, source file,and the source line) stack frame n. Frame 0 is the currently executing,or innermost, frame (function call), frame 1 is the frame that called theinnermost one. The highest numbered frame is the one for the main program.


up [ count]
Move count (default 1) frames up the stack toward the outermost frame. Then select and print the frame.

14.3.5 Obtaining Information About The Program and The Debugger State

Besides looking at the values of variables, there is often a need to getother sorts of information about the state of your program and of thedebugging environment itself.dgawk has one command whichprovides this information, appropriately calledinfo. infois used with one of a number of arguments that tell it exactly whatyou want to know:

info what i what
The value for what should be one of the following:
args
Arguments of the selected frame.
break
List all currently set breakpoints.
display
List all items in the automatic display list.
frame
Description of the selected stack frame.
functions
List all function definitions including source file names andline numbers.
locals
Local variables of the selected frame.
source
The name of the current source file. Each time the program stops, thecurrent source file is the file containing the current instruction. When dgawk first starts, the current source file is the first fileincluded via the -f option. The‘ listfilename:lineno’ command canbe used at any time to change the current source.
sources
List all program sources.
variables
List all global variables.
watch
List all items in the watch list.

Additional commands give you control over the debugger, the ability tosave the debugger's state, and the ability to run debugger commandsfrom a file. The commands are:

option [ name[ = value]] o [ name[ = value]]
Without an argument, display the available debugger optionsand their current values. ‘ optionname’ shows the currentvalue of the named option. ‘ optionname=value’ assignsa new value to the named option. The available options are:
history_size
The maximum number of lines to keep in the history file ./.dgawk_history. The default is 100.
listsize
The number of lines that list prints. The default is 15.
outfile
Send gawk output to a file; debugger output still goesto standard output. An empty string ( "") resets output tostandard output.
prompt
The debugger prompt. The default is ‘ dgawk> ’.
save_history [ on | off ]
Save command history to file ./.dgawk_history. The default is on.
save_options [ on | off ]
Save current options to file ./.dgawkrc upon exit. The default is on. Options are read back in to the next session upon startup.
trace [ on | off ]
Turn instruction tracing on or off. The default is off.

save filename
Save the commands from the current session to the given file name,so that they can be replayed using the source command.
source filename
Run command(s) from a file; an error in any command does notterminate execution of subsequent commands. Comments (lines startingwith ‘ #’) are allowed in a command file. Empty lines are ignored; they do notrepeat the last command. You can't restart the program by having more than one runcommand in the file. Also, the list of commands may include additional source commands; however, dgawk will not source thesame file more than once in order to avoid infinite recursion.

In addition to, or instead of the source command, you can usethe -R file or --command=file command-lineoptions to execute commands from a file non-interactively(seeOptions.

14.3.6 Miscellaneous Commands

There are a few more commands which do not fit into theprevious categories, as follows:

dump [ filename]
Dump bytecode of the program to standard output or to the filenamed in filename. This prints a representation of the internalinstructions which gawk executes to implement the awkcommands in a program. This can be very enlightening, as the followingpartial dump of Davide Brini's obfuscated code(see Signature Program) demonstrates:
          dgawk> dump
          -|        # BEGIN
          -|
          -| [     2:0x89faef4] Op_rule             : [in_rule = BEGIN] [source_file = brini.awk]
          -| [     3:0x89fa428] Op_push_i           : "~" [PERM|STRING|STRCUR]
          -| [     3:0x89fa464] Op_push_i           : "~" [PERM|STRING|STRCUR]
          -| [     3:0x89fa450] Op_match            :
          -| [     3:0x89fa3ec] Op_store_var        : O [do_reference = FALSE]
          -| [     4:0x89fa48c] Op_push_i           : "==" [PERM|STRING|STRCUR]
          -| [     4:0x89fa4c8] Op_push_i           : "==" [PERM|STRING|STRCUR]
          -| [     4:0x89fa4b4] Op_equal            :
          -| [     4:0x89fa400] Op_store_var        : o [do_reference = FALSE]
          -| [     5:0x89fa4f0] Op_push             : o
          -| [     5:0x89fa4dc] Op_plus_i           : 0 [PERM|NUMCUR|NUMBER]
          -| [     5:0x89fa414] Op_push_lhs         : o [do_reference = TRUE]
          -| [     5:0x89fa4a0] Op_assign_plus      :
          -| [      :0x89fa478] Op_pop              :
          -| [     6:0x89fa540] Op_push             : O
          -| [     6:0x89fa554] Op_push_i           : "" [PERM|STRING|STRCUR]
          -| [      :0x89fa5a4] Op_no_op            :
          -| [     6:0x89fa590] Op_push             : O
          -| [      :0x89fa5b8] Op_concat           : [expr_count = 3] [concat_flag = 0]
          -| [     6:0x89fa518] Op_store_var        : x [do_reference = FALSE]
          -| [     7:0x89fa504] Op_push_loop        : [target_continue = 0x89fa568] [target_break = 0x89fa680]
          -| [     7:0x89fa568] Op_push_lhs         : X [do_reference = TRUE]
          -| [     7:0x89fa52c] Op_postincrement    :
          -| [     7:0x89fa5e0] Op_push             : x
          -| [     7:0x89fa61c] Op_push             : o
          -| [     7:0x89fa5f4] Op_plus             :
          -| [     7:0x89fa644] Op_push             : o
          -| [     7:0x89fa630] Op_plus             :
          -| [     7:0x89fa5cc] Op_leq              :
          -| [      :0x89fa57c] Op_jmp_false        : [target_jmp = 0x89fa680]
          -| [     7:0x89fa694] Op_push_i           : "%c" [PERM|STRING|STRCUR]
          -| [      :0x89fa6d0] Op_no_op            :
          -| [     7:0x89fa608] Op_assign_concat    : c
          -| [      :0x89fa6a8] Op_jmp              : [target_jmp = 0x89fa568]
          -| [      :0x89fa680] Op_pop_loop         :
          -|
          ...
          -|
          -| [     8:0x89fa658] Op_K_printf         : [expr_count = 17] [redir_type = ""]
          -| [      :0x89fa374] Op_no_op            :
          -| [      :0x89fa3d8] Op_atexit           :
          -| [      :0x89fa6bc] Op_stop             :
          -| [      :0x89fa39c] Op_no_op            :
          -| [      :0x89fa3b0] Op_after_beginfile  :
          -| [      :0x89fa388] Op_no_op            :
          -| [      :0x89fa3c4] Op_after_endfile    :
          dgawk>


help h
Print a list of all of the dgawk commands with a shortsummary of their usage. ‘ helpcommand’ prints the informationabout the command command.


list [ - | + | n | filename : n | nm | function] l [ - | + | n | filename : n | nm | function]
Print the specified lines (default 15) from the current source fileor the file named filename. The possible arguments to listare as follows:
-
Print lines before the lines last printed.
+
Print lines after the lines last printed. list without any argument does the same thing.
n
Print lines centered around line number n.
nm
Print lines from n to m.
filename : n
Print lines centered around line number n insource file filename. This command may change the current source file.
function
Print lines centered around beginning of thefunction function. This command may change the current source file.


quit q
Exit the debugger. Debugging is great fun, but sometimes we all haveto tend to other obligations in life, and sometimes we find the bug,and are free to go on to the next one! As we saw above, if you arerunning a program, dgawk warns you if you accidentally type‘ q’ or ‘ quit’, to make sure you really want to quit.


trace on | off
Turn on or off a continuous printing of instructions which are about tobe executed, along with printing the awk line which theyimplement. The default is off.

It is to be hoped that most of the “opcodes” in these instructions arefairly self-explanatory, and usingstepi and nexti whiletrace is on will make them into familiar friends.

14.4 Readline Support

If dgawk is compiled with the readline library, youcan take advantage of that library's command completion and history expansionfeatures. The following types of completion are available:

Command completion
Command names.
Source file name completion
Source file names. Relevant commands are break, clear, list, tbreak,and until.
Argument completion
Non-numeric arguments to a command. Relevant commands are enable and info.
Variable name completion
Global variable names, and function arguments in the current contextif the program is running. Relevant commands are display, print, set,and watch.


Previous:  Readline Support,Up:  Debugger

14.5 Limitations and Future Plans

We hope you find dgawk useful and enjoyable to work with,but as with any program, especially in its early releases, it still hassome limitations. A few which are worth being aware of are:

  • At this point, dgawk does not give a detailed explanation ofwhat you did wrong when you type in something it doesn't like. Rather, it justresponds ‘syntax error’. When you do figure out what your mistake was,though, you'll feel like a real guru.
  • If you perused the dump of opcodes in Miscellaneous Dgawk Commands,(or if you are already familiar with gawk internals),you will realize that much of the internal manipulation of dataingawk, as in many interpreters, is done on a stack.Op_push, Op_pop, etc., are the “bread and butter” ofmostgawk code. Unfortunately, as of now, dgawkdoes not allow you to examine the stack's contents.

    That is, the intermediate results of expression evaluation are on thestack, but cannot be printed. Rather, only variables which are definedin the program can be printed. Of course, a workaround forthis is to use more explicit variables at the debugging stage and thenchange back to obscure, perhaps more optimal code later.

  • There is no way to look “inside” the process of compilingregular expressions to see if you got it right. As anawkprogrammer, you are expected to know what/[^[:alnum:][:blank:]]/means.
  • dgawk is designed to be used by running a program (with all itsparameters) on the command line, as described indgawk invocation. There is no way (as of now) to attach or “break in” to a running program. This seems reasonable for a language which is used mainly for quicklyexecuting, short programs.
  • dgawk only accepts source supplied with the-f option.

Look forward to a future release when these and other missing features maybe added, and of course feel free to try to add them yourself!


Next:  ,Previous:  Debugger,Up:  Top

Appendix A The Evolution of the awk Language

This Web page describes the GNU implementation of awk, which followsthe POSIX specification. Many long-timeawk users learned awk programmingwith the originalawk implementation in Version 7 Unix. (This implementation was the basis forawk in Berkeley Unix,through 4.3-Reno. Subsequent versions of Berkeley Unix, and some systemsderived from 4.4BSD-Lite, use various versions ofgawkfor their awk.) This chapter briefly describes theevolution of theawk language, with cross-references to other partsof the Web page where you can find more information.


Next:  ,Up:  Language History

A.1 Major Changes Between V7 and SVR3.1

Theawk language evolved considerably between the release ofVersion 7 Unix (1978) and the new version that was first made generally available inSystem V Release 3.1 (1987). This section summarizes the changes, withcross-references to further details:

  • The requirement for ‘;’ to separate rules on a line(seeStatements/Lines).
  • User-defined functions and the return statement(see User-defined).
  • The delete statement (see Delete).
  • The do-while statement(see Do Statement).
  • The built-in functions atan2(), cos(), sin(),rand(), andsrand() (see Numeric Functions).
  • The built-in functions gsub(), sub(), and match()(seeString Functions).
  • The built-in functions close() and system()(see I/O Functions).
  • The ARGC, ARGV, FNR, RLENGTH,RSTART,and SUBSEP built-in variables (see Built-in Variables).
  • Assignable $0 (see Changing Fields).
  • The conditional expression using the ternary operator ‘?:’(seeConditional Exp).
  • The expression ‘index-variable in array’ outside of forstatements (see Reference to Elements).
  • The exponentiation operator ‘^’(see Arithmetic Ops) and its assignment operatorform ‘^=’ (seeAssignment Ops).
  • C-compatible operator precedence, which breaks some old awkprograms (seePrecedence).
  • Regexps as the value of FS(see Field Separators) and as thethird argument to thesplit() function(see String Functions), rather than using only the first characterofFS.
  • Dynamic regexps as operands of the ‘~’ and ‘!~’ operators(seeRegexp Usage).
  • The escape sequences ‘\b’, ‘\f’, and ‘\r’(seeEscape Sequences). (Some vendors have updated their old versions ofawk torecognize ‘\b’, ‘\f’, and ‘\r’, but this is notsomething you can rely on.)
  • Redirection of input for the getline function(see Getline).
  • Multiple BEGIN and END rules(see BEGIN/END).
  • Multidimensional arrays(see Multi-dimensional).


Next:  ,Previous:  V7/SVR3.1,Up:  Language History

A.2 Changes Between SVR3.1 and SVR4

The System V Release 4 (1989) version of Unixawk added these features(some of which originated ingawk):

  • The ENVIRON array (see Built-in Variables).
  • Multiple -f options on the command line(seeOptions).
  • The -v option for assigning variables before program execution begins(seeOptions).
  • The -- option for terminating command-line options.
  • The ‘\a’, ‘\v’, and ‘\x’ escape sequences(seeEscape Sequences).
  • A defined return value for the srand() built-in function(see Numeric Functions).
  • The toupper() and tolower() built-in string functionsfor case translation(seeString Functions).
  • A cleaner specification for the ‘%c’ format-control letter in theprintf function(seeControl Letters).
  • The ability to dynamically pass the field width and precision ("%*.*d")in the argument list of theprintf function(see Control Letters).
  • The use of regexp constants, such as /foo/, as expressions, wherethey are equivalent to using the matching operator, as in ‘$0 ~ /foo/’(seeUsing Constant Regexps).
  • Processing of escape sequences inside command-line variable assignments(see Assignment Options).


Next:  ,Previous:  SVR4,Up:  Language History

A.3 Changes Between SVR4 and POSIX awk

The POSIX Command Language and Utilities standard for awk (1992)introduced the following changes into the language:

  • The use of -W for implementation-specific options(seeOptions).
  • The use of CONVFMT for controlling the conversion of numbersto strings (seeConversion).
  • The concept of a numeric string and tighter comparison rules to gowith it (seeTyping and Comparison).
  • The use of built-in variables as function parameter names is forbidden(see Definition Syntax.
  • More complete documentation of many of the previously undocumentedfeatures of the language.

See Common Extensions, for a list of common extensionsnot permitted by the POSIX standard.

The 2008 POSIX standard can be found online athttp://www.opengroup.org/onlinepubs/9699919799/.


Next:  ,Previous:  POSIX,Up:  Language History

A.4 Extensions in Brian Kernighan's awk

Brian Kernighanhas made his version available via his home page(see Other Versions).

This section describes common extensions thatoriginally appeared in his version ofawk.

See Common Extensions, for a full list of the extensionsavailable in hisawk.


Next:  ,Previous:  BTL,Up:  Language History

A.5 Extensions in gawk Not in POSIXawk

The GNU implementation, gawk, adds a large number of features. They can all be disabled with either the--traditional or--posix options(seeOptions).

A number of features have come and gone over the years. This sectionsummarizes the additional features over POSIXawk that arein the current version of gawk.

  • Additional built-in variables:
    • TheARGINDBINMODE,ERRNO,FIELDWIDTHS,FPAT,IGNORECASE,LINT,PROCINFO,RT,andTEXTDOMAINvariables(seeBuilt-in Variables).
  • Special files in I/O redirections:
    • The /dev/stdin, /dev/stdout,/dev/stderr and/dev/fd/N special file names(seeSpecial Files).
    • The /inet, /inet4, and ‘/inet6’ special files forTCP/IP networking using ‘|&’ to specify which version of theIP protocol to use. (see TCP/IP Networking).
  • Changes and/or additions to the language:
  • New keywords:
  • Changes to standard awk functions:
    • The optional second argument to close() that allows closing one endof a two-way pipe to a coprocess(seeTwo-way I/O).
    • POSIX compliance for gsub() and sub().
    • The length() function accepts an array argumentand returns the number of elements in the array(seeString Functions).
    • The optional third argument to the match() functionfor capturing text-matching subexpressions within a regexp(seeString Functions).
    • Positional specifiers in printf formats formaking translations easier(seePrintf Ordering).
    • The split() function's additional optional fourthargument which is an array to hold the text of the field separators. (seeString Functions).
  • Additional functions only in gawk:
    • Theand(),compl(),lshift(),or(),rshift(),andxor()functions for bit manipulation(seeBitwise Functions).
    • The asort() and asorti() functions for sorting arrays(seeArray Sorting).
    • The bindtextdomain(), dcgettext() and dcngettext()functions for internationalization(seeProgrammer i18n).
    • The extension() built-in function and the ability to addnew functions dynamically(seeDynamic Extensions).
    • The fflush() function from Brian Kernighan'sversion of awk(seeI/O Functions).
    • The gensub(), patsplit(), and strtonum() functionsfor more powerful text manipulation(seeString Functions).
    • The mktime(), systime(), and strftime()functions for working with timestamps(seeTime Functions).
  • Changes and/or additions in the command-line options:
    • The AWKPATH environment variable for specifying a path search forthe-f command-line option(see Options).
    • The ability to use GNU-style long-named options that start with --and the--characters-as-bytes,--compat,--dump-variables,--exec,--gen-pot,--lint,--lint-old,--non-decimal-data,--posix,--profile,--re-interval,--sandbox,--source,--traditional,and--use-lc-numericoptions(seeOptions).
  • Support for the following obsolete systems was removed from the codeand the documentation forgawk version 4.0:
    • Amiga
    • Atari
    • BeOS
    • Cray
    • MIPS RiscOS
    • MS-DOS with the Microsoft Compiler
    • MS-Windows with the Microsoft Compiler
    • NeXT
    • SunOS 3.x, Sun 386 (Road Runner)
    • Tandem (non-POSIX)
    • Prestandard VAX C compiler for VAX/VMS


Next:  ,Previous:  POSIX/GNU,Up:  Language History

A.6 Common Extensions Summary

This section summarizes the common extensions supportedby gawk, Brian Kernighan'sawk, and mawk,the three most widely-used freely available versions ofawk(see Other Versions).

FeatureBWK AwkMawkGNU Awk
\x’ Escape sequenceXXX
RS as regexp XX
FS as null stringXXX
/dev/stdin special fileX X
/dev/stdout special fileXXX
/dev/stderr special fileXXX
** and **= operatorsX X
func keywordX X
nextfile statementXXX
delete without subscriptXXX
length() of an arrayX X
fflush() functionXXX
BINMODE variable XX


Next:  ,Previous:  Common Extensions,Up:  Language History

A.7 Regexp Ranges and Locales: A Long Sad Story

This section describes the confusing history of ranges withinregular expressions and their interactions with locales, and how thisaffected different versions ofgawk.

The original Unix tools that worked with regular expressions definedcharacter ranges (such as ‘[a-z]’) to match any character betweenthe first character in the range and the last character in the range,inclusive. Ordering was based on the numeric value of each characterin the machine's native character set. Thus, on ASCII-based systems,[a-z] matched all the lowercase letters, and only the lowercaseletters, since the numeric values for the letters from ‘a’ through‘z’ were contigous. (On an EBCDIC system, the range ‘[a-z]’includes additional, non-alphabetic characters as well.)

Almost all introductory Unix literature explained range expressionsas working in this fashion, and in particular, would teach that the“correct” way to match lowercase letters was with ‘[a-z]’, andthat ‘[A-Z]’ was the the “correct” way to match uppercase letters. And indeed, this was true.

The 1993 POSIX standard introduced the idea of locales (see Locales). Since many locales include other letters besides the plain twenty-sixletters of the American English alphabet, the POSIX standard addedcharacter classes (seeBracket Expressions) as a way to matchdifferent kinds of characters besides the traditional ones in the ASCIIcharacter set.

However, the standard changed the interpretation of range expressions. In the"C" and "POSIX" locales, a range expression like‘[a-dx-z]’ is still equivalent to ‘[abcdxyz]’, as in ASCII. But outside those locales, the ordering was defined to be based oncollation order.

In many locales, ‘A’ and ‘a’ are both less than ‘B’. In other words, these locales sort characters in dictionary order,and ‘[a-dx-z]’ is typically not equivalent to ‘[abcdxyz]’;instead it might be equivalent to ‘[aBbCcdXxYyz]’, for example.

This point needs to be emphasized: Much literature teaches that you shoulduse ‘[a-z]’ to match a lowercase character. But on systems withnon-ASCII locales, this also matched all of the uppercase charactersexcept ‘Z’! This was a continuous cause of confusion, even wellinto the twenty-first century.

To demonstrate these issues, the following example uses the sub()function, which does text replacement (seeString Functions). Here,the intent is to remove trailing uppercase characters:

     $ echo something1234abc | gawk-3.1.8 '{ sub("[A-Z]*$", ""); print }'
     -| something1234a

This output is unexpected, since the ‘bc’ at the end of‘something1234abc’ should not normally match ‘[A-Z]*’. This result is due to the locale setting (and thus you may not seeit on your system).

Similar considerations apply to other ranges. For example, ‘["-/]’is perfectly valid in ASCII, but is not valid in many Unicode locales,such as ‘en_US.UTF-8’.

Early versions of gawk used regexp matching code that was notlocale aware, so ranges had their traditional interpretation.

When gawk switched to using locale-aware regexp matchers,the problems began; especially as both GNU/Linux and commercial Unixvendors started implementing non-ASCII locales,and making themthe default. Perhaps the most frequently asked question became somethinglike “why does[A-Z] match lowercase letters?!?”

This situation existed for close to 10 years, if not more, andthe gawk maintainer grew weary of trying to explain thatgawk was being nicely standards-compliant, and that the issuewas in the user's locale. During the development of version 4.0,he modifiedgawk to always treat ranges in the original,pre-POSIX fashion, unless--posix was used (see Options).

Fortunately, shortly before the final release of gawk 4.0,the maintainer learned that the 2008 standard had changed thedefinition of ranges, such that outside the"C" and "POSIX"locales, the meaning of range expressions wasundefined.81

By using this lovely technical term, the standard gives licenseto implementors to implement ranges in whatever way they choose. Thegawk maintainer chose to apply the pre-POSIX meaning in allcases: the default regexp matching; with--traditional, and with--posix; in all cases,gawk remains POSIX compliant.

A.8 Major Contributors to gawk

Always give credit where credit is due.
Anonymous

This section names the major contributors to gawkand/or this Web page, in approximate chronological order:

  • Dr. Alfred V. Aho,Dr. Peter J. Weinberger, andDr. Brian W. Kernighan, all of Bell Laboratories,designed and implemented Unix awk,from which gawk gets the majority of its feature set.
  • Paul Rubindid the initial design and implementation in 1986, and wrotethe first draft (around 40 pages) of this Web page.
  • Jay Fenlasonfinished the initial implementation.
  • Diane Closerevised the first draft of this Web page, bringing itto around 90 pages.
  • Richard Stallmanhelped finish the implementation and the initial draft of thisWeb page. He is also the founder of the FSF and the GNU project.
  • John Woodscontributed parts of the code (mostly fixes) inthe initial version ofgawk.
  • In 1988,David Truemantook over primary maintenance ofgawk,making it compatible with “new” awk, andgreatly improving its performance.
  • Conrad Kwok,Scott Garfinkle,andKent Williamsdid the initial ports to MS-DOS with various versions of MSC.
  • Pat Rankinprovided the VMS port and its documentation.
  • Hal Petersonprovided help in portinggawk to Cray systems. (This is no longer supported.)
  • Kai Uwe Rommelprovided the initial port to OS/2 and its documentation.
  • Michal Jaegermannprovided the port to Atari systems and its documentation. (This port is no longer supported.) He continues to provide portability checking with DEC Alphasystems, and has done a lot of work to make sure gawkworks on non-32-bit systems.
  • Fred Fishprovided the port to Amiga systems and its documentation. (With Fred's sad passing, this is no longer supported.)
  • Scott Deifikcurrently maintains the MS-DOS port using DJGPP.
  • Eli Zaretskiicurrently maintains the MS-Windows port using MinGW.
  • Juan Grigeraprovided a port to Windows32 systems. (This is no longer supported.)
  • For many years,Dr. Darrel Hankersonacted as coordinator for the various ports to different PC platformsand created binary distributions for various PC operating systems. He was also instrumental in keeping the documentation up to date forthe various PC platforms.
  • Christos Zoulasprovided the extension()built-in function for dynamically adding new modules.
  • Jürgen Kahrscontributed the initial version of the TCP/IP networkingcode and documentation, and motivated the inclusion of the ‘|&’ operator.
  • Stephen Daviesprovided the initial port to Tandem systems and its documentation. (However, this is no longer supported.) He was also instrumental in the initial work to integrate thebyte-code internals into thegawk code base.
  • Matthew Woehlkeprovided improvements for Tandem's POSIX-compliant systems.
  • Martin Brownprovided the port to BeOS and its documentation. (This is no longer supported.)
  • Arno Petersdid the initial work to convertgawk to useGNU Automake and GNU gettext.
  • Alan J. Broderprovided the initial version of theasort() functionas well as the code for the optional third argument to thematch() function.
  • Andreas Bueningupdated the gawk port for OS/2.
  • Isamu Hasegawa,of IBM in Japan, contributed support for multibyte characters.
  • Michael Benzinger contributed the initial code forswitch statements.
  • Patrick T.J. McPhee contributed the code for dynamic loading in Windows32environments. (This is no longer supported)
  • John Haquereworked the gawk internals to use a byte-code engine,providing thedgawk debugger for awk programs.
  • Efraim Yawitz contributed the original text forDebugger.
  • Arnold Robbinshas been working ongawk since 1988, at firsthelping David Trueman, and as the primary maintainer since around 1994.


Next:  ,Previous:  Language History,Up:  Top

Appendix B Installing gawk

This appendix provides instructions for installing gawk on thevarious platforms that are supported by the developers. The primarydeveloper supports GNU/Linux (and Unix), whereas the other ports arecontributed. SeeBugs,for the electronic mail addresses of the people who didthe respective ports.

B.1 The gawk Distribution

This section describes how to get thegawkdistribution, how to extract it, and then what is in the various files andsubdirectories.

B.1.1 Getting the gawk Distribution

There are three ways to get GNU software:

  • Copy it from someone else who already has it.

  • Retrieve gawkfrom the Internet hostftp.gnu.org, in the directory/gnu/gawk. Both anonymous ftp andhttp access are supported. If you have the wget program, you can use a command likethe following:
              wget http://ftp.gnu.org/gnu/gawk/gawk-4.0.0.tar.gz
    

The GNU software archive is mirrored around the world. The up-to-date list of mirror sites is available fromthe main FSF web site. Try to use one of the mirrors; theywill be less busy, and you can usually find one closer to your site.


Next:  ,Previous:  Getting,Up:  Gawk Distribution

B.1.2 Extracting the Distribution

gawk is distributed as several tar files compressed withdifferent compression programs: gzip,bzip2,and xz. For simplicity, the rest of these instructions assumeyou are using the one compressed with the GNU Zip program,gzip.

Once you have the distribution (for example,gawk-4.0.0.tar.gz),usegzip to expand thefile and then use tar to extract it. You can use the followingpipeline to produce thegawk distribution:

     # Under System V, add 'o' to the tar options
     gzip -d -c gawk-4.0.0.tar.gz | tar -xvpf -

On a system with GNU tar, you can lettardo the decompression for you:

     tar -xvpzf gawk-4.0.0.tar.gz

Extracting the archivecreates a directory named gawk-4.0.0in the current directory.

The distribution file name is of the formgawk-V.R.P.tar.gz. TheV represents the major version of gawk,theR represents the current release of version V, andthe P represents a patch level, meaning that minor bugs havebeen fixed in the release. The current patch level is 0,but when retrieving distributions, you should get the version with the highestversion, release, and patch level. (Note, however, that patch levels greater thanor equal to 70 denote “beta” or nonproduction software; you might not wantto retrieve such a version unless you don't mind experimenting.) If you are not on a Unix or GNU/Linux system, you need to make other arrangementsfor getting and extracting the gawk distribution. You should consulta local expert.


Previous:  Extracting,Up:  Gawk Distribution

B.1.3 Contents of the gawk Distribution

The gawk distribution has a number of C source files,documentation files,subdirectories, and files related to the configuration process(seeUnix Installation),as well as several subdirectories related to different non-Unixoperating systems:

Various ‘ .c’, ‘ .y’, and ‘ .h’ files
The actual gawk source code.
README README_d/README.*
Descriptive files: README for gawk under Unix and therest for the various hardware and software combinations.
INSTALL
A file providing an overview of the configuration and installation process.
ChangeLog
A detailed list of source code changes as bugs are fixed or improvements made.
ChangeLog.0
An older list of source code changes.
NEWS
A list of changes to gawk since the last release or patch.
NEWS.0
An older list of changes to gawk.
COPYING
The GNU General Public License.
FUTURES
A brief list of features and changes being contemplated for futurereleases, with some indication of the time frame for the feature, basedon its difficulty.
LIMITATIONS
A list of those factors that limit gawk's performance. Most of these depend on the hardware or operating system software andare not limits in gawk itself.
POSIX.STD
A description of behaviors in the POSIX standard for awk whichare left undefined, or where gawk may not comply fully, as wellas a list of things that the POSIX standard should describe but does not.


doc/awkforai.txt
A short article describing why gawk is a good language forArtificial Intelligence (AI) programming.
doc/bc_notes
A brief description of gawk's “byte code” internals.
doc/README.card doc/ad.block doc/awkcard.in doc/cardfonts doc/colors doc/macros doc/no.colors doc/setter.outline
The troff source for a five-color awk reference card. A modern version of troff such as GNU troff ( groff) isneeded to produce the color version. See the file README.cardfor instructions if you have an older troff.
doc/gawk.1
The troff source for a manual page describing gawk. This is distributed for the convenience of Unix users.


doc/gawk.texi
The Texinfo source file for this Web page. It should be processed with TeX(via texi2dvi or texi2pdf)to produce a printed document, andwith makeinfo to produce an Info or HTML file.
doc/gawk.info
The generated Info file for this Web page.
doc/gawkinet.texi
The Texinfo source file for TCP/IP Internetworking with gawk. It should be processed with TeX(via texi2dvi or texi2pdf)to produce a printed document andwith makeinfo to produce an Info or HTML file.
doc/gawkinet.info
The generated Info file for TCP/IP Internetworking with gawk.
doc/igawk.1
The troff source for a manual page describing the igawkprogram presented in Igawk Program.
doc/Makefile.in
The input file used during the configuration process to generate theactual Makefile for creating the documentation.
Makefile.am */Makefile.am
Files used by the GNU automake software for generatingthe Makefile.in files used by autoconf and configure.
Makefile.in aclocal.m4 configh.in configure.ac configure custom.h missing_d/* m4/*
These files and subdirectories are used when configuring gawkfor various Unix systems. They are explained in Unix Installation.
po/*
The po library contains message translations.
awklib/extract.awk awklib/Makefile.am awklib/Makefile.in awklib/eg/*
The awklib directory contains a copy of extract.awk(see Extract Program),which can be used to extract the sample programs from the Texinfosource file for this Web page. It also contains a Makefile.in file, which configure uses to generate a Makefile. Makefile.am is used by GNU Automake to create Makefile.in. The library functions from Library Functions,and the igawk program from Igawk Program,are included as ready-to-use files in the gawk distribution. They are installed as part of the installation process. The rest of the programs in this Web page are available in appropriatesubdirectories of awklib/eg.
posix/*
Files needed for building gawk on POSIX-compliant systems.
pc/*
Files needed for building gawk under MS-Windows and OS/2(see PC Installation, for details).
vms/*
Files needed for building gawk under VMS(see VMS Installation, for details).
test/*
A test suite for gawk. You can use ‘ make check’ from the top-level gawkdirectory to run your version of gawk against the test suite. If gawk successfully passes ‘ make check’, then you canbe confident of a successful port.

B.2 Compiling and Installing gawk on Unix-like Systems

Usually, you can compile and install gawk by typing only twocommands. However, if you use an unusual system, you may needto configuregawk for your system yourself.

B.2.1 Compiling gawk for Unix-like Systems

The normal installation steps should work on all modern commercialUnix-derived systems, GNU/Linux, BSD-based systems, and the Cygwinenvironment for MS-Windows.

After you have extracted the gawk distribution,cdto gawk-4.0.0. Like most GNU software,gawk is configuredautomatically for your system by running theconfigure program. This program is a Bourne shell script that is generated automatically usingGNUautoconf. (The autoconf software isdescribed fully inAutoconf—Generating Automatic Configuration Scripts,which can be found online atthe Free Software Foundation's web site.)

To configure gawk, simply run configure:

     sh ./configure

This produces a Makefile and config.h tailored to your system. Theconfig.h file describes various facts about your system. You might want to edit theMakefile tochange the CFLAGS variable, which controlsthe command-line options that are passed to the C compiler (such asoptimization levels or compiling for debugging).

Alternatively, you can add your own values for most makevariables on the command line, such asCC and CFLAGS, whenrunning configure:

     CC=cc CFLAGS=-g sh ./configure

See the file INSTALL in thegawk distribution forall the details.

After you have run configure and possibly edited theMakefile,type:

     make

Shortly thereafter, you should have an executable version of gawk. That's all there is to it! To verify thatgawk is working properly,run ‘make check’. All of the tests should succeed. If these steps do not work, or if any of the tests fail,check the files in theREADME_d directory to see if you'vefound a known problem. If the failure is not described there,please send in a bug report (seeBugs).

B.2.2 Additional Configuration Options

There are several additional options you may use on theconfigurecommand line when compiling gawk from scratch, including:

--disable-lint
Disable all lint checking within gawk. The --lint and --lint-old options(see Options)are accepted, but silently do nothing. Similarly, setting the LINT variable(see User-modified)has no effect on the running awk program.

When used with GCC's automatic dead-code-elimination, this optioncuts almost 200K bytes off the size of thegawkexecutable on GNU/Linux x86 systems. Results on other systems andwith other compilers are likely to vary. Using this option may bring you some slight performance improvement.

Using this option will cause some of the tests in the test suiteto fail. This option may be removed at a later date.


--disable-nls
Disable all message-translation facilities. This is usually not desirable, but it may bring you some slight performanceimprovement.


--with-whiny-user-strftime
Force use of the included version of the strftime()function for deficient systems.

Use the command ‘./configure --help’ to see the full list ofoptions thatconfigure supplies.

B.2.3 The Configuration Process

This section is of interest only if you know something about using theC language and Unix-like operating systems.

The source code for gawk generally attempts to adhere to formalstandards wherever possible. This means thatgawk uses libraryroutines that are specified by the ISO C standard and by the POSIXoperating system interface standard. Thegawk source code requires using an ISO C compiler (the 1990standard).

Many Unix systems do not support all of either the ISO or thePOSIX standards. Themissing_d subdirectory in the gawkdistribution contains replacement versions of those functions that aremost likely to be missing.

The config.h file that configure creates containsdefinitions that describe features of the particular operating systemwhere you are attempting to compilegawk. The three thingsdescribed by this file are: what header files are available, so thatthey can be correctly included, what (supposedly) standard functionsare actually available in your C libraries, and various miscellaneousfacts about your operating system. For example, there may not be anst_blksize element in thestat structure. In this case,‘HAVE_ST_BLKSIZE’ is undefined.

It is possible for your C compiler to lie toconfigure. It maydo so by not exiting with an error when a library function is notavailable. To get around this, edit the filecustom.h. Use an ‘#ifdef’ that is appropriate for your system, and either#define any constants thatconfigure should have defined butdidn't, or#undef any constants that configure defined andshould not have.custom.h is automatically included byconfig.h.

It is also possible that the configure program generated byautoconf will not work on your system in some other fashion. If you do have a problem, the fileconfigure.ac is the input forautoconf. You may be able to change this file and generate anew version ofconfigure that works on your system(seeBugs,for information on how to report problems in configuringgawk). The same mechanism may be used to send in updates toconfigure.acand/or custom.h.


Next:  ,Previous:  Unix Installation,Up:  Installation

B.3 Installation on Other Operating Systems

This section describes how to install gawk onvarious non-Unix systems.

<!-- Rewritten by Scott Deifik --><!-- and Darrel Hankerson -->
B.3.1 Installation on PC Operating Systems

This section covers installation and usage of gawk on x86 machinesrunning MS-DOS, any version of MS-Windows, or OS/2. In this section, the term “Windows32”refers to any of Microsoft Windows-95/98/ME/NT/2000/XP/Vista/7.

The limitations of MS-DOS (and MS-DOS shells under Windows32 or OS/2) has meantthat various “DOS extenders” are often used with programs such asgawk. The varying capabilities of Microsoft Windows 3.1and Windows32 can add to the confusion. For an overview of theconsiderations, please refer to README_d/README.pc in thedistribution.

B.3.1.1 Installing a Prepared Distribution for PC Systems

If you have received a binary distribution prepared by the MS-DOSmaintainers, thengawk and the necessary support files appearunder thegnu directory, with executables in gnu/bin,libraries ingnu/lib/awk, and manual pages under gnu/man. This is designed for easy installation to a/gnu directory on yourdrive—however, the files can be installed anywhere providedAWKPATH isset properly. Regardless of the installation directory, the first line ofigawk.cmd andigawk.bat (in gnu/bin) may need to beedited.

The binary distribution contains a separate file describing thecontents. In particular, it may include more than one version of thegawk executable.

OS/2 (32 bit, EMX) binary distributions are prepared for the /usrdirectory of your preferred drive. SetUNIXROOT to your installationdrive (e.g., ‘e:’) if you want to installgawk onto another drivethan the hardcoded default ‘c:’. Executables appear in/usr/bin,libraries under /usr/share/awk, manual pages under/usr/man,Texinfo documentation under /usr/info, and NLS filesunder /usr/share/locale. Note that the files can be installed anywhere providedAWKPATH isset properly.

If you already have a file /usr/info/dir from another packagedo not overwrite it! Instead enter the following commands at your prompt(replace ‘x:’ by your installation drive):

     install-info --info-dir=x:/usr/info x:/usr/info/gawk.info
     install-info --info-dir=x:/usr/info x:/usr/info/gawkinet.info

The binary distribution may contain a separate file containing additionalor more detailed installation instructions.

B.3.1.2 Compiling gawk for PC Operating Systems

gawk can be compiled for MS-DOS, Windows32, and OS/2 using the GNUdevelopment tools from DJ Delorie (DJGPP: MS-DOS only) or EberhardMattes (EMX: MS-DOS, Windows32 and OS/2). The fileREADME_d/README.pc in the gawk distribution containsadditional notes, andpc/Makefile contains important information oncompilation options.

To buildgawk for MS-DOS and Windows32, copy the files inthepc directory (except for ChangeLog) to thedirectory with the rest of thegawk sources, then invokemake with the appropriate target name as an argument tobuildgawk. The Makefile copied from thepcdirectory contains a configuration section with comments and may needto be edited in order to work with yourmake utility.

The Makefile supports a number of targets for building variousMS-DOS and Windows32 versions. A list of targets is printed if themake command is given without a target. As an example, tobuild gawk using the DJGPP tools, enter ‘make djgpp’. (The DJGPP tools needed for the build may be found atftp://ftp.delorie.com/pub/djgpp/current/v2gnu/.) To build anative MS-Windows binary of gawk, type ‘make mingw32’.

The 32 bit EMX version ofgawk works “out of the box” under OS/2. However, it is highly recommended to use GCC 2.95.3 for the compilation. In principle, it is possible to compilegawk the following way:

     $ ./configure
     $ make

This is not recommended, though. To get an OMF executable you shoulduse the following commands at yoursh prompt:

     $ CFLAGS="-O2 -Zomf -Zmt"
     $ export CFLAGS
     $ LDFLAGS="-s -Zcrtdll -Zlinker /exepack:2 -Zlinker /pm:vio -Zstack 0x6000"
     $ export LDFLAGS
     $ RANLIB="echo"
     $ export RANLIB
     $ ./configure --prefix=c:/usr
     $ make AR=emxomfar

These are just suggestions for use with GCC 2.x. You may use any other set of(self-consistent) environment variables and compiler flags.

If you use GCC 2.95 it is recommended to use also:

     $ LIBS="-lgcc"
     $ export LIBS

You can also get an a.out executable if you prefer:

     $ CFLAGS="-O2 -Zmt"
     $ export CFLAGS
     $ LDFLAGS="-s -Zstack 0x6000"
     $ LIBS="-lgcc"
     $ unset RANLIB
     
     $ ./configure --prefix=c:/usr
     $ make
NOTE: Compilation of a.out executables also works with GCC 3.2. Versions later than GCC 3.2 have not been tested successfully.

make install’ works as expected with the EMX build.

NOTE: Ancient OS/2 ports of GNU make are not able to handlethe Makefiles of this package. If you encounter any problems with make, try GNU Make 3.79.1 or later versions. You shouldfind the latest version on ftp://hobbes.nmsu.edu/pub/os2/.


Next:  ,Previous:  PC Compiling,Up:  PC Installation

B.3.1.3 Testing gawk on PC Operating Systems

Using make to run the standard tests and to installgawkrequires additional Unix-like tools, includingsh, sed, andcp. In order to run the tests, thetest/*.ok files may need tobe converted so that they have the usual MS-DOS-style end-of-line markers. Alternatively, runmake check CMP="diff -a" to use GNU diffin text mode instead of cmp to compare the resulting files.

Mostof the tests work properly with Stewartson's shell along with thecompanion utilities or appropriate GNU utilities. However, some editing oftest/Makefile is required. It is recommended that you copy the filepc/Makefile.tst over the file test/Makefile as areplacement. Details can be found inREADME_d/README.pcand in the file pc/Makefile.tst.

On OS/2 the pid test fails because spawnl() is used instead offork()/execl() to start child processes. Also thembfw1 and mbprintf1 tests fail because the neededmultibyte functionality is not available.


Next:  ,Previous:  PC Testing,Up:  PC Installation

B.3.1.4 Using gawk on PC Operating Systems

With the exception of the Cygwin environment,the ‘|&’ operator and TCP/IP networking(see TCP/IP Networking)are not supported for MS-DOS or MS-Windows. EMX (OS/2 only) does supportat least the ‘|&’ operator.

The MS-DOS and MS-Windows versions of gawk search forprogram files as described inAWKPATH Variable. However,semicolons (rather than colons) separate elements in theAWKPATHvariable. If AWKPATH is not set or is empty, then the defaultsearch path for MS-Windows and MS-DOS versions is".;c:/lib/awk;c:/gnu/lib/awk".

The search path for OS/2 (32 bit, EMX) is determined by the prefix directory(most likely/usr or c:/usr) that has been specified as an option oftheconfigure script like it is the case for the Unix versions. Ifc:/usr is the prefix directory then the default search path contains.and c:/usr/share/awk. Additionally, to support binary distributions ofgawk for OS/2systems whose drive ‘c:’ might not support long file names or might not existat all, there is a special environment variable. IfUNIXROOT specifiesa drive then this specific drive is also searched for program files. E.g., ifUNIXROOT is set to e: the complete default search path is".;c:/usr/share/awk;e:/usr/share/awk".

An sh-like shell (as opposed to command.com under MS-DOSor cmd.exe under MS-Windows or OS/2) may be useful forawk programming. The DJGPP collection of tools includes an MS-DOS port of Bash,and several shells are available for OS/2, includingksh.

Under MS-Windows, OS/2 and MS-DOS, gawk (and many other text programs) silentlytranslate end-of-line"\r\n" to "\n" on input and "\n"to "\r\n" on output. A specialBINMODE variable (c.e.) allows control over these translations and is interpreted as follows:

  • If BINMODE is "r", or one,thenbinary mode is set on read (i.e., no translations on reads).
  • If BINMODE is "w", or two,thenbinary mode is set on write (i.e., no translations on writes).
  • If BINMODE is "rw" or "wr" or three,binary mode is set for both read and write.
  • BINMODE=non-null-string isthe same as ‘BINMODE=3’ (i.e., no translations onreads or writes). However,gawk issues a warningmessage if the string is not one of"rw" or "wr".

The modes for standard input and standard output are set one timeonly (after thecommand line is read, but before processing any of theawk program). Setting BINMODE for standard input orstandard output is accomplished by using anappropriate ‘-v BINMODE=N’ option on the command line.BINMODE is set at the time a file or pipe is opened and cannot bechanged mid-stream.

The name BINMODE was chosen to match mawk(seeOther Versions). mawk andgawk handle BINMODE similarly; however,mawk adds a ‘-W BINMODE=N’ option and an environmentvariable that can setBINMODE, RS, and ORS. Thefiles binmode[1-3].awk (undergnu/lib/awk in some of theprepared distributions) have been chosen to matchmawk's ‘-WBINMODE=N’ option. These can be changed or discarded; in particular,the setting ofRS giving the fewest “surprises” is open to debate. mawk uses ‘RS = "\r\n"’ if binary mode is set on read, which isappropriate for files with the MS-DOS-style end-of-line.

To illustrate, the following examples set binary mode on writes for standardoutput and other files, and setORS as the “usual” MS-DOS-styleend-of-line:

     gawk -v BINMODE=2 -v ORS="\r\n" ...

or:

     gawk -v BINMODE=w -f binmode2.awk ...

These give the same result as the ‘-W BINMODE=2’ option inmawk. The following changes the record separator to"\r\n" and sets binarymode on reads, but does not affect the mode on standard input:

     gawk -v RS="\r\n" --source "BEGIN { BINMODE = 1 }" ...

or:

     gawk -f binmode1.awk ...

With proper quoting, in the first example the setting of RS can bemoved into the BEGIN rule.


Next:  ,Previous:  PC Using,Up:  PC Installation

B.3.1.5 Using gawk In The Cygwin Environment

gawk can be built and used “out of the box” under MS-Windowsif you are using theCygwin environment. This environment provides an excellent simulation of Unix, using theGNU tools, such as Bash, the GNU Compiler Collection (GCC), GNU Make,and other GNU programs. Compilation and installation for Cygwin is thesame as for a Unix system:

     tar -xvpzf gawk-4.0.0.tar.gz
     cd gawk-4.0.0
     ./configure
     make

When compared to GNU/Linux on the same system, the ‘configure’step on Cygwin takes considerably longer. However, it does finish,and then the ‘make’ proceeds as usual.

NOTE: The ‘ |&’ operator and TCP/IP networking(see TCP/IP Networking)are fully supported in the Cygwin environment. This is not truefor any other environment on MS-Windows.


Previous:  Cygwin,Up:  PC Installation

B.3.1.6 Using gawk In The MSYS Environment

In the MSYS environment under MS-Windows, gawk automaticallyuses binary mode for reading and writing files. Thus there is noneed to use theBINMODE variable.

This can cause problems with other Unix-like components that havebeen ported to MS-Windows that expectgawk to do automatictranslation of "\r\n", since it won't. Caveat Emptor!

B.3.2 How to Compile and Install gawk on VMS
<!-- based on material from Pat Rankin -->

This subsection describes how to compile and installgawk under VMS. The older designation “VMS” is used throughout to refer to OpenVMS.

B.3.2.1 Compiling gawk on VMS

To compilegawk under VMS, there is a DCL command procedure thatissues all the necessaryCC and LINK commands. There isalso a Makefile for use with theMMS utility. From the sourcedirectory, use either:

     $ @[.VMS]VMSBUILD.COM

or:

     $ MMS/DESCRIPTION=[.VMS]DESCRIP.MMS GAWK

Older versions of gawk could be built with VAX C orGNU C on VAX/VMS, as well as with DEC C, but that is no longersupported. DEC C (also briefly known as “Compaq C” and now knownas “HP C,” but referred to here as “DEC C”) is required. BothVMSBUILD.COM and DESCRIP.MMS contain some obsolete supportfor the older compilers but are set up to use DEC C by default.

gawk has been tested under Alpha/VMS 7.3-1 using Compaq C V6.4,and on Alpha/VMS 7.3, Alpha/VMS 7.3-2, and IA64/VMS 8.3.82


Next:  ,Previous:  VMS Compilation,Up:  VMS Installation

B.3.2.2 Installing gawk on VMS

To install gawk, all you need is a “foreign” command, which isaDCL symbol whose value begins with a dollar sign. For example:

     $ GAWK :== $disk1:[gnubin]GAWK

Substitute the actual location of gawk.exe for‘$disk1:[gnubin]’. The symbol should be placed in thelogin.com of any user who wants to run gawk,so that it is defined every time the user logs on. Alternatively, the symbol may be placed in the system-widesylogin.com procedure, which allows all usersto run gawk.

Optionally, the help entry can be loaded into a VMS help library:

     $ LIBRARY/HELP SYS$HELP:HELPLIB [.VMS]GAWK.HLP

(You may want to substitute a site-specific help library rather thanthe standard VMS library ‘HELPLIB’.) After loading the help text,the command:

     $ HELP GAWK

provides information about both the gawk implementation and theawk programming language.

The logical name ‘AWK_LIBRARY’ can designate a default locationforawk program files. For the -f option, if the specifiedfile name has no device or directory path information in it,gawklooks in the current directory first, then in the directory specifiedby the translation of ‘AWK_LIBRARY’ if the file is not found. If, after searching in both directories, the file still is not found,gawk appends the suffix ‘.awk’ to the filename and retriesthe file search. If ‘AWK_LIBRARY’ has no definition, a default valueof ‘SYS$LIBRARY:’ is used for it.

B.3.2.3 Running gawk on VMS

Command-line parsing and quoting conventions are significantly differenton VMS, so examples in this Web page or from other sources often need minorchanges. Theyare minor though, and all awk programsshould run correctly.

Here are a couple of trivial tests:

     $ gawk -- "BEGIN {print ""Hello, World!""}"
     $ gawk -"W" version
     ! could also be -"W version" or "-W version"

Note that uppercase and mixed-case text must be quoted.

The VMS port of gawk includes a DCL-style interface in additionto the original shell-style interface (see the help entry for details). One side effect of dual command-line parsing is that if there is only asingle parameter (as in the quoted string program above), the commandbecomes ambiguous. To work around this, the normally optional --flag is required to force Unix-style parsing rather thanDCL parsing. If anyother dash-type options (or multiple parameters such as data files toprocess) are present, there is no ambiguity and-- can be omitted.

The default search path, when looking forawk program files specifiedby the -f option, is "SYS$DISK:[],AWK_LIBRARY:". The logicalnameAWKPATH can be used to override this default. The formatofAWKPATH is a comma-separated list of directory specifications. When defining it, the value should be quoted so that it retains a singletranslation and not a multitranslationRMS searchlist.


Previous:  VMS Running,Up:  VMS Installation

B.3.2.4 Some VMS Systems Have An Old Version of gawk
<!-- Thanks to "gerard labadie" -->

Some versions of VMS have an old version of gawk. To access it,define a symbol, as follows:

     $ gawk :== $sys$common:[syshlp.examples.tcpip.snmp]gawk.exe

This is apparently version 2.15.6, which is extremely old. Werecommend compiling and using the current version.

B.4 Reporting Problems and Bugs

There is nothing more dangerous than a bored archeologist.
The Hitchhiker's Guide to the Galaxy

If you have problems withgawk or think that you have found a bug,please report it to the developers; we cannot promise to do anythingbut we might well want to fix it.

Before reporting a bug, make sure you have actually found a real bug. Carefully reread the documentation and see if it really says you can dowhat you're trying to do. If it's not clear whether you should be ableto do something or not, report that too; it's a bug in the documentation!

Before reporting a bug or trying to fix it yourself, try to isolate itto the smallest possibleawk program and input data file thatreproduces the problem. Then send us the program and data file,some idea of what kind of Unix system you're using,the compiler you used to compilegawk, and the exact resultsgawk gave you. Also say what you expected to occur; this helpsus decide whether the problem is really in the documentation.

Please include the version number of gawk you are using. You can get this information with the command ‘gawk --version’.

Once you have a precise problem, send email to“bug-gawk at gnu dot org”.

Using this address automatically sends a copy of yourmail to me. If necessary, I can be reached directly at“arnold at skeeve dot com”. The bug reporting address is preferred since theemail list is archived at the GNU Project. All email should be in English, since that is my native language.

CAUTION: Do not try to report bugs in gawk byposting to the Usenet/Internet newsgroup comp.lang.awk. While the gawk developers do occasionally read this newsgroup,there is no guarantee that we will see your posting. The steps describedabove are the official recognized ways for reporting bugs. Really.
NOTE: Many distributions of GNU/Linux and the various BSD-based operating systemshave their own bug reporting systems. If you report a bug using your distribution'sbug reporting system, please also send a copy to“bug-gawk at gnu dot org”.

This is for two reasons. First, while some distributions forwardbug reports “upstream” to the GNU mailing list, many don't, so there is a goodchance that thegawk maintainer won't even see the bug report! Second,mail to the GNU list is archived, and having everything at the GNU projectkeeps things self-contained and not dependant on other web sites.

Non-bug suggestions are always welcome as well. If you have questionsabout things that are unclear in the documentation or are just obscurefeatures, ask me; I will try to help you out, although Imay not have the time to fix the problem. You can send me electronicmail at the Internet address noted previously.

If you find bugs in one of the non-Unix ports of gawk, please sendan electronic mail message to the person who maintains that port. Theyare named in the following list, as well as in theREADME file in the gawkdistribution. Information in theREADME file should be consideredauthoritative if it conflicts with this Web page.

The people maintaining the non-Unix ports of gawk areas follows:

MS-DOS with DJGPPScott Deifik, “scottd dot mail at sbcglobal dot net”.


MS-Windows with MINGWEli Zaretskii, “eliz at gnu dot org”.


OS/2Andreas Buening, “andreas dot buening at nexgo dot de”.


VMSPat Rankin, “rankin at pactechdata dot com”.


z/OS (OS/390)Dave Pitts, “dpitts at cozx dot com”.

If your bug is also reproducible under Unix, please send a copy of yourreport to the “bug-gawk at gnu dot org” email list as well.


Previous:  Bugs,Up:  Installation

B.5 Other Freely Available awk Implementations

It's kind of fun to put comments like this in your awk code.
// Do C++ comments work? answer: yes! of course
Michael Brennan

There are a number of other freely available awk implementations. This section briefly describes where to get them:

Unix awk
Brian Kernighan, one of the original designers of Unix awk,has made his implementation of awk freely available. You can retrieve this version via the World Wide Web from his home page. It is available in several archive formats:
Shell archive
http://www.cs.princeton.edu/~bwk/btl.mirror/awk.shar
Compressed tar file
http://www.cs.princeton.edu/~bwk/btl.mirror/awk.tar.gz
Zip file
http://www.cs.princeton.edu/~bwk/btl.mirror/awk.zip

This version requires an ISO C (1990 standard) compiler;the C compiler fromGCC (the GNU Compiler Collection)works quite nicely.

See Common Extensions,for a list of extensions in thisawk that are not in POSIX awk.


mawk
Michael Brennan wrote an independent implementation of awk,called mawk. It is available under the GPL(see Copying),just as gawk is.

The original distribution site for the mawk source codeno longer has it. A copy is available athttp://www.skeeve.com/gawk/mawk1.3.3.tar.gz.

In 2009, Thomas Dickey took on mawk maintenance. Basic information is available onthe project's web page. The download URL ishttp://invisible-island.net/datafiles/release/mawk.tar.gz.

Once you have it,gunzip may be used to decompress this file. Installationis similar togawk's(see Unix Installation).

See Common Extensions,for a list of extensions inmawk that are not in POSIX awk.


awka
Written by Andrew Sumner, awka translates awk programs into C, compiles them,and links them with a library of functions that provides the core awk functionality. It also has a number of extensions.

The awk translator is released under the GPL, and the libraryis under the LGPL.

To get awka, go to http://sourceforge.net/projects/awka.

The project seems to be frozen; no new code changes have been madesince approximately 2003.


pawk
Nelson H.F. Beebe at the University of Utah has modifiedBrian Kernighan's awk to provide timing and profiling information. It is different from pgawk(see Profiling),in that it uses CPU-based profiling, not line-countprofiling. You may find it at either ftp://ftp.math.utah.edu/pub/pawk/pawk-20030606.tar.gzor http://www.math.utah.edu/pub/pawk/pawk-20030606.tar.gz.
Busybox Awk
Busybox is a GPL-licensed program providing small versions of manyapplications within a single executable. It is aimed at embedded systems. It includes a full implementation of POSIX awk. When buildingit, be careful not to do ‘ make install’ as it will overwritecopies of other applications in your /usr/local/bin. For moreinformation, see the project's home page.


The OpenSolaris POSIX awk
The version of awk in /usr/xpg4/bin on Solaris ismore-or-lessPOSIX-compliant. It is based on the awk from Mortice KernSystems for PCs. The source code can be downloaded fromthe OpenSolaris web site. This author was able to make it compile and work under GNU/Linuxwith 1–2 hours of work. Making it more generally portable (usingGNU Autoconf and/or Automake) would take more work, and thishas not been done, at least to our knowledge.


jawk
This is an interpreter for awk written in Java. It claimsto be a full interpreter, although because it uses Java facilitiesfor I/O and for regexp matching, the language it supports is differentfrom POSIX awk. More information is available on the project's home page.
Libmawk
This is an embeddable awk interpreter derived from mawk. For more information see http://repo.hu/projects/libmawk/.
QSE Awk
This is an embeddable awk interpreter. For more informationsee http://code.google.com/p/qse/ and http://awk.info/?tools/qse.
QTawk
This is an independent implementation of awk distributedunder the GPL. It has a large number of extensions over standard awk and may not be 100% syntactically compatible with it. See http://www.quiktrim.org/QTawk.html for more information,including the manual and a download link.
xgawk
XML gawk. This is a fork of the gawk 3.1.6 source baseto support processing XML files. It has a number ofinteresting extensions which should one day be integratedinto the main gawk code base. For more information, see the XMLgawk project web site.


Next:  ,Previous:  Installation,Up:  Top

Appendix C Implementation Notes

This appendix contains information mainly of interest to implementers andmaintainers ofgawk. Everything in it applies specifically togawk and not to other implementations.


Next:  ,Up:  Notes

C.1 Downward Compatibility and Debugging

SeePOSIX/GNU,for a summary of the GNU extensions to theawk language and program. All of these features can be turned off by invokinggawk with the--traditional option or with the--posix option.

If gawk is compiled for debugging with ‘-DDEBUG’, then thereis one more option available on the command line:

-Y --parsedebug
Prints out the parse stack information as the program is being parsed.

This option is intended only for serious gawk developersand not for the casual user. It probably has not even been compiled intoyour version ofgawk, since it slows down execution.


Next:  ,Previous:  Compatibility Mode,Up:  Notes

C.2 Making Additions to gawk

If you find that you want to enhance gawk in a significantfashion, you are perfectly free to do so. That is the point of havingfree software; the source code is available and you are free to changeit as you want (see Copying).

This section discusses the ways you might want to change gawkas well as any considerations you should bear in mind.


Next:  ,Up:  Additions

C.2.1 Accessing The gawk Git Repository

As gawk is Free Software, the source code is always available.Gawk Distribution, describes how to get and build the formal,released versions ofgawk.

However, if you want to modify gawk and contribute back yourchanges, you will probably wish to work with the development version. To do so, you will need to access thegawk source coderepository. The code is maintained using theGit distributed version control system. You will need to install it if your system doesn't have it. Once you have done so, use the command:

     git clone git://git.savannah.gnu.org/gawk.git

This will clone the gawk repository. If you are behind afirewall that will not allow you to use the Git native protocol, youcan still access the repository using:

     git clone http://git.savannah.gnu.org/r/gawk.git

Once you have made changes, you can use ‘git diff’ to produce apatch, and send that to thegawk maintainer; see Bugsfor how to do that.

Finally, if you cannot install Git (e.g., if it hasn't been portedyet to your operating system), you can use the Git–CVS gatewayto check out a copy using CVS, as follows:

     cvs -d:pserver:anonymous@pserver.git.sv.gnu.org:/gawk.git co -d gawk master


Next:  ,Previous:  Accessing The Source,Up:  Additions

C.2.2 Adding New Features

You are free to add any new features you like to gawk. However, if you want your changes to be incorporated into thegawkdistribution, there are several steps that you need to take in order tomake it possible to include your changes:

  1. Before building the new feature into gawk itself,consider writing it as an extension module(seeDynamic Extensions). If that's not possible, continue with the rest of the steps in this list.
  2. Be prepared to sign the appropriate paperwork. In order for the FSF to distribute your changes, you must either placethose changes in the public domain and submit a signed statement to thateffect, or assign the copyright in your changes to the FSF. Both of these actions are easy to do and many people have done soalready. If you have questions, please contact me(seeBugs),or “assign at gnu dot org”.
  3. Get the latest version. It is much easier for me to integrate changes if they are relative tothe most recent distributed version ofgawk. If your version ofgawk is very old, I may not be able to integrate them at all. (SeeGetting,for information on getting the latest version of gawk.)
  4. Follow the GNU Coding Standards. This document describes how GNU software should be written. If you haven'tread it, please do so, preferablybefore starting to modify gawk. (TheGNU Coding Standards are available fromthe GNU Project'sweb site. Texinfo, Info, and DVI versions are also available.)

  5. Use the gawk coding style. The C code forgawk follows the instructions in theGNU Coding Standards, with minor exceptions. The code is formattedusing the traditional “K&R” style, particularly as regards to the placementof braces and the use of TABs. In brief, the coding rules for gawkare as follows:
    • Use ANSI/ISO style (prototype) function headers when defining functions.
    • Put the name of the function at the beginning of its own line.
    • Put the return type of the function, even if it is int, on theline above the line with the name and arguments of the function.
    • Put spaces around parentheses used in control structures(if, while, for, do, switch,and return).
    • Do not put spaces in front of parentheses used in function calls.
    • Put spaces around all C operators and after commas in function calls.
    • Do not use the comma operator to produce multiple side effects, exceptin for loop initialization and increment parts, and in macro bodies.
    • Use real TABs for indenting, not spaces.
    • Use the “K&R” brace layout style.
    • Use comparisons against NULL and '\0' in the conditions ofif,while, and for statements, as well as in the casesofswitch statements, instead of just theplain pointer or character value.
    • Use the TRUE, FALSE and NULL symbolic constantsand the character constant'\0' where appropriate, instead of 1and 0.
    • Provide one-line descriptive comments for each function.
    • Do not use the alloca() function for allocating memory off thestack. Its use causes more portability trouble than is worth the minorbenefit of not having to free the storage. Instead, usemalloc()and free().
    • Do not use comparisons of the form ‘! strcmp(a, b)’ or similar. As Henry Spencer once said, “strcmp() is not a boolean!”Instead, use ‘strcmp(a, b) == 0’.
    • If adding new bit flag values, use explicit hexadecimal constants(0x001,0x002, 0x004, and son on) instead ofshifting one left by successive amounts (‘(1<<0)’, ‘(1<<1)’,and so on).
    NOTE: If I have to reformat your code to follow the coding style used in gawk, I may not bother to integrate your changes at all.

  6. Update the documentation. Along with your new code, please supply new sections and/or chaptersfor this Web page. If at all possible, please use realTexinfo, instead of just supplying unformatted ASCII text (althougheven that is better than no documentation at all). Conventions to be followed in GAWK: Effective AWK Programming are providedafter the ‘@bye’ at the end of the Texinfo source file. If possible, please update theman page as well.

    You will also have to sign paperwork for your documentation changes.

  7. Submit changes as unified diffs. Use ‘diff -u -r -N’ to comparethe originalgawk source tree with your version. I recommend using the GNU version ofdiff. Send the output produced by either run ofdiff to me when yousubmit your changes. (SeeBugs, for the electronic mailinformation.)

    Using this format makes it easy for me to apply your changes to themaster version of thegawk source code (using patch). If I have to apply the changes manually, using a text editor, I maynot do so, particularly if there are lots of changes.

  8. Include an entry for the ChangeLog file with your submission. This helps further minimize the amount of work I have to do,making it easier for me to accept patches.

Although this sounds like a lot of work, please remember that while youmay write the new code, I have to maintain it and support it. If itisn't possible for me to do that with a minimum of extra work, then Iprobably will not.


Previous:  Adding Code,Up:  Additions

C.2.3 Porting gawk to a New Operating System

If you want to portgawk to a new operating system, there areseveral steps:

  1. Follow the guidelines inthe previous sectionconcerning coding style, submission of diffs, and so on.
  2. Be prepared to sign the appropriate paperwork. In order for the FSF to distribute your code, you must either placeyour code in the public domain and submit a signed statement to thateffect, or assign the copyright in your code to the FSF.
  3. When doing a port, bear in mind that your code must coexist peacefullywith the rest ofgawk and the other ports. Avoid gratuitouschanges to the system-independent parts of the code. If at all possible,avoid sprinkling ‘#ifdef’s just for your port throughout thecode.

    If the changes needed for a particular system affect too much of thecode, I probably will not accept them. In such a case, you can, of course,distribute your changes on your own, as long as you complywith the GPL(seeCopying).

  4. A number of the files that come with gawk are maintained by otherpeople. Thus, you should not change themunless it is for a very good reason; i.e., changes are not out of thequestion, but changes to these files are scrutinized extra carefully. The files are dfa.c,dfa.h, getopt1.c,getopt.c,getopt.h,install-sh, mkinstalldirs,regcomp.c,regex.c,regexec.c, regexex.c,regex.h,regex_internal.c, andregex_internal.h.
  5. Be willing to continue to maintain the port. Non-Unix operating systems are supported by volunteers who maintainthe code needed to compile and rungawk on their systems. If noonevolunteers to maintain a port, it becomes unsupported and it maybe necessary to remove it from the distribution.
  6. Supply an appropriate gawkmisc.??? file. Each port has its owngawkmisc.??? that implements certainoperating system specific functions. This is cleaner than a plethora of‘#ifdef’s scattered throughout the code. Thegawkmisc.c inthe main source directory includes the appropriategawkmisc.??? file from each subdirectory. Be sure to update it as well.

    Each port's gawkmisc.??? file has a suffix reminiscent of the machineor operating system for the port—for example,pc/gawkmisc.pc andvms/gawkmisc.vms. The use of separate suffixes, instead of plaingawkmisc.c, makes it possible to move files from a port's subdirectoryinto the main subdirectory, without accidentally destroying the realgawkmisc.c file. (Currently, this is only an issue for thePC operating system ports.)

  7. Supply a Makefile as well as any other C source and header files that arenecessary for your operating system. All your code should be in aseparate subdirectory, with a name that is the same as, or reminiscentof, either your operating system or the computer system. If possible,try to structure things so that it is not necessary to move files outof the subdirectory into the main source directory. If that is notpossible, then be sure to avoid using names for your files thatduplicate the names of files in the main source directory.
  8. Update the documentation. Please write a section (or sections) for this Web page describing theinstallation and compilation steps needed to compile and/or installgawk for your system.

Following these steps makes it much easier to integrate your changesinto gawk and have them coexist happily with otheroperating systems' code that is already there.

In the code that you supply and maintain, feel free to use acoding style and brace layout that suits your taste.


Next:  ,Previous:  Additions,Up:  Notes

C.3 Adding New Built-in Functions to gawk

Danger Will Robinson! Danger!!
Warning! Warning!

The Robot

It is possible to add new built-infunctions to gawk using dynamically loaded libraries. Thisfacility is available on systems (such as GNU/Linux) that supportthe Cdlopen() and dlsym() functions. This section describes how to write and use dynamicallyloaded extensions forgawk. Experience with programming inC or C++ is necessary when reading this section.

CAUTION: The facilities described in this sectionare very much subject to change in a future gawk release. Be aware that you may have to re-do everything,at some future time.

If you have written your own dynamic extensions,be sure to recompile them for each newgawk release. There is no guarantee of binary compatibility between differentreleases, nor will there ever be such a guarantee.

NOTE: When --sandbox is specified, extensions are disabled(see Options.
C.3.1 A Minimal Introduction to gawk Internals

The truth is thatgawk was not designed for simple extensibility. The facilities for adding functions using shared libraries work, butare something of a “bag on the side.” Thus, this tour isbrief and simplistic; would-begawk hackers are encouraged tospend some time reading the source code before trying to writeextensions based on the material presented here. Of particular noteare the filesawk.h, builtin.c, andeval.c. Reading awkgram.y in order to see how the parse tree is builtwould also be of use.

With the disclaimers out of the way, the following types, structuremembers, functions, and macros are declared inawk.h and are ofuse when writing extensions. The next sectionshows how they are used:

AWKNUM
An AWKNUM is the internal type of awkfloating-point numbers. Typically, it is a C double.


NODE
Just about everything is done using objects of type NODE. These contain both strings and numbers, as well as variables and arrays.


AWKNUM force_number(NODE *n)
This macro forces a value to be numeric. It returns the actualnumeric value contained in the node. It may end up calling an internal gawk function.


void force_string(NODE *n)
This macro guarantees that a NODE's string value is current. It may end up calling an internal gawk function. It also guarantees that the string is zero-terminated.


void force_wstring(NODE *n)
Similarly, thismacro guarantees that a NODE's wide-string value is current. It may end up calling an internal gawk function. It also guarantees that the wide string is zero-terminated.


size_t get_curfunc_arg_count(void)
This function returns the actual number of parameters passedto the current function. Inside the code of an extensionthis can be used to determine the maximum index which issafe to use with get_actual_argument. If this value isgreater than nargs, the function wascalled incorrectly from the awk program.


nargs
Inside an extension function, this is the maximum number ofexpected parameters, as set by the make_builtin() function.


n->stptr n->stlen
The data and length of a NODE's string value, respectively. The string is not guaranteed to be zero-terminated. If you need to pass the string value to a C library function, savethe value in n->stptr[n->stlen], assign '\0' to it,call the routine, and then restore the value.


n->wstptr n->wstlen
The data and length of a NODE's wide-string value, respectively. Use force_wstring() to make sure these values are current.


n->type
The type of the NODE. This is a C enum. Values shouldbe one of Node_var, Node_var_new, or Node_var_arrayfor function parameters.


n->vname
The “variable name” of a node. This is not of much use insideexternally written extensions.


void assoc_clear(NODE *n)
Clears the associative array pointed to by n. Make sure that ‘ n->type == Node_var_array’ first.


NODE **assoc_lookup(NODE *symbol, NODE *subs, int reference)
Finds, and installs if necessary, array elements. symbol is the array, subs is the subscript. This is usually a value created with make_string() (see below). reference should be TRUE if it is an error to use thevalue before it is created. Typically, FALSE is thecorrect value to use from extension functions.


NODE *make_string(char *s, size_t len)
Take a C string and turn it into a pointer to a NODE thatcan be stored appropriately. This is permanent storage; understandingof gawk memory management is helpful.


NODE *make_number(AWKNUM val)
Take an AWKNUM and turn it into a pointer to a NODE thatcan be stored appropriately. This is permanent storage; understandingof gawk memory management is helpful.


NODE *dupnode(NODE *n)
Duplicate a node. In most cases, this increments an internalreference count instead of actually duplicating the entire NODE;understanding of gawk memory management is helpful.


void unref(NODE *n)
This macro releases the memory associated with a NODEallocated with make_string() or make_number(). Understanding of gawk memory management is helpful.


void make_builtin(const char *name, NODE *(*func)(NODE *), int count)
Register a C function pointed to by func as new built-infunction name. name is a regular C string. countis the maximum number of arguments that the function takes. The function should be written in the following manner:
          /* do_xxx --- do xxx function for gawk */
          
          NODE *
          do_xxx(int nargs)
          {
              ...
          }


NODE *get_argument(int i)
This function is called from within a C extension function to getthe i-th argument from the function call. The first argument is argument zero.


NODE *get_actual_argument(int i, int optional, int wantarray);
This function retrieves a particular argument i. wantarray is TRUEif the argument should be an array, FALSE otherwise. If optional is TRUE, the argument need not have been supplied. If it wasn't, the returnvalue is NULL. It is a fatal error if optional is TRUE butthe argument was not provided.


get_scalar_argument(i, opt)
This is a convenience macro that calls get_actual_argument().


get_array_argument(i, opt)
This is a convenience macro that calls get_actual_argument().


void update_ERRNO(void)
This function is called from within a C extension function to setthe value of gawk's ERRNO variable, based on the currentvalue of the C errno global variable. It is provided as a convenience.


void update_ERRNO_saved(int errno_saved)
This function is called from within a C extension function to setthe value of gawk's ERRNO variable, based on the errorvalue provided as the argument. It is provided as a convenience.


void register_deferred_variable(const char *name, NODE *(*load_func)(void))
This function is called to register a function to be called when areference to an undefined variable with the given name is encountered. The callback function will never be called if the variable exists already,so, unless the calling code is running at program startup, it should firstcheck whether a variable of the given name already exists. The argument function must return a pointer to a NODE containing thenewly created variable. This function is used to implement the builtin ENVIRON and PROCINFO arrays, so you can refer to themfor examples.


void register_open_hook(void *(*open_func)(IOBUF *))
This function is called to register a function to be called whenevera new data file is opened, leading to the creation of an IOBUFstructure in iop_alloc(). After creating the new IOBUF, iop_alloc() will call (in reverse order of registration, so the lastfunction registered is called first) each open hook until one returnsnon- NULL. If any hook returns a non- NULL value, that value is assignedto the IOBUF's opaque field (which will presumably pointto a structure containing additional state associated with the inputprocessing), and no further open hooks are called.

The function called will most likely want to set the IOBUF'sget_record method to indicate that future input records shouldbe retrieved by calling that method instead of using the standardgawk input processing.

And the function will also probably want to set the IOBUF'sclose_func method to be called when the file is closed to cleanup any state associated with the input.

Finally, hook functions should be prepared to receive an IOBUFstructure where thefd field is set to INVALID_HANDLE,meaning that gawk was not able to open the file itself. Inthis case, the hook function must be able to successfully open the fileand place a valid file descriptor there.

Currently, for example, the hook function facility is used to implementthe XML parser shared library extension. For more info, please look inawk.h and inio.c.

An argument that is supposed to be an array needs to be handled withsome extra code, in case the array being passed in is actuallyfrom a function parameter.

The following boilerplate code shows how to do this:

     NODE *the_arg;
     
     /* assume need 3rd arg, 0-based */
     the_arg = get_array_argument(2, FALSE);

Again, you should spend time studying the gawk internals;don't just blindly copy this code.


Next:  ,Previous:  Internals,Up:  Dynamic Extensions

C.3.2 Extension Licensing

Every dynamic extension should define the global symbolplugin_is_GPL_compatible to assert that it has been licensed undera GPL-compatible license. If this symbol does not exist,gawkwill emit a fatal error and exit.

The declared type of the symbol should be int. It does not needto be in any allocated section, though. The code merely asserts thatthe symbol exists in the global scope. Something like this is enough:

     int plugin_is_GPL_compatible;
C.3.3 Example: Directory and File Operation Built-ins

Two useful functions that are not in awk arechdir()(so that an awk program can change its directory) andstat() (so that anawk program can gather information abouta file). This section implements these functions forgawk in anexternal extension library.

C.3.3.1 Using chdir() and stat()

This section shows how to use the new functions at the awklevel once they've been integrated into the runninggawkinterpreter. Using chdir() is very straightforward. It takes one argument,the new directory to change to:

     ...
     newdir = "/home/arnold/funstuff"
     ret = chdir(newdir)
     if (ret < 0) {
         printf("could not change to %s: %s\n",
                        newdir, ERRNO) > "/dev/stderr"
         exit 1
     }
     ...

The return value is negative if the chdir failed,and ERRNO(seeBuilt-in Variables)is set to a string indicating the error.

Using stat() is a bit more complicated. The C stat() function fills in a structure that has a fairamount of information. The right way to model this inawk is to fill in an associativearray with the appropriate information:

     file = "/home/arnold/.profile"
     fdata[1] = "x"    # force `fdata' to be an array
     ret = stat(file, fdata)
     if (ret < 0) {
         printf("could not stat %s: %s\n",
                  file, ERRNO) > "/dev/stderr"
         exit 1
     }
     printf("size of %s is %d bytes\n", file, fdata["size"])

The stat() function always clears the data array, even ifthe stat() fails. It fills in the following elements:

"name"
The name of the file that was stat()'ed.
"dev" "ino"
The file's device and inode numbers, respectively.
"mode"
The file's mode, as a numeric value. This includes both the file'stype and its permissions.
"nlink"
The number of hard links (directory entries) the file has.
"uid" "gid"
The numeric user and group ID numbers of the file's owner.
"size"
The size in bytes of the file.
"blocks"
The number of disk blocks the file actually occupies. This may notbe a function of the file's size if the file has holes.
"atime" "mtime" "ctime"
The file's last access, modification, and inode update times,respectively. These are numeric timestamps, suitable for formattingwith strftime()(see Built-in).
"pmode"
The file's “printable mode.” This is a string representation ofthe file's type and permissions, such as what is produced by‘ ls -l’—for example, "drwxr-xr-x".
"type"
A printable string representation of the file's type. The valueis one of the following:
"blockdev" "chardev"
The file is a block or character device (“special file”).
"directory"
The file is a directory.
"fifo"
The file is a named-pipe (also known as a FIFO).
"file"
The file is just a regular file.
"socket"
The file is an AF_UNIX (“Unix domain”) socket in thefilesystem.
"symlink"
The file is a symbolic link.

Several additional elements may be present depending upon the operatingsystem and the type of the file. You can test for them in yourawkprogram by using the in operator(seeReference to Elements):

"blksize"
The preferred block size for I/O to the file. This field is notpresent on all POSIX-like systems in the C stat structure.
"linkval"
If the file is a symbolic link, this element is the name of thefile the link points to (i.e., the value of the link).
"rdev" "major" "minor"
If the file is a block or character device file, then these valuesrepresent the numeric device number and the major and minor componentsof that number, respectively.
C.3.3.2 C Code for chdir() and stat()

Here is the C code for these extensions. They were written forGNU/Linux. The code needs some more work for complete portabilityto other POSIX-compliant systems:83

     #include "awk.h"
     
     #include <sys/sysmacros.h>
     
     int plugin_is_GPL_compatible;
     
     /*  do_chdir --- provide dynamically loaded chdir() builtin for gawk */
     
     static NODE *
     do_chdir(int nargs)
     {
         NODE *newdir;
         int ret = -1;
     
         if (do_lint && get_curfunc_arg_count() != 1)
             lintwarn("chdir: called with incorrect number of arguments");
     
         newdir = get_scalar_argument(0, FALSE);

The file includes the "awk.h" header file for definitionsfor the gawk internals. It includes <sys/sysmacros.h>for access to themajor() and minor() macros.

By convention, for anawk function foo, the function thatimplements it is called ‘do_foo’. The function should takea ‘int’ argument, usually callednargs, thatrepresents the number of defined arguments for the function. Thenewdirvariable represents the new directory to change to, retrievedwithget_scalar_argument(). Note that the first argument isnumbered zero.

This code actually accomplishes the chdir(). It first forcesthe argument to be a string and passes the string value to thechdir() system call. If thechdir() fails, ERRNOis updated.

         (void) force_string(newdir);
         ret = chdir(newdir->stptr);
         if (ret < 0)
             update_ERRNO();

Finally, the function returns the return value to the awk level:

         return make_number((AWKNUM) ret);
     }

The stat() built-in is more involved. First comes a functionthat turns a numeric mode into a printable representation(e.g., 644 becomes ‘-rw-r--r--’). This is omitted here for brevity:

     /* format_mode --- turn a stat mode field into something readable */
     
     static char *
     format_mode(unsigned long fmode)
     {
         ...
     }

Next comes the do_stat() function. It starts withvariable declarations and argument checking:

     /* do_stat --- provide a stat() function for gawk */
     
     static NODE *
     do_stat(int nargs)
     {
         NODE *file, *array, *tmp;
         struct stat sbuf;
         int ret;
         NODE **aptr;
         char *pmode;    /* printable mode */
         char *type = "unknown";
     
         if (do_lint && get_curfunc_arg_count() > 2)
             lintwarn("stat: called with too many arguments");

Then comes the actual work. First, the function gets the arguments. Then, it always clears the array. The code uselstat() (instead of stat())to get the file information,in case the file is a symbolic link. If there's an error, it setsERRNO and returns:

         /* file is first arg, array to hold results is second */
         file = get_scalar_argument(0, FALSE);
         array = get_array_argument(1, FALSE);
     
         /* empty out the array */
         assoc_clear(array);
     
         /* lstat the file, if error, set ERRNO and return */
         (void) force_string(file);
         ret = lstat(file->stptr, & sbuf);
         if (ret < 0) {
             update_ERRNO();
             return make_number((AWKNUM) ret);
         }

Now comes the tedious part: filling in the array. Only a few of thecalls are shown here, since they all follow the same pattern:

         /* fill in the array */
         aptr = assoc_lookup(array, tmp = make_string("name", 4), FALSE);
         *aptr = dupnode(file);
         unref(tmp);
     
         aptr = assoc_lookup(array, tmp = make_string("mode", 4), FALSE);
         *aptr = make_number((AWKNUM) sbuf.st_mode);
         unref(tmp);
     
         aptr = assoc_lookup(array, tmp = make_string("pmode", 5), FALSE);
         pmode = format_mode(sbuf.st_mode);
         *aptr = make_string(pmode, strlen(pmode));
         unref(tmp);

When done, return the lstat() return value:

     
         return make_number((AWKNUM) ret);
     }

Finally, it's necessary to provide the “glue” that loads thenew function(s) intogawk. By convention, each library hasa routine nameddlload() that does the job:

     /* dlload --- load new builtins in this library */
     
     NODE *
     dlload(NODE *tree, void *dl)
     {
         make_builtin("chdir", do_chdir, 1);
         make_builtin("stat", do_stat, 2);
         return make_number((AWKNUM) 0);
     }

And that's it! As an exercise, consider adding functions toimplement system calls such aschown(), chmod(),and umask().


Previous:  Internal File Ops,Up:  Sample Library

C.3.3.3 Integrating the Extensions

Now that the code is written, it must be possible to add it atruntime to the runninggawk interpreter. First, thecode must be compiled. Assuming that the functions are ina file namedfilefuncs.c, and idir is the locationof thegawk include files,the following steps createa GNU/Linux shared library:

     $ gcc -fPIC -shared -DHAVE_CONFIG_H -c -O -g -Iidir filefuncs.c
     $ ld -o filefuncs.so -shared filefuncs.o

Once the library exists, it is loaded by calling theextension()built-in function. This function takes two arguments: the name of thelibrary to load and the name of a function to call when the libraryis first loaded. This function adds the new functions togawk. It returns the value returned by the initialization functionwithin the shared library:

     # file testff.awk
     BEGIN {
         extension("./filefuncs.so", "dlload")
     
         chdir(".")  # no-op
     
         data[1] = 1 # force `data' to be an array
         print "Info for testff.awk"
         ret = stat("testff.awk", data)
         print "ret =", ret
         for (i in data)
             printf "data[\"%s\"] = %s\n", i, data[i]
         print "testff.awk modified:",
             strftime("%m %d %y %H:%M:%S", data["mtime"])
     
         print "\nInfo for JUNK"
         ret = stat("JUNK", data)
         print "ret =", ret
         for (i in data)
             printf "data[\"%s\"] = %s\n", i, data[i]
         print "JUNK modified:", strftime("%m %d %y %H:%M:%S", data["mtime"])
     }

Here are the results of running the program:

     $ gawk -f testff.awk
     -| Info for testff.awk
     -| ret = 0
     -| data["size"] = 607
     -| data["ino"] = 14945891
     -| data["name"] = testff.awk
     -| data["pmode"] = -rw-rw-r--
     -| data["nlink"] = 1
     -| data["atime"] = 1293993369
     -| data["mtime"] = 1288520752
     -| data["mode"] = 33204
     -| data["blksize"] = 4096
     -| data["dev"] = 2054
     -| data["type"] = file
     -| data["gid"] = 500
     -| data["uid"] = 500
     -| data["blocks"] = 8
     -| data["ctime"] = 1290113572
     -| testff.awk modified: 10 31 10 12:25:52
     -|
     -| Info for JUNK
     -| ret = -1
     -| JUNK modified: 01 01 70 02:00:00


Previous:  Dynamic Extensions,Up:  Notes

C.4 Probable Future Extensions

AWK is a language similar to PERL, only considerably more elegant.
Arnold Robbins

Hey!
Larry Wall

This section briefly lists extensions and possible improvementsthat indicate the directions we arecurrently considering forgawk. The file FUTURES in thegawk distribution lists these extensions as well.

Following is a list of probable future changes visible at theawk language level:

Loadable module interface
It is not clear that the awk-level interface to themodules facility is as good as it should be. The interface needs to beredesigned, particularly taking namespace issues into account, aswell as possibly including issues such as library search path orderand versioning.
RECLEN variable for fixed-length records
Along with FIELDWIDTHS, this would speed up the processing offixed-length records. PROCINFO["RS"] would be "RS" or "RECLEN",depending upon which kind of record processing is in effect.
Databases
It may be possible to map a GDBM/NDBM/SDBM file into an awk array.
More lint warnings
There are more things that could be checked for portability.

Following is a list of probable improvements that will make gawk'ssource code easier to work with:

Loadable module mechanics
The current extension mechanism works(see Dynamic Extensions),but is rather primitive. It requires a fair amount of manual workto create and integrate a loadable module. Nor is the current mechanism as portable as might be desired. The GNU libtool package provides a number of features thatwould make using loadable modules much easier. gawk should be changed to use libtool.
Loadable module internals
The API to its internals that gawk “exports” should be revised. Too many things are needlessly exposed. A new API should be designedand implemented to make module writing easier.
Better array subscript management
gawk's management of array subscript storage could use revamping,so that using the same value to index multiple arrays onlystores one copy of the index value.

Finally,the programs in the test suite could use documenting in this Web page.

See Additions,if you are interested in tackling any of these projects.


Next:  ,Previous:  Notes,Up:  Top

Appendix D Basic Programming Concepts

This appendix attempts to define some of the basic conceptsand terms that are used throughout the rest of this Web page. As this Web page is specifically about awk,and not about computer programming in general, the coverage hereis by necessity fairly cursory and simplistic. (If you need more background, there are manyother introductory texts that you should refer to instead.)

D.1 What a Program Does

At the most basic level, the job of a program is to processsome input data and produce results.

                       _______
     +------+         /       \         +---------+
     | Data | -----> < Program > -----> | Results |
     +------+         \_______/         +---------+

The “program” in the figure can be either a compiledprogram84(such asls),or it may be interpreted. In the latter case, a machine-executableprogram such asawk reads your program, and then uses theinstructions in your program to process the data.

When you write a program, it usually consistsof the following, very basic set of steps:

                                   ______
     +----------------+           / More \  No       +----------+
     | Initialization | -------> <  Data  > -------> | Clean Up |
     +----------------+    ^      \   ?  /           +----------+
                           |       +--+-+
                           |          | Yes
                           |          |
                           |          V
                           |     +---------+
                           +-----+ Process |
                                 +---------+
Initialization
These are the things you do before actually starting to processdata, such as checking arguments, initializing any data you needto work with, and so on. This step corresponds to awk's BEGIN rule(see BEGIN/END).

If you were baking a cake, this might consist of laying out all themixing bowls and the baking pan, and making sure you have all theingredients that you need.

Processing
This is where the actual work is done. Your program reads data,one logical chunk at a time, and processes it as appropriate.

In most programming languages, you have to manually manage the readingof data, checking to see if there is more each time you read a chunk.awk's pattern-action paradigm(see Getting Started)handles the mechanics of this for you.

In baking a cake, the processing corresponds to the actual labor:breaking eggs, mixing the flour, water, and other ingredients, and then putting the cakeinto the oven.

Clean Up
Once you've processed all the data, you may have things you need todo before exiting. This step corresponds to awk's END rule(see BEGIN/END).

After the cake comes out of the oven, you still have to wrap it inplastic wrap to keep anyone from tasting it, as well as washthe mixing bowls and utensils.

An algorithm is a detailed set of instructions necessary to accomplisha task, or process data. It is much the same as a recipe for bakinga cake. Programs implement algorithms. Often, it is up to you to designthe algorithm and implement it, simultaneously.

The “logical chunks” we talked about previously are calledrecords,similar to the records a company keeps on employees, a school keeps forstudents, or a doctor keeps for patients. Each record has many component parts, such as first and last names,date of birth, address, and so on. The component parts are referredto as the fields of the record.

The act of reading data is termed input, and that ofgenerating results, not too surprisingly, is termedoutput. They are often referred to together as “input/output,”and even more often, as “I/O” for short. (You will also see “input” and “output” used as verbs.)

awk manages the reading of data for you, as well as thebreaking it up into records and fields. Your program's job is totell awk what to do with the data. You do this by describingpatterns in the data to look for, andactions to executewhen those patterns are seen. This data-driven nature ofawk programs usually makes them both easier to writeand easier to read.

D.2 Data Values in a Computer

In a program,you keep track of information and values in things calledvariables. A variable is just a name for a given value, such as first_name,last_name, address, and so on. awk has several predefined variables, and it hasspecial names to refer to the current input recordand the fields of the record. You may also group multipleassociated values under one name, as an array.

Data, particularly inawk, consists of either numericvalues, such as 42 or 3.1415927, or string values. String values are essentially anything that's not a number, such as a name. Strings are sometimes referred to ascharacter data, since theystore the individual characters that comprise them. Individual variables, as well as numeric and string variables, arereferred to asscalar values. Groups of values, such as arrays, are not scalars.

Within computers, there are two kinds of numeric values:integersand floating-point. In school, integer values were referred to as “whole” numbers—that is,numbers without any fractional part, such as 1, 42, or −17. The advantage to integer numbers is that they represent values exactly. The disadvantage is that their range is limited. On most systems,this range is −2,147,483,648 to 2,147,483,647. However, many systems now support a range from−9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Integer values come in two flavors:signed and unsigned. Signed values may be negative or positive, with the range of values justdescribed. Unsigned values are always positive. On most systems,the range is from 0 to 4,294,967,295. However, many systems now support a range from0 to 18,446,744,073,709,551,615.

Floating-point numbers represent what are called “real” numbers; i.e.,those that do have a fractional part, such as 3.1415927. The advantage to floating-point numbers is that theycan represent a much larger range of values. The disadvantage is that there are numbers that they cannot representexactly.awk uses double precision floating-point numbers, whichcan hold more digits thansingle precisionfloating-point numbers. Floating-point issues are discussed more fully inFloating Point Issues.

At the very lowest level, computers store values as groups of binary digits,orbits. Modern computers group bits into groups of eight, called bytes. Advanced applications sometimes have to manipulate bits directly,andgawk provides functions for doing so.

While you are probably used to the idea of a number without a value (i.e., zero),it takes a bit more getting used to the idea of zero-length character data. Nevertheless, such a thing exists. It is called thenull string. The null string is character data that has no value. In other words, it is empty. It is written inawk programslike this: "".

Humans are used to working in decimal; i.e., base 10. In base 10,numbers go from 0 to 9, and then “roll over” into the nextcolumn. (Remember grade school? 42 is 4 times 10 plus 2.)

There are other number bases though. Computers commonly use base 2or binary, base 8 oroctal, and base 16 or hexadecimal. In binary, each column represents two times the value in the column toits right. Each column may contain either a 0 or a 1. Thus, binary 1010 represents 1 times 8, plus 0 times 4, plus 1 times 2,plus 0 times 1, or decimal 10. Octal and hexadecimal are discussed more inNondecimal-numbers.

Programs are written in programming languages. Hundreds, if not thousands, of programming languages exist. One of the most popular is the C programming language. The C language had a very strong influence on the design oftheawk language.

There have been several versions of C. The first is often referred toas “K&R” C, after the initials of Brian Kernighan and Dennis Ritchie,the authors of the first book on C. (Dennis Ritchie created the language,and Brian Kernighan was one of the creators ofawk.)

In the mid-1980s, an effort began to produce an international standardfor C. This work culminated in 1989, with the production of the ANSIstandard for C. This standard became an ISO standard in 1990. In 1999, a revised ISO C standard was approved and released. Where it makes sense, POSIX awk is compatible with 1999 ISO C.


Previous:  Basic Data Typing,Up:  Basic Concepts

D.3 Floating-Point Number Caveats

As mentioned earlier, floating-point numbers represent what are called“real” numbers, i.e., those that have a fractional part.awkuses double precision floating-point numbers to represent allnumeric values. This section describes some of the issuesinvolved in using floating-point numbers.

There is a very nicepaper on floating-point arithmeticby David Goldberg,“What Every Computer Scientist Should Know About Floating-point Arithmetic,”ACM Computing Surveys23, 1 (1991-03), 5-48. This is worth reading if you are interested in the details,but it does require a background in computer science.

D.3.1 The String Value Can Lie

Internally, awk keeps both the numeric value(double precision floating-point) and the string value for a variable. Separately,awk keepstrack of what type the variable has(seeTyping and Comparison),which plays a role in how variables are used in comparisons.

It is important to note that the string value for a number may notreflect the full value (all the digits) that the numeric valueactually contains. The following program (values.awk) illustrates this:

     {
        sum = $1 + $2
        # see it for what it is
        printf("sum = %.12g\n", sum)
        # use CONVFMT
        a = "<" sum ">"
        print "a =", a
        # use OFMT
        print "sum =", sum
     }

This program shows the full value of the sum of $1 and$2using printf, and then prints the string values obtainedfrom both automatic conversion (viaCONVFMT) andfrom printing (via OFMT).

Here is what happens when the program is run:

     $ echo 3.654321 1.2345678 | awk -f values.awk
     -| sum = 4.8888888
     -| a = <4.88889>
     -| sum = 4.88889

This makes it clear that the full numeric value is different fromwhat the default string representations show.

CONVFMT's default value is "%.6g", which yields a value withat least six significant digits. For some applications, you might want tochange it to specify more precision. On most modern machines, most of the time,17 digits is enough to capture a floating-point number'svalue exactly.85

D.3.2 Floating Point Numbers Are Not Abstract Numbers

Unlike numbers in the abstract sense (such as what you studied in high schoolor college math), numbers stored in computers are limited in certain ways. They cannot represent an infinite number of digits, nor can they alwaysrepresent things exactly. In particular,floating-point numbers cannotalways represent values exactly. Here is an example:

     $ awk '{ printf("%010d\n", $1 * 100) }'
     515.79
     -| 0000051579
     515.80
     -| 0000051579
     515.81
     -| 0000051580
     515.82
     -| 0000051582
     Ctrl-d

This shows that some values can be represented exactly,whereas others are only approximated. This is not a “bug”inawk, but simply an artifact of how computersrepresent numbers.

Another peculiarity of floating-point numbers on modern systemsis that they often have more than one representation for the number zero! In particular, it is possible to represent “minus zero” as well asregular, or “positive” zero.

This example shows that negative and positive zero are distinct valueswhen stored internally, but that they are in fact equal to each other,as well as to “regular” zero:

     $ gawk 'BEGIN { mz = -0 ; pz = 0
     > printf "-0 = %g, +0 = %g, (-0 == +0) -> %d\n", mz, pz, mz == pz
     > printf "mz == 0 -> %d, pz == 0 -> %d\n", mz == 0, pz == 0
     > }'
     -| -0 = -0, +0 = 0, (-0 == +0) -> 1
     -| mz == 0 -> 1, pz == 0 -> 1

It helps to keep this in mind should you process numeric datathat contains negative zero values; the fact that the zero is negativeis noted and can affect comparisons.

D.3.3 Standards Versus Existing Practice

Historically, awk has converted any non-numeric looking stringto the numeric value zero, when required. Furthermore, the originaldefinition of the language and the original POSIX standards specified thatawk only understands decimal numbers (base 10), and not octal(base 8) or hexadecimal numbers (base 16).

Changes in the language of the2001 and 2004 POSIX standard can be interpreted to imply thatawkshould support additional features. These features are:

  • Interpretation of floating point data values specified in hexadecimalnotation (‘0xDEADBEEF’). (Note: data values,notsource code constants.)
  • Support for the special IEEE 754 floating point values “Not A Number”(NaN), positive Infinity (“inf”) and negative Infinity (“−inf”). In particular, the format for these values is as specified by the ISO 1999C standard, which ignores case and can allow machine-dependent additionalcharacters after the ‘nan’ and allow either ‘inf’ or ‘infinity’.

The first problem is that both of these are clear changes to historicalpractice:

  • The gawk maintainer feels that supporting hexadecimal floatingpoint values, in particular, is ugly, and was never intended by theoriginal designers to be part of the language.
  • Allowing completely alphabetic strings to have valid numericvalues is also a very severe departure from historical practice.

The second problem is that the gawk maintainer feels that thisinterpretation of the standard, which requires a certain amount of“language lawyering” to arrive at in the first place, was not evenintended by the standard developers. In other words, “we see how yougot where you are, but we don't think that that's where you want to be.”

The 2008 POSIX standard added explicit wording to allow, but not require,that awk support hexadecimal floating point values andspecial values for “Not A Number” and infinity.

Although the gawk maintainer continues to feel thatproviding those features is inadvisable,nevertheless, on systems that support IEEE floating point, it seemsreasonable to providesome way to support NaN and Infinity values. The solution implemented ingawk is as follows:

  • With the --posix command-line option,gawk becomes“hands off.” String values are passed directly to the system library'sstrtod() function, and if it successfully returns a numeric value,that is what's used.86By definition, the results are not portable acrossdifferent systems. They are also a little surprising:
              $ echo nanny | gawk --posix '{ print $1 + 0 }'
              -| nan
              $ echo 0xDeadBeef | gawk --posix '{ print $1 + 0 }'
              -| 3735928559
    
  • Without --posix, gawk interprets the four strings‘+inf’,‘-inf’,‘+nan’,and‘-nan’specially, producing the corresponding special numeric values. The leading sign acts a signal togawk (and the user)that the value is really numeric. Hexadecimal floating point isnot supported (unless you also use--non-decimal-data,which is not recommended). For example:
              $ echo nanny | gawk '{ print $1 + 0 }'
              -| 0
              $ echo +nan | gawk '{ print $1 + 0 }'
              -| nan
              $ echo 0xDeadBeef | gawk '{ print $1 + 0 }'
              -| 0
    

    gawk does ignore case in the four special values. Thus ‘+nan’ and ‘+NaN’ are the same.


Next:  ,Previous:  Basic Concepts,Up:  Top

Glossary

Action
A series of awk statements attached to a rule. If the rule'spattern matches an input record, awk executes therule's action. Actions are always enclosed in curly braces. (See Action Overview.)


Amazing awk Assembler
Henry Spencer at the University of Toronto wrote a retargetable assemblercompletely as sed and awk scripts. It is thousandsof lines long, including machine descriptions for several eight-bitmicrocomputers. It is a good example of a program that would have beenbetter written in another language. You can get it from http://awk.info/?awk100/aaa.


Ada
A programming language originally defined by the U.S. Department ofDefense for embedded programming. It was designed to enforce goodSoftware Engineering practices.


Amazingly Workable Formatter ( awf)
Henry Spencer at the University of Toronto wrote a formatter that acceptsa large subset of the ‘ nroff -ms’ and ‘ nroff -man’ formattingcommands, using awk and sh. It is availablefrom http://awk.info/?tools/awf.
Anchor
The regexp metacharacters ‘ ^’ and ‘ $’, which force the matchto the beginning or end of the string, respectively.


ANSI
The American National Standards Institute. This organization producesmany standards, among them the standards for the C and C++ programminglanguages. These standards often become international standards as well. See also“ISO.”
Array
A grouping of multiple values under the same name. Most languages just provide sequential arrays. awk provides associative arrays.
Assertion
A statement in a program that a condition is true at this point in the program. Useful for reasoning about how a program is supposed to behave.
Assignment
An awk expression that changes the value of some awkvariable or data object. An object that you can assign to is called an lvalue. The assigned values are called rvalues. See Assignment Ops.
Associative Array
Arrays in which the indices may be numbers or strings, not justsequential integers in a fixed range.
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 recordgiven 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.
Bash
The GNU version of the standard shell(the Bourne- Again SHell). See also “Bourne Shell.”
BBS
See “Bulletin Board System.”
Bit
Short for “Binary Digit.”All values in computer memory ultimately reduce to binary digits: valuesthat are either zero or one. Groups of bits may be interpreted differently—as integers,floating-point numbers, character data, addresses of othermemory objects, or other data. awk lets you work with floating-point numbers and strings. gawk lets you manipulate bit values with the built-infunctions described in Bitwise Functions.

Computers are often defined by how many bits they use to represent integervalues. Typical systems are 32-bit systems, but 64-bit systems arebecoming increasingly popular, and 16-bit systems have essentiallydisappeared.

Boolean Expression
Named after the English mathematician Boole. See also “Logical Expression.”
Bourne Shell
The standard shell ( /bin/sh) on Unix and Unix-like systems,originally written by Steven R. Bourne. Many shells (Bash, ksh, pdksh, zsh) aregenerally upwardly compatible with the Bourne shell.
Built-in Function
The awk language provides built-in functions that perform variousnumerical, I/O-related, and string computations. Examples are sqrt() (for the square root of a number) and substr() (for asubstring of a string). gawk provides functions for timestamp management, bit manipulation,array sorting, type checking,and runtime string translation. (See Built-in.)
Built-in Variable
ARGC, ARGV, CONVFMT, ENVIRON, FILENAME, FNR, FS, NF, NR, OFMT, OFS, ORS, RLENGTH, RSTART, RS,and SUBSEPare the variables that have special meaning to awk. In addition, ARGIND, BINMODE, ERRNO, FIELDWIDTHS, FPAT, IGNORECASE, LINT, PROCINFO, RT,and TEXTDOMAINare the variables that have special meaning to gawk. Changing some of them affects awk's running environment. (See Built-in Variables.)
Braces
See “Curly Braces.”
Bulletin Board System
A computer system allowing users to log in and read and/or leave messagesfor other users of the system, much like leaving paper notes on a bulletinboard.
C
The system programming language that most GNU software is written in. The awk programming language has C-like syntax, and this Web pagepoints out similarities between awk and C when appropriate.

In general, gawk attempts to be as similar to the 1990 versionof ISO C as makes sense.

C++
A popular object-oriented programming language derived from C.


Character Set
The set of numeric codes used by a computer system to represent thecharacters (letters, numbers, punctuation, etc.) of a particular countryor place. The most common character set in use today is ASCII (AmericanStandard Code for Information Interchange). Many Europeancountries use an extension of ASCII known as ISO-8859-1 (ISO Latin-1). The Unicode character set isbecoming increasingly popular and standard, and is particularlywidely used on GNU/Linux systems.


CHEM
A preprocessor for pic that reads descriptions of moleculesand produces pic input for drawing them. It was written in awkby Brian Kernighan and Jon Bentley, and is available from http://netlib.sandia.gov/netlib/typesetting/chem.gz.
Coprocess
A subordinate program with which two-way communications is possible.


Compiler
A program that translates human-readable source code intomachine-executable object code. The object code is then executeddirectly by the computer. See also “Interpreter.”
Compound Statement
A series of awk statements, enclosed in curly braces. Compoundstatements may be nested. (See Statements.)
Concatenation
Concatenating two strings means sticking them together, one after another,producing a new string. For example, the string ‘ foo’ concatenated withthe string ‘ bar’ gives the string ‘ foobar’. (See Concatenation.)
Conditional Expression
An expression using the ‘ ?:’ ternary operator, such as‘ expr1 ?expr2 : expr3’. The expression expr1 is evaluated; if the result is true, the value of the wholeexpression is the value of expr2; otherwise the value is expr3. In either case, only one of expr2 and expr3is evaluated. (See Conditional Exp.)
Comparison Expression
A relation that is either true or false, such as ‘ a < b’. Comparison expressions are used in if, while, do,and forstatements, and in patterns to select which input records to process. (See Typing and Comparison.)
Curly Braces
The characters ‘ {’ and ‘ }’. Curly braces are used in awk for delimiting actions, compound statements, and functionbodies.


Dark Corner
An area in the language where specifications often were (or stillare) not clear, leading to unexpected or undesirable behavior. Such areas are marked in this Web page with“(d.c.)” in the textand are indexed under the heading “dark corner.”
Data Driven
A description of awk programs, where you specify the data youare interested in processing, and what to do when that data is seen.
Data Objects
These are numbers and strings of characters. Numbers are converted intostrings and vice versa, as needed. (See Conversion.)
Deadlock
The situation in which two communicating processes are each waitingfor the other to perform an action.
Debugger
A program used to help developers remove “bugs” from (de-bug)their programs.
Double Precision
An internal representation of numbers that can have fractional parts. Double precision numbers keep track of more digits than do single precisionnumbers, but operations on them are sometimes more expensive. This is the way awk stores numeric values. It is the C type double.
Dynamic Regular Expression
A dynamic regular expression is a regular expression written as anordinary expression. It could be a string constant, such as "foo", but it may also be an expression whose value can vary. (See Computed Regexps.)
Environment
A collection of strings, of the form name = val, that eachprogram has available to it. Users generally place values into theenvironment in order to provide information to various programs. Typicalexamples are the environment variables HOME and PATH.
Empty String
See “Null String.”


Epoch
The date used as the “beginning of time” for timestamps. Time values in most systems are represented as seconds since the epoch,with library functions available for converting these values intostandard date and time formats.

The epoch on Unix and POSIX systems is 1970-01-01 00:00:00 UTC. See also “GMT” and “UTC.”

Escape Sequences
A special sequence of characters used for describing nonprintingcharacters, such as ‘ \n’ for newline or ‘ \033’ for the ASCIIESC (Escape) character. (See Escape Sequences.)
Extension
An additional feature or change to a programming language orutility not defined by that language's or utility's standard. gawk has (too) many extensions over POSIX awk.
FDL
See “Free Documentation License.”
Field
When awk reads an input record, it splits the record into piecesseparated by whitespace (or by a separator regexp that you canchange by setting the built-in variable FS). Such pieces arecalled fields. If the pieces are of fixed length, you can use the built-invariable FIELDWIDTHS to describe their lengths. If you wish to specify the contents of fields instead of the fieldseparator, you can use the built-in variable FPAT to do so. (See Field Separators, Constant Size,and Splitting By Content.)
Flag
A variable whose truth value indicates the existence or nonexistenceof some condition.
Floating-Point Number
Often referred to in mathematical terms as a “rational” or real number,this is just a number that can have a fractional part. See also “Double Precision” and “Single Precision.”
Format
Format strings are used to control the appearance of output in the strftime() and sprintf() functions, and are used in the printf statement as well. Also, data conversions from numbers to stringsare controlled by the format strings contained in the built-in variables CONVFMT and OFMT. (See Control Letters.)
Free Documentation License
This document describes the terms under which this Web pageis published and may be copied. (See GNU Free Documentation License.)
Function
A specialized group of statements used to encapsulate generalor program-specific tasks. awk has a number of built-infunctions, and also allows you to define your own. (See Functions.)
FSF
See “Free Software Foundation.”


Free Software Foundation
A nonprofit organization dedicatedto the production and distribution of freely distributable software. It was founded by Richard M. Stallman, the author of the originalEmacs editor. GNU Emacs is the most widely used version of Emacs today.
gawk
The GNU implementation of awk.


General Public License
This document describes the terms under which gawk and its sourcecode may be distributed. (See Copying.)
GMT
“Greenwich Mean Time.”This is the old term for UTC. It is the time of day used internally for Unix and POSIX systems. See also “Epoch” and “UTC.”


GNU
“GNU's not Unix”. An on-going project of the Free Software Foundationto create a complete, freely distributable, POSIX-compliant computingenvironment.
GNU/Linux
A variant of the GNU system using the Linux kernel, instead of theFree Software Foundation's Hurd kernel. The Linux kernel is a stable, efficient, full-featured clone of Unix that hasbeen ported to a variety of architectures. It is most popular on PC-class systems, but runs well on a variety ofother systems too. The Linux kernel source code is available under the terms of the GNU GeneralPublic License, which is perhaps its most important aspect.
GPL
See “General Public License.”
Hexadecimal
Base 16 notation, where the digits are 09 and AF, with ‘ A’representing 10, ‘ B’ representing 11, and so on, up to ‘ F’ for 15. Hexadecimal numbers are written in C using a leading ‘ 0x’,to indicate their base. Thus, 0x12 is 18 (1 times 16 plus 2). See Nondecimal-numbers.
I/O
Abbreviation for “Input/Output,” the act of moving data into and/orout of a running program.
Input Record
A single chunk of data that is read in by awk. Usually, an awk inputrecord consists of one line of text. (See Records.)
Integer
A whole number, i.e., a number that does not have a fractional part.
Internationalization
The process of writing or modifying a program sothat it can use multiple languages without requiringfurther source code changes.


Interpreter
A program that reads human-readable source code directly, and usesthe instructions in it to process data and produce results. awk is typically (but not always) implemented as an interpreter. See also “Compiler.”
Interval Expression
A component of a regular expression that lets you specify repeated matches ofsome part of the regexp. Interval expressions were not originally availablein awk programs.


ISO
The International Standards Organization. This organization produces international standards for many things, includingprogramming languages, such as C and C++. In the computer arena, important standards like those for C, C++, and POSIXbecome both American national and ISO international standards simultaneously. This Web page refers to Standard C as “ISO C” throughout.


Java
A modern programming language originally developed by Sun Microsystems(now Oracle) supporting Object-Oriented programming. Although usuallyimplemented by compiling to the instructions for a standard virtualmachine (the JVM), the language can be compiled to native code.
Keyword
In the awk language, a keyword is a word that has specialmeaning. Keywords are reserved and may not be used as variable names.

gawk's keywords are:BEGIN,BEGINFILE,END,ENDFILE,break,case,continue,defaultdelete,do...while,else,exit,for...in,for,function,func,if,nextfile,next,switch,andwhile.


Lesser General Public License
This document describes the terms under which binary library archivesor shared objects,and their source code may be distributed.
Linux
See “GNU/Linux.”
LGPL
See “Lesser General Public License.”
Localization
The process of providing the data necessary for aninternationalized program to work in a particular language.
Logical Expression
An expression using the operators for logic, AND, OR, and NOT, written‘ &&’, ‘ ||’, and ‘ !’ in awk. Often called Booleanexpressions, after the mathematician who pioneered this kind ofmathematical logic.
Lvalue
An expression that can appear on the left side of an assignmentoperator. In most languages, lvalues can be variables or arrayelements. In awk, a field designator can also be used as anlvalue.
Matching
The act of testing a string against a regular expression. If theregexp describes the contents of the string, it is said to match it.
Metacharacters
Characters used within a regexp that do not stand for themselves. Instead, they denote regular expression operations, such as repetition,grouping, or alternation.
No-op
An operation that does nothing.
Null String
A string with no characters in it. It is represented explicitly in awk programs by placing two double quote characters next toeach other ( ""). It can appear in input data by having two successiveoccurrences of the field separator appear next to each other.
Number
A numeric-valued data object. Modern awk implementations usedouble precision floating-point to represent numbers. Ancient awk implementations used single precision floating-point.
Octal
Base-eight notation, where the digits are 07. Octal numbers are written in C using a leading ‘ 0’,to indicate their base. Thus, 013 is 11 (one times 8 plus 3). See Nondecimal-numbers.


P1003.1, P1003.2
See “POSIX.”
Pattern
Patterns tell awk which input records are interesting to whichrules.

A pattern is an arbitrary conditional expression against which input istested. If the condition is satisfied, the pattern is said tomatchthe input record. A typical pattern might compare the input record againsta regular expression. (SeePattern Overview.)

POSIX
The name for a series of standardsthat specify a Portable Operating System interface. The “IX” denotesthe Unix heritage of these standards. The main standard of interest for awk users is IEEE Standard for Information Technology, Standard 1003.1-2008. The 2008 POSIX standard can be found online at http://www.opengroup.org/onlinepubs/9699919799/.
Precedence
The order in which operations are performed when operators are usedwithout explicit parentheses.
Private
Variables and/or functions that are meant for use exclusively by libraryfunctions and not for the main awk program. Special care must betaken when naming such variables and functions. (See Library Names.)
Range (of input lines)
A sequence of consecutive lines from the input file(s). A patterncan specify ranges of input lines for awk to process or it canspecify single lines. (See Pattern Overview.)
Recursion
When a function calls itself, either directly or indirectly. As long as this is not clear, refer to the entry for “recursion.”If this is clear, stop, and proceed to the next entry.
Redirection
Redirection means performing input from something other than the standard inputstream, or performing output to something other than the standard output stream.

You can redirect input to the getline statement usingthe ‘<’, ‘|’, and ‘|&’ operators. You can redirect the output of theprint and printf statementsto a file or a system command, using the ‘>’, ‘>>’, ‘|’, and ‘|&’operators. (See Getline,and Redirection.)

Regexp
See “Regular Expression.”
Regular Expression
A regular expression (“regexp” for short) is a pattern that denotes aset of strings, possibly an infinite set. For example, the regular expression‘ R.*xp’ matches any string starting with the letter ‘ R’and ending with the letters ‘ xp’. In awk, regular expressions areused in patterns and in conditional expressions. Regular expressions may containescape sequences. (See Regexp.)
Regular Expression Constant
A regular expression constant is a regular expression written withinslashes, such as /foo/. This regular expression is chosenwhen you write the awk program and cannot be changed duringits execution. (See Regexp Usage.)
Rule
A segment of an awk program that specifies how to process singleinput records. A rule consists of a pattern and an action. awk reads an input record; then, for each rule, if the input recordsatisfies the rule's pattern, awk executes the rule's action. Otherwise, the rule does nothing for that input record.
Rvalue
A value that can appear on the right side of an assignment operator. In awk, essentially every expression has a value. These valuesare rvalues.
Scalar
A single value, be it a number or a string. Regular variables are scalars; arrays and functions are not.
Search Path
In gawk, a list of directories to search for awk program source files. In the shell, a list of directories to search for executable programs.
Seed
The initial value, or starting point, for a sequence of random numbers.
sed
See “Stream Editor.”
Shell
The command interpreter for Unix and POSIX-compliant systems. The shell works both interactively, and as a programming languagefor batch files, or shell scripts.
Short-Circuit
The nature of the awk logical operators ‘ &&’ and ‘ ||’. If the value of the entire expression is determinable from evaluating justthe lefthand side of these operators, the righthand side is notevaluated. (See Boolean Ops.)
Side Effect
A side effect occurs when an expression has an effect aside from merelyproducing a value. Assignment expressions, increment and decrementexpressions, and function calls have side effects. (See Assignment Ops.)
Single Precision
An internal representation of numbers that can have fractional parts. Single precision numbers keep track of fewer digits than do double precisionnumbers, but operations on them are sometimes less expensive in terms of CPU time. This is the type used by some very old versions of awk to storenumeric values. It is the C type float.
Space
The character generated by hitting the space bar on the keyboard.
Special File
A file name interpreted internally by gawk, instead of being handeddirectly to the underlying operating system—for example, /dev/stderr. (See Special Files.)
Stream Editor
A program that reads records from an input stream and processes them oneor more at a time. This is in contrast with batch programs, which mayexpect to read their input files in entirety before starting to doanything, as well as with interactive programs which require input from theuser.
String
A datum consisting of a sequence of characters, such as ‘ I am astring’. Constant strings are written with double quotes in the awk language and may contain escape sequences. (See Escape Sequences.)
Tab
The character generated by hitting the TAB key on the keyboard. It usually expands to up to eight spaces upon output.
Text Domain
A unique name that identifies an application. Used for grouping messages that are translated at runtimeinto the local language.
Timestamp
A value in the “seconds since the epoch” format used by Unixand POSIX systems. Used for the gawk functions mktime(), strftime(), and systime(). See also “Epoch” and “UTC.”


Unix
A computer operating system originally developed in the early 1970's atAT&T Bell Laboratories. It initially became popular in universities aroundthe world and later moved into commercial environments as a softwaredevelopment system and network server system. There are many commercialversions of Unix, as well as several work-alike systems whose source codeis freely available (such as GNU/Linux, NetBSD, FreeBSD, and OpenBSD).
UTC
The accepted abbreviation for “Universal Coordinated Time.”This is standard time in Greenwich, England, which is used as areference time for day and date calculations. See also “Epoch” and “GMT.”
Whitespace
A sequence of space, TAB, or newline characters occurring inside an inputrecord or a string.


Next:  ,Previous:  Glossary,Up:  Top

GNU General Public License

Version 3, 29 June 2007
     Copyright © 2007 Free Software Foundation, Inc. http://fsf.org/
     
     Everyone is permitted to copy and distribute verbatim copies of this
     license document, but changing it is not allowed.

Preamble

The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.

The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedomto share and change all versions of a program—to make sure it remainsfree software for all its users. We, the Free Software Foundation,use the GNU General Public License for most of our software; itapplies also to any other work released this way by its authors. Youcan apply it to your programs, too.

When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, youhave certain responsibilities if you distribute copies of thesoftware, or if you modify it: responsibilities to respect the freedomof others.

For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too,receive or can get the source code. And you must show them theseterms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.

Some devices are designed to deny users access to install or runmodified versions of the software inside them, although themanufacturer can do so. This is fundamentally incompatible with theaim of protecting users' freedom to change the software. Thesystematic pattern of such abuse occurs in the area of products forindividuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit thepractice for those products. If such problems arise substantially inother domains, we stand ready to extend this provision to thosedomains in future versions of the GPL, as needed to protect thefreedom of users.

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wishto avoid the special danger that patents applied to a free programcould make it effectively proprietary. To prevent this, the GPLassures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution andmodification follow.

TERMS AND CONDITIONS

  1. Definitions.

    “This License” refers to version 3 of the GNU General Public License.

    “Copyright” also means copyright-like laws that apply to other kindsof works, such as semiconductor masks.

    “The Program” refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as “you”. “Licensees” and“recipients” may be individuals or organizations.

    To “modify” a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making ofan exact copy. The resulting work is called a “modified version” ofthe earlier work or a work “based on” the earlier work.

    A “covered work” means either the unmodified Program or a work basedon the Program.

    To “propagate” a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.

    To “convey” a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a userthrough a computer network, with no transfer of a copy, is notconveying.

    An interactive user interface displays “Appropriate Legal Notices” tothe extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.

  2. Source Code.

    The “source code” for a work means the preferred form of the work formaking modifications to it. “Object code” means any non-source formof a work.

    A “Standard Interface” means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.

    The “System Libraries” of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A“Major Component”, in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.

    The “Corresponding Source” for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.

    The Corresponding Source need not include anything that users canregenerate automatically from other parts of the Corresponding Source.

    The Corresponding Source for a work in source code form is that samework.

  3. Basic Permissions.

    All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.

    You may make, run and propagate covered works that you do not convey,without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of havingthem make modifications exclusively for you, or provide you withfacilities for running those works, provided that you comply with theterms of this License in conveying all material for which you do notcontrol copyright. Those thus making or running the covered works foryou must do so exclusively on your behalf, under your direction andcontrol, on terms that prohibit them from making any copies of yourcopyrighted material outside their relationship with you.

    Conveying under any other circumstances is permitted solely under theconditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.

  4. Protecting Users' Legal Rights From Anti-Circumvention Law.

    No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.

    When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent suchcircumvention is effected by exercising rights under this License withrespect to the covered work, and you disclaim any intention to limitoperation or modification of the work as a means of enforcing, againstthe work's users, your or third parties' legal rights to forbidcircumvention of technological measures.

  5. Conveying Verbatim Copies.

    You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.

    You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.

  6. Conveying Modified Source Versions.

    You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of theseconditions:

    1. The work must carry prominent notices stating that you modified it,and giving a relevant date.
    2. The work must carry prominent notices stating that it is releasedunder this License and any conditions added under section 7. Thisrequirement modifies the requirement in section 4 to “keep intact allnotices”.
    3. You must license the entire work, as a whole, under this License toanyone who comes into possession of a copy. This License willtherefore apply, along with any applicable section 7 additional terms,to the whole of the work, and all its parts, regardless of how theyare packaged. This License gives no permission to license the work inany other way, but it does not invalidate such permission if you haveseparately received it.
    4. If the work has interactive user interfaces, each must displayAppropriate Legal Notices; however, if the Program has interactiveinterfaces that do not display Appropriate Legal Notices, your workneed not make them do so.

    A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an“aggregate” if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.

  7. Conveying Non-Source Forms.

    You may convey a covered work in object code form under the terms ofsections 4 and 5, provided that you also convey the machine-readableCorresponding Source under the terms of this License, in one of theseways:

    1. Convey the object code in, or embodied in, a physical product(including a physical distribution medium), accompanied by theCorresponding Source fixed on a durable physical medium customarilyused for software interchange.
    2. Convey the object code in, or embodied in, a physical product(including a physical distribution medium), accompanied by a writtenoffer, valid for at least three years and valid for as long as youoffer spare parts or customer support for that product model, to giveanyone who possesses the object code either (1) a copy of theCorresponding Source for all the software in the product that iscovered by this License, on a durable physical medium customarily usedfor software interchange, for a price no more than your reasonablecost of physically performing this conveying of source, or (2) accessto copy the Corresponding Source from a network server at no charge.
    3. Convey individual copies of the object code with a copy of the writtenoffer to provide the Corresponding Source. This alternative isallowed only occasionally and noncommercially, and only if youreceived the object code with such an offer, in accord with subsection6b.
    4. Convey the object code by offering access from a designated place(gratis or for a charge), and offer equivalent access to theCorresponding Source in the same way through the same place at nofurther charge. You need not require recipients to copy theCorresponding Source along with the object code. If the place to copythe object code is a network server, the Corresponding Source may beon a different server (operated by you or a third party) that supportsequivalent copying facilities, provided you maintain clear directionsnext to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remainobligated to ensure that it is available for as long as needed tosatisfy these requirements.
    5. Convey the object code using peer-to-peer transmission, provided youinform other peers where the object code and Corresponding Source ofthe work are being offered to the general public at no charge undersubsection 6d.

    A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.

    A “User Product” is either (1) a “consumer product”, which means anytangible personal property which is normally used for personal,family, or household purposes, or (2) anything designed or sold forincorporation into a dwelling. In determining whether a product is aconsumer product, doubtful cases shall be resolved in favor ofcoverage. For a particular product received by a particular user,“normally used” refers to a typical or common use of that class ofproduct, regardless of the status of the particular user or of the wayin which the particular user actually uses, or expects or is expectedto use, the product. A product is a consumer product regardless ofwhether the product has substantial commercial, industrial ornon-consumer uses, unless such uses represent the only significantmode of use of the product.

    “Installation Information” for a User Product means any methods,procedures, authorization keys, or other information required toinstall and execute modified versions of a covered work in that UserProduct from a modified version of its Corresponding Source. Theinformation must suffice to ensure that the continued functioning ofthe modified object code is in no case prevented or interfered withsolely because modification has been made.

    If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).

    The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, orupdates for a work that has been modified or installed by therecipient, or for the User Product in which it has been modified orinstalled. Access to a network may be denied when the modificationitself materially and adversely affects the operation of the networkor violates the rules and protocols for communication across thenetwork.

    Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.

  8. Additional Terms.

    “Additional permissions” are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.

    When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.

    Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holdersof that material) supplement the terms of this License with terms:

    1. Disclaiming warranty or limiting liability differently from the termsof sections 15 and 16 of this License; or
    2. Requiring preservation of specified reasonable legal notices or authorattributions in that material or in the Appropriate Legal Noticesdisplayed by works containing it; or
    3. Prohibiting misrepresentation of the origin of that material, orrequiring that modified versions of such material be marked inreasonable ways as different from the original version; or
    4. Limiting the use for publicity purposes of names of licensors orauthors of the material; or
    5. Declining to grant rights under trademark law for use of some tradenames, trademarks, or service marks; or
    6. Requiring indemnification of licensors and authors of that material byanyone who conveys the material (or modified versions of it) withcontractual assumptions of liability to the recipient, for anyliability that these contractual assumptions directly impose on thoselicensors and authors.

    All other non-permissive additional terms are considered “furtherrestrictions” within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.

    If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.

    Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions; theabove requirements apply either way.

  9. Termination.

    You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).

    However, if you cease all violation of this License, then your licensefrom a particular copyright holder is reinstated (a) provisionally,unless and until the copyright holder explicitly and finallyterminates your license, and (b) permanently, if the copyright holderfails to notify you of the violation by some reasonable means prior to60 days after the cessation.

    Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.

    Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.

  10. Acceptance Not Required for Having Copies.

    You are not required to accept this License in order to receive or runa copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.

  11. Automatic Licensing of Downstream Recipients.

    Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.

    An “entity transaction” is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.

    You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.

  12. Patents.

    A “contributor” is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's “contributor version”.

    A contributor's “essential patent claims” are all patent claims ownedor controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, “control” includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.

    Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.

    In the following three paragraphs, a “patent license” is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To “grant” such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.

    If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. “Knowingly relying” means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.

    If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.

    A patent license is “discriminatory” if it does not include within thescope of its coverage, prohibits the exercise of, or is conditioned onthe non-exercise of one or more of the rights that are specificallygranted under this License. You may not convey a covered work if youare a party to an arrangement with a third party that is in thebusiness of distributing software, under which you make payment to thethird party based on the extent of your activity of conveying thework, and under which the third party grants, to any of the partieswho would receive the covered work from you, a discriminatory patentlicense (a) in connection with copies of the covered work conveyed byyou (or copies made from those copies), or (b) primarily for and inconnection with specific products or compilations that contain thecovered work, unless you entered into that arrangement, or that patentlicense was granted, prior to 28 March 2007.

    Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.

  13. No Surrender of Others' Freedom.

    If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot conveya covered work so as to satisfy simultaneously your obligations underthis License and any other pertinent obligations, then as aconsequence you may not convey it at all. For example, if you agreeto terms that obligate you to collect a royalty for further conveyingfrom those to whom you convey the Program, the only way you couldsatisfy both those terms and this License would be to refrain entirelyfrom conveying the Program.

  14. Use with the GNU Affero General Public License.

    Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.

  15. Revised Versions of this License.

    The Free Software Foundation may publish revised and/or new versionsof the GNU General Public License from time to time. Such newversions will be similar in spirit to the present version, but maydiffer in detail to address new problems or concerns.

    Each version is given a distinguishing version number. If the Programspecifies that a certain numbered version of the GNU General PublicLicense “or any later version” applies to it, you have the option offollowing the terms and conditions either of that numbered version orof any later version published by the Free Software Foundation. Ifthe Program does not specify a version number of the GNU GeneralPublic License, you may choose any version ever published by the FreeSoftware Foundation.

    If the Program specifies that a proxy can decide which future versionsof the GNU General Public License can be used, that proxy's publicstatement of acceptance of a version permanently authorizes you tochoose that version for the Program.

    Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.

  16. Disclaimer of Warranty.

    THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUTWARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOTLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FORA PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY ANDPERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVEDEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR ORCORRECTION.

  17. Limitation of Liability.

    IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/ORCONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGESARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUTNOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE ORLOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAMTO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHERPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

  18. Interpretation of Sections 15 and 16.

    If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under theseterms.

To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe “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) year 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 3 of the License, 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, see http://www.gnu.org/licenses/.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:

     program Copyright (C) year name of author
     This program 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 showthe appropriate parts of the General Public License. Of course, yourprogram's commands might be different; for a GUI interface, you woulduse an “about box”.

You should also get your employer (if you work as a programmer) or school,if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, seehttp://www.gnu.org/licenses/.

The GNU General Public License does not permit incorporating yourprogram into proprietary programs. If your program is a subroutinelibrary, you may consider it more useful to permit linking proprietaryapplications with the library. If this is what you want to do, usethe GNU Lesser General Public License instead of this License. Butfirst, please readhttp://www.gnu.org/philosophy/why-not-lgpl.html.


Next:  ,Previous:  Copying,Up:  Top

GNU Free Documentation License

Version 1.3, 3 November 2008
     Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.
     http://fsf.org/
     
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.
  1. PREAMBLE

    The purpose of this License is to make a manual, textbook, or otherfunctional and useful documentfree in the sense of freedom: toassure everyone the effective freedom to copy and redistribute it,with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a wayto get credit for their work, while not being considered responsiblefor modifications made by others.

    This License is a kind of “copyleft”, which means that derivativeworks of the document must themselves be free in the same sense. Itcomplements the GNU General Public License, which is a copyleftlicense designed for free software.

    We have designed this License in order to use it for manuals for freesoftware, because free software needs free documentation: a freeprogram should come with manuals providing the same freedoms that thesoftware does. But this License is not limited to software manuals;it can be used for any textual work, regardless of subject matter orwhether it is published as a printed book. We recommend this Licenseprincipally for works whose purpose is instruction or reference.

  2. APPLICABILITY AND DEFINITIONS

    This License applies to any manual or other work, in any medium, thatcontains a notice placed by the copyright holder saying it can bedistributed under the terms of this License. Such a notice grants aworld-wide, royalty-free license, unlimited in duration, to use thatwork under the conditions stated herein. The “Document”, below,refers to any such manual or work. Any member of the public is alicensee, and is addressed as “you”. You accept the license if youcopy, modify or distribute the work in a way requiring permissionunder copyright law.

    A “Modified Version” of the Document means any work containing theDocument or a portion of it, either copied verbatim, or withmodifications and/or translated into another language.

    A “Secondary Section” is a named appendix or a front-matter sectionof the Document that deals exclusively with the relationship of thepublishers or authors of the Document to the Document's overallsubject (or to related matters) and contains nothing that could falldirectly within that overall subject. (Thus, if the Document is inpart a textbook of mathematics, a Secondary Section may not explainany mathematics.) The relationship could be a matter of historicalconnection with the subject or with related matters, or of legal,commercial, philosophical, ethical or political position regardingthem.

    The “Invariant Sections” are certain Secondary Sections whose titlesare designated, as being those of Invariant Sections, in the noticethat says that the Document is released under this License. If asection does not fit the above definition of Secondary then it is notallowed to be designated as Invariant. The Document may contain zeroInvariant Sections. If the Document does not identify any InvariantSections then there are none.

    The “Cover Texts” are certain short passages of text that are listed,as Front-Cover Texts or Back-Cover Texts, in the notice that says thatthe Document is released under this License. A Front-Cover Text maybe at most 5 words, and a Back-Cover Text may be at most 25 words.

    A “Transparent” copy of the Document means a machine-readable copy,represented in a format whose specification is available to thegeneral public, that is suitable for revising the documentstraightforwardly with generic text editors or (for images composed ofpixels) generic paint programs or (for drawings) some widely availabledrawing editor, and that is suitable for input to text formatters orfor automatic translation to a variety of formats suitable for inputto text formatters. A copy made in an otherwise Transparent fileformat whose markup, or absence of markup, has been arranged to thwartor discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amountof text. A copy that is not “Transparent” is called “Opaque”.

    Examples of suitable formats for Transparent copies include plainascii without markup, Texinfo input format, LaTeX inputformat,SGML or XML using a publicly availableDTD, and standard-conforming simpleHTML,PostScript or PDF designed for human modification. Examplesof transparent image formats includePNG, XCF andJPG. Opaque formats include proprietary formats that can beread and edited only by proprietary word processors,SGML orXML for which the DTD and/or processing tools arenot generally available, and the machine-generatedHTML,PostScript or PDF produced by some word processors foroutput purposes only.

    The “Title Page” means, for a printed book, the title page itself,plus such following pages as are needed to hold, legibly, the materialthis License requires to appear in the title page. For works informats which do not have any title page as such, “Title Page” meansthe text near the most prominent appearance of the work's title,preceding the beginning of the body of the text.

    The “publisher” means any person or entity that distributes copiesof the Document to the public.

    A section “Entitled XYZ” means a named subunit of the Document whosetitle either is precisely XYZ or contains XYZ in parentheses followingtext that translates XYZ in another language. (Here XYZ stands for aspecific section name mentioned below, such as “Acknowledgements”,“Dedications”, “Endorsements”, or “History”.) To “Preserve the Title”of such a section when you modify the Document means that it remains asection “Entitled XYZ” according to this definition.

    The Document may include Warranty Disclaimers next to the notice whichstates that this License applies to the Document. These WarrantyDisclaimers are considered to be included by reference in thisLicense, but only as regards disclaiming warranties: any otherimplication that these Warranty Disclaimers may have is void and hasno effect on the meaning of this License.

  3. VERBATIM COPYING

    You may copy and distribute the Document in any medium, eithercommercially or noncommercially, provided that this License, thecopyright notices, and the license notice saying this License appliesto the Document are reproduced in all copies, and that you add no otherconditions whatsoever to those of this License. You may not usetechnical measures to obstruct or control the reading or furthercopying of the copies you make or distribute. However, you may acceptcompensation in exchange for copies. If you distribute a large enoughnumber of copies you must also follow the conditions in section 3.

    You may also lend copies, under the same conditions stated above, andyou may publicly display copies.

  4. COPYING IN QUANTITY

    If you publish printed copies (or copies in media that commonly haveprinted covers) of the Document, numbering more than 100, and theDocument's license notice requires Cover Texts, you must enclose thecopies in covers that carry, clearly and legibly, all these CoverTexts: Front-Cover Texts on the front cover, and Back-Cover Texts onthe back cover. Both covers must also clearly and legibly identifyyou as the publisher of these copies. The front cover must presentthe full title with all words of the title equally prominent andvisible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preservethe title of the Document and satisfy these conditions, can be treatedas verbatim copying in other respects.

    If the required texts for either cover are too voluminous to fitlegibly, you should put the first ones listed (as many as fitreasonably) on the actual cover, and continue the rest onto adjacentpages.

    If you publish or distribute Opaque copies of the Document numberingmore than 100, you must either include a machine-readable Transparentcopy along with each Opaque copy, or state in or with each Opaque copya computer-network location from which the general network-usingpublic has access to download using public-standard network protocolsa complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps,when you begin distribution of Opaque copies in quantity, to ensurethat this Transparent copy will remain thus accessible at the statedlocation until at least one year after the last time you distribute anOpaque copy (directly or through your agents or retailers) of thatedition to the public.

    It is requested, but not required, that you contact the authors of theDocument well before redistributing any large number of copies, to givethem a chance to provide you with an updated version of the Document.

  5. MODIFICATIONS

    You may copy and distribute a Modified Version of the Document underthe conditions of sections 2 and 3 above, provided that you releasethe Modified Version under precisely this License, with the ModifiedVersion filling the role of the Document, thus licensing distributionand modification of the Modified Version to whoever possesses a copyof it. In addition, you must do these things in the Modified Version:

    1. Use in the Title Page (and on the covers, if any) a title distinctfrom that of the Document, and from those of previous versions(which should, if there were any, be listed in the History sectionof the Document). You may use the same title as a previous versionif the original publisher of that version gives permission.
    2. List on the Title Page, as authors, one or more persons or entitiesresponsible for authorship of the modifications in the ModifiedVersion, together with at least five of the principal authors of theDocument (all of its principal authors, if it has fewer than five),unless they release you from this requirement.
    3. State on the Title page the name of the publisher of theModified Version, as the publisher.
    4. Preserve all the copyright notices of the Document.
    5. Add an appropriate copyright notice for your modificationsadjacent to the other copyright notices.
    6. Include, immediately after the copyright notices, a license noticegiving the public permission to use the Modified Version under theterms of this License, in the form shown in the Addendum below.
    7. Preserve in that license notice the full lists of Invariant Sectionsand required Cover Texts given in the Document's license notice.
    8. Include an unaltered copy of this License.
    9. Preserve the section Entitled “History”, Preserve its Title, and addto it an item stating at least the title, year, new authors, andpublisher of the Modified Version as given on the Title Page. Ifthere is no section Entitled “History” in the Document, create onestating the title, year, authors, and publisher of the Document asgiven on its Title Page, then add an item describing the ModifiedVersion as stated in the previous sentence.
    10. Preserve the network location, if any, given in the Document forpublic access to a Transparent copy of the Document, and likewisethe network locations given in the Document for previous versionsit was based on. These may be placed in the “History” section. You may omit a network location for a work that was published atleast four years before the Document itself, or if the originalpublisher of the version it refers to gives permission.
    11. For any section Entitled “Acknowledgements” or “Dedications”, Preservethe Title of the section, and preserve in the section all thesubstance and tone of each of the contributor acknowledgements and/ordedications given therein.
    12. Preserve all the Invariant Sections of the Document,unaltered in their text and in their titles. Section numbersor the equivalent are not considered part of the section titles.
    13. Delete any section Entitled “Endorsements”. Such a sectionmay not be included in the Modified Version.
    14. Do not retitle any existing section to be Entitled “Endorsements” orto conflict in title with any Invariant Section.
    15. Preserve any Warranty Disclaimers.

    If the Modified Version includes new front-matter sections orappendices that qualify as Secondary Sections and contain no materialcopied from the Document, you may at your option designate some or allof these sections as invariant. To do this, add their titles to thelist of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

    You may add a section Entitled “Endorsements”, provided it containsnothing but endorsements of your Modified Version by variousparties—for example, statements of peer review or that the text hasbeen approved by an organization as the authoritative definition of astandard.

    You may add a passage of up to five words as a Front-Cover Text, and apassage of up to 25 words as a Back-Cover Text, to the end of the listof Cover Texts in the Modified Version. Only one passage ofFront-Cover Text and one of Back-Cover Text may be added by (orthrough arrangements made by) any one entity. If the Document alreadyincludes a cover text for the same cover, previously added by you orby arrangement made by the same entity you are acting on behalf of,you may not add another; but you may replace the old one, on explicitpermission from the previous publisher that added the old one.

    The author(s) and publisher(s) of the Document do not by this Licensegive permission to use their names for publicity for or to assert orimply endorsement of any Modified Version.

  6. COMBINING DOCUMENTS

    You may combine the Document with other documents released under thisLicense, under the terms defined in section 4 above for modifiedversions, provided that you include in the combination all of theInvariant Sections of all of the original documents, unmodified, andlist them all as Invariant Sections of your combined work in itslicense notice, and that you preserve all their Warranty Disclaimers.

    The combined work need only contain one copy of this License, andmultiple identical Invariant Sections may be replaced with a singlecopy. If there are multiple Invariant Sections with the same name butdifferent contents, make the title of each such section unique byadding at the end of it, in parentheses, the name of the originalauthor or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list ofInvariant Sections in the license notice of the combined work.

    In the combination, you must combine any sections Entitled “History”in the various original documents, forming one section Entitled“History”; likewise combine any sections Entitled “Acknowledgements”,and any sections Entitled “Dedications”. You must delete allsections Entitled “Endorsements.”

  7. COLLECTIONS OF DOCUMENTS

    You may make a collection consisting of the Document and other documentsreleased under this License, and replace the individual copies of thisLicense in the various documents with a single copy that is included inthe collection, provided that you follow the rules of this License forverbatim copying of each of the documents in all other respects.

    You may extract a single document from such a collection, and distributeit individually under this License, provided you insert a copy of thisLicense into the extracted document, and follow this License in allother respects regarding verbatim copying of that document.

  8. AGGREGATION WITH INDEPENDENT WORKS

    A compilation of the Document or its derivatives with other separateand independent documents or works, in or on a volume of a storage ordistribution medium, is called an “aggregate” if the copyrightresulting from the compilation is not used to limit the legal rightsof the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does notapply to the other works in the aggregate which are not themselvesderivative works of the Document.

    If the Cover Text requirement of section 3 is applicable to thesecopies of the Document, then if the Document is less than one half ofthe entire aggregate, the Document's Cover Texts may be placed oncovers that bracket the Document within the aggregate, or theelectronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the wholeaggregate.

  9. TRANSLATION

    Translation is considered a kind of modification, so you maydistribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires specialpermission from their copyright holders, but you may includetranslations of some or all Invariant Sections in addition to theoriginal versions of these Invariant Sections. You may include atranslation of this License, and all the license notices in theDocument, and any Warranty Disclaimers, provided that you also includethe original English version of this License and the original versionsof those notices and disclaimers. In case of a disagreement betweenthe translation and the original version of this License or a noticeor disclaimer, the original version will prevail.

    If a section in the Document is Entitled “Acknowledgements”,“Dedications”, or “History”, the requirement (section 4) to Preserveits Title (section 1) will typically require changing the actualtitle.

  10. TERMINATION

    You may not copy, modify, sublicense, or distribute the Documentexcept as expressly provided under this License. Any attemptotherwise to copy, modify, sublicense, or distribute it is void, andwill automatically terminate your rights under this License.

    However, if you cease all violation of this License, then your licensefrom a particular copyright holder is reinstated (a) provisionally,unless and until the copyright holder explicitly and finallyterminates your license, and (b) permanently, if the copyright holderfails to notify you of the violation by some reasonable means prior to60 days after the cessation.

    Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.

    Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, receipt of a copy of some or all of the same material doesnot give you any rights to use it.

  11. FUTURE REVISIONS OF THIS LICENSE

    The Free Software Foundation may publish new, revised versionsof the GNU Free Documentation License from time to time. Such newversions will be similar in spirit to the present version, but maydiffer in detail to address new problems or concerns. Seehttp://www.gnu.org/copyleft/.

    Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of thisLicense “or any later version” applies to it, you have the option offollowing the terms and conditions either of that specified version orof any later version that has been published (not as a draft) by theFree Software Foundation. If the Document does not specify a versionnumber of this License, you may choose any version ever published (notas a draft) by the Free Software Foundation. If the Documentspecifies that a proxy can decide which future versions of thisLicense can be used, that proxy's public statement of acceptance of aversion permanently authorizes you to choose that version for theDocument.

  12. RELICENSING

    “Massive Multiauthor Collaboration Site” (or “MMC Site”) means anyWorld Wide Web server that publishes copyrightable works and alsoprovides prominent facilities for anybody to edit those works. Apublic wiki that anybody can edit is an example of such a server. A“Massive Multiauthor Collaboration” (or “MMC”) contained in thesite means any set of copyrightable works thus published on the MMCsite.

    “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0license published by Creative Commons Corporation, a not-for-profitcorporation with a principal place of business in San Francisco,California, as well as future copyleft versions of that licensepublished by that same organization.

    “Incorporate” means to publish or republish a Document, in whole orin part, as part of another Document.

    An MMC is “eligible for relicensing” if it is licensed under thisLicense, and if all works that were first published under this Licensesomewhere other than this MMC, and subsequently incorporated in wholeor in part into the MMC, (1) had no cover texts or invariant sections,and (2) were thus incorporated prior to November 1, 2008.

    The operator of an MMC Site may republish an MMC contained in the siteunder CC-BY-SA on the same site at any time before August 1, 2009,provided the MMC is eligible for relicensing.

ADDENDUM: How to use this License for your documents

To use this License in a document you have written, include a copy ofthe License in the document and put the following copyright andlicense notices just after the title page:

       Copyright (C)  year  your name.
       Permission is granted to copy, distribute and/or modify this document
       under the terms of the GNU Free Documentation License, Version 1.3
       or any later version published by the Free Software Foundation;
       with no Invariant Sections, no Front-Cover Texts, and no Back-Cover
       Texts.  A copy of the license is included in the section entitled ``GNU
       Free Documentation License''.

If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,replace the “with...Texts.” line with this:

         with the Invariant Sections being list their titles, with
         the Front-Cover Texts being list, and with the Back-Cover Texts
         being list.

If you have Invariant Sections without Cover Texts, or some othercombination of the three, merge those two alternatives to suit thesituation.

If your document contains nontrivial examples of program code, werecommend releasing these examples in parallel under your choice offree software license, such as the GNU General Public License,to permit their use in free software.

Index


Footnotes

[1] The 2008 POSIX standard can be found online athttp://www.opengroup.org/onlinepubs/9699919799/.

[2] These commandsare available on POSIX-compliant systems, as well as on traditionalUnix-based systems. If you are using some other operating system, you still need tobe familiar with the ideas of I/O redirection and pipes.

[3] Often, these systemsusegawk for their awk implementation!

[4] All such differencesappear in the index under theentry “differences inawk and gawk.”

[5] GNU stands for “GNU's not Unix.”

[6] The terminology “GNU/Linux” is explainedin theGlossary.

[7] If you use Bash as your shell, you should executethe command ‘set +H’ before running this program interactively,to disable the C shell-style command history, which treats‘!’ as a special character. We recommend putting this command intoyour personal startup file.

[8] Although we generally recommend the use of singlequotes around the program text, double quotes are needed here in order toput the single quote into the message.

[9] The ‘#!’ mechanism works onGNU/Linux systems, BSD-based systems and commercial Unix systems.

[10] Theline beginning with ‘#!’ lists the full file name of an interpreterto run and an optional initial command-line argument to pass to thatinterpreter. The operating system then runs the interpreter with the givenargument and the full argument list of the executed program. The first argumentin the list is the full file name of theawk program. The rest of theargument list contains either options toawk, or data files,or both.

[11] The ‘LC_ALL=C’ isneeded to produce this traditional-style output fromls.

[12] The ‘?’ and ‘:’ referred to here is thethree-operand conditional expression described inConditional Exp. Splitting lines after ‘?’ and ‘:’ is a minorgawkextension; if --posix is specified(seeOptions), then this extension is disabled.

[13] Not recommended.

[14] Your version ofgawkmay use a different directory; itwill depend upon howgawk was built and installed. The actualdirectory is the value of ‘$(datadir)’ generated whengawk was configured. You probably don't need to worry about this,though.

[15] In other literature,you may see a bracket expression referred to as either acharacter set, acharacter class, or a character list.

[16] Use two backslashes if you'reusing a string constant with a regexp operator or function.

[17] Experienced C and C++ programmers will notethat it is possible, using something like‘IGNORECASE = 1 && /foObAr/ { ... }’and‘IGNORECASE = 0 || /foobar/ { ... }’. However, this is somewhat obscure and we don't recommend it.

[18] If you don't understand this,don't worry about it; it just means thatgawk doesthe right thing.

[19] At least that we knowabout.

[20] In POSIXawk, newlines are notconsidered whitespace for separating fields.

[21] The sed utility is a “stream editor.”Its behavior is also defined by the POSIX standard.

[22] At least, we don't know of one.

[23] When FS is the null string ("")or a regexp, this special feature ofRS does not apply. It does apply to the default field separator of a single space:‘FS = " "’.

[24] This is not quite true.RT couldbe changed if RS is a regular expression.

[25] The “tty” in/dev/tty stands for“Teletype,” a serial terminal.

[26] The technical terminology is rather morbid. The finished child is called a “zombie,” and cleaning up afterit is referred to as “reaping.”

[27] This is a full 16-bit value as returned by thewait()system call. See the system manual pages for information onhow to decode this value.

[28] The internal representation of all numbers,including integers, uses double precisionfloating-point numbers. On most modern systems, these are in IEEE 754 standard format.

[29] Pathological cases can require up to752 digits (!), but we doubt that you need to worry about this.

[30] It happens that Brian Kernighan'sawk,gawk and mawk all “get it right,”but you should not rely on this.

[31] gawk hasfollowed these rules for many years,and it is gratifying that the POSIX standard is also now correct.

[32] Technically, string comparison is supposedto behave the same way as if the strings are compared with the Cstrcoll() function.

[33] Thisprogram has a bug; it prints lines starting with ‘END’. Howwould you fix it?

[34] The original version ofawk keptreading and ignoring input until the end of the file was seen.

[35] InPOSIXawk, newline does not count as whitespace.

[36] Some early implementations of Unixawk initializedFILENAME to"-", even if there were data files to beprocessed. This behavior was incorrect and should not be reliedupon in your programs.

[37] Thanks to Michael Brennan for pointing this out.

[38] The C version ofrand()on many Unix systemsis known to produce fairly poor sequences of random numbers. However, nothing requires that anawk implementation use the Crand() to implement theawk version of rand(). In fact,gawk uses the BSD random() function, which isconsiderably better thanrand(), to produce random numbers.

[39] mawkuses a different seed each time.

[40] Computer-generated random numbers really are not trulyrandom. They are technically known as “pseudorandom.” This meansthat while the numbers in a sequence appear to be random, you can infact generate the same sequence of random numbers over and over again.

[41] Unlessyou use the--non-decimal-data option, which isn't recommended. SeeNondecimal Data, for more information.

[42] Note that this meansthat the record will first be regenerated using the value ofOFS ifany fields have been changed, and that the fields will be updatedafter the substitution, even if the operation is a “no-op” suchas ‘sub(/^/, "")’.

[43] This is different fromC and C++, in which the first character is number zero.

[44] A program is interactiveif the standard output is connected to a terminal device. On modernsystems, this means your keyboard and screen.

[45] See Glossary,especially the entries “Epoch” and “UTC.”

[46] The GNUdate utility canalso do many of the things described here. Its use may be preferablefor simple time-related operations in shell scripts.

[47] Occasionally there areminutes in a year with a leap second, which is why theseconds can go up to 60.

[48] Unfortunately,not every system'sstrftime() necessarilysupports all of the conversions listed here.

[49] If you don't understand any of this, don't worry aboutit; these facilities are meant to make it easier to “internationalize”programs. Other internationalization features are described inInternationalization.

[50] This is because ISO C leaves thebehavior of the C version ofstrftime() undefined and gawkuses the system's version ofstrftime() if it's there. Typically, the conversion specifier either does not appear in thereturned string or appears literally.

[51] This exampleshows that 0's come in on the left side. Forgawk, this isalways true, but in some languages, it's possible to have the left sidefill with 1's. Caveat emptor.

[52] This program won't actually run,sincefoo() is undefined.

[53] For some operating systems, thegawkport doesn't support GNU gettext. Therefore, these features are not availableif you are using one of those operating systems. Sorry.

[54] Americansuse a comma every three decimal places and a period for the decimalpoint, while many Europeans do exactly the opposite:1,234.56 versus 1.234,56.

[55] Thexgettext utility that comes with GNUgettext can handle.awk files.

[56] This example is borrowedfrom the GNUgettext manual.

[57] This is good fodder for an “Obfuscatedawk” contest.

[58] Perhaps it would be better if it werecalled “Hippy.” Ah, well.

[59] When two elementscompare as equal, the Cqsort() function does not guaranteethat they will maintain their original relative order after sorting. Using the string value to provide a unique ordering when the numericvalues are equal ensures thatgawk behaves consistentlyacross different environments.

[60] Youmay also use one of the predefined sorting names that sorts indecreasing order.

[61] Thisis true because locale-based comparison occurs only when in POSIXcompatibility mode, and sinceasort() and asorti() aregawk extensions, they are not available in that case.

[62] This is verydifferent from the same operator in the C shell.

[63] The effects arenot identical. Output of the transformedrecord will be in all lowercase, whileIGNORECASE preserves the originalcontents of the input record.

[64] While all the library routines could havebeen rewritten to use this convention, this was not done, in order toshow how our ownawk programming style has evolved and toprovide some basis for this discussion.

[65] gawk's --dump-variables command-lineoption is useful for verifying this.

[66] Thisis changing; many systems use Unicode, a very large character setthat includes ASCII as a subset. On systems with full Unicode support,a character can occupy up to 32 bits, making simple tests such asused here prohibitively expensive.

[67] ASCIIhas been extended in many countries to use the values from 128 to 255for country-specific characters. If your system uses these extensions,you can simplify_ord_init to loop from 0 to 255.

[68] It wouldbe nice ifawk had an assignment operator for concatenation. The lack of an explicit operator for concatenation makes string operationsmore difficult than they really need to be.

[69] Thisfunction was written beforegawk acquired the ability tosplit strings into single characters using"" as the separator. We have left it alone, since using substr() is more portable.

[70] It is often the case that passwordinformation is stored in a network database.

[71] Italso introduces a subtle bug;if a match happens, we output the translated line, not the original.

[72] This is the traditional usage. ThePOSIX usage is different, but not relevant for what the programaims to demonstrate.

[73] wc can't just use the value ofFNR inendfile(). If you examinethe code inFiletrans Function,you will see thatFNR has already been reset by the timeendfile() is called.

[74] Since gawkunderstands multibyte locales, this code counts characters, not bytes.

[75] On some oldersystems,tr may require that the lists be written asrange expressions enclosed in square brackets (‘[a-z]’) and quoted,to prevent the shell from attempting a file name expansion. This isnot a feature.

[76] Thisprogram was written beforegawk acquired the ability tosplit each character in a string into separate array elements.

[77] “Real world” is defined as“a program actually used to get something done.”

[78] This program was written beforegawk had thegensub() function. Consider how you might use it to simplify the code.

[79] Fully explaining thesh language is beyondthe scope of this book. We provide some minimal explanations, but seea good shell programming book if you wish to understand things in moredepth.

[80] On some very old versions ofawk, the test‘getline junk < t’ can loop forever if the file exists but is empty. Caveat emptor.

[81] Seethe standardandits rationale.

[82] The IA64architecture is also known as “Itanium.”

[83] This version is editedslightly for presentation. Seeextension/filefuncs.c in thegawk distributionfor the complete version.

[84] Compiled programs are typically writtenin lower-level languages such as C, C++, or Ada,and then translated, orcompiled, into a form thatthe computer can execute directly.

[85] Pathological cases can require up to752 digits (!), but we doubt that you need to worry about this.

[86] You asked for it, you got it.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值