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 12: A Library of awk Functions 199ARGV[i] = ARGV[i-1]# make sure gawk knows to keep goingARGC++# make current file next to get doneARGV[ARGIND+1] = FILENAME# do itnextfile}This code relies on the ARGIND variable (see Section 6.5.2 [Built-in Variables That ConveyInformation], page 113), which is specific to gawk. If you are not using gawk, you can useideas presented in the previous section to either update ARGIND on your own or modify thiscode as appropriate.The rewind function also relies on the nextfile keyword (see Section 6.4.9 [Using gawk’snextfile Statement], page 109). See Section 12.2.1 [Implementing nextfile as a Function],page 188, for a function version of nextfile.12.3.3 Checking for Readable Data FilesNormally, if you give awk a data file that isn’t readable, it stops with a fatal error. Thereare times when you might want to just ignore such files and keep going. You can do thisby prepending the following program to your awk program:# readable.awk --- library file to skip over unreadable filesBEGIN {for (i = 1; i < ARGC; i++) {if (ARGV[i] ~ /^[A-Za-z_][A-Za-z0-9_]*=.*/ \|| ARGV[i] == "-")continue # assignment or standard inputelse if ((getline junk < ARGV[i]) < 0) # unreadabledelete ARGV[i]elseclose(ARGV[i])}}This works, because the getline won’t be fatal. Removing the element from ARGV withdelete skips the file (since it’s no longer in the list).12.3.4 Checking For Zero-length FilesAll known awk implementations silently skip over zero-length files. This is a by-productof awk’s implicit read-a-record-and-match-against-the-rules loop: when awk tries to read arecord from an empty file, it immediately receives an end of file indication, closes the file,and proceeds on to the next command-line data file, without executing any user-level awkprogram code.Using gawk’s ARGIND variable (see Section 6.5 [Built-in Variables], page 110), it is possibleto detect when an empty data file has been skipped. Similar to the library file presented

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

Saved successfully!

Ooh no, something went wrong!