21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 13: Practical awk Programs 21513 Practical awk ProgramsChapter 12 [A Library of awk Functions], page 186, presents the idea that reading programsin a language contributes to learning that language. This chapter continues that theme, presentinga potpourri of awk programs for your reading enjoyment. There are three sections.The first describes how to run the programs presented in this chapter.The second presents awk versions of several common POSIX utilities. These are programsthat you are hopefully already familiar with, and therefore, whose problems are understood.By reimplementing these programs in awk, you can focus on the awk-related aspects ofsolving the programming problem.The third is a grab bag of interesting programs. These solve a number of differentdata-manipulation and management problems. Many of the programs are short, whichemphasizes awk’s ability to do a lot in just a few lines of code.Many of these programs use the library functions presented in Chapter 12 [A Library ofawk Functions], page 186.13.1 Running the Example ProgramsTo run a given program, you would typically do something like this:awk -f program -- options filesHere, program is the name of the awk program (such as ‘cut.awk’), options are anycommand-line options for the program that start with a ‘-’, and files are the actual datafiles.If your system supports the ‘#!’ executable interpreter mechanism (see Section 1.1.4[Executable awk Programs], page 13), you can instead run your program directly:cut.awk -c1-8 myfiles > resultsIf your awk is not gawk, you may instead need to use this:cut.awk -- -c1-8 myfiles > results13.2 Reinventing Wheels for Fun and ProfitThis section presents a number of POSIX utilities that are implemented in awk. Reinventingthese programs in awk is often enjoyable, because the algorithms can be very clearlyexpressed, and the code is usually very concise and simple. This is true because awk doesso much for you.It should be noted that these programs are not necessarily intended to replace the installedversions on your system. Instead, their purpose is to illustrate awk language programmingfor “real world” tasks.The programs are presented in alphabetical order.13.2.1 Cutting out Fields and ColumnsThe cut utility selects, or “cuts,” characters or fields from its standard input and sendsthem to its standard output. Fields are separated by TABs by default, but you may supplya command-line option to change the field delimiter (i.e., the field-separator character).cut’s definition of fields is less general than awk’s.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!