21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

246 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>END @{ print "Always avoid bored archeologists!" @}@c end file@end example...‘extract.awk’ begins by setting IGNORECASE to one, so that mixed upper- and lowercaseletters in the directives won’t matter.The first rule handles calling system, checking that a command is given (NF is at leastthree) and also checking that the command exits with a zero exit status, signifying OK:# extract.awk --- extract files and run programs# from texinfo filesBEGIN { IGNORECASE = 1 }/^@c(omment)?[ \t]+system/ \{if (NF < 3) {e = (FILENAME ":" FNR)}e = (eprint e > "/dev/stderr"next": badly formed ‘system’ line")}$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 function fits nicely on the page.The second rule handles moving data into files. It verifies that a file name is given in thedirective. If the file named is not the current file, then the current file is closed. Keepingthe current file open until a new file is encountered allows the use of the ‘>’ redirection forprinting the contents, keeping open file management simple.The ‘for’ loop does the work. It reads lines using getline (see Section 3.8 [ExplicitInput with getline], page 52). For an unexpected end of file, it calls the unexpected_eoffunction. If the line is an “endfile” line, then it breaks out of the loop. If the line is an‘@group’ or ‘@end group’ line, then it ignores 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 programcan print it directly. Otherwise, each leading ‘@’ must be stripped off. To remove the ‘@’symbols, the line is split into separate elements of the array a, using the split function(see Section 8.1.3 [String-Manipulation Functions], page 132). The ‘@’ symbol is used as theseparator character. Each element of a that is empty indicates two successive ‘@’ symbols

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

Saved successfully!

Ooh no, something went wrong!