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 3: Reading Input Files 55to be used as input. This form of getline reads one record at a time from the pipe. Forexample, the following program copies its input to its output, except for lines that beginwith ‘@execute’, which are replaced by the output produced by running the rest of the lineas a shell command:{}if ($1 == "@execute") {tmp = substr($0, 10)while ((tmp | getline) > 0)printclose(tmp)} elseprintThe close function is called to ensure that if two identical ‘@execute’ lines appear in theinput, the command is run for each one. Given the input:foobarbaz@execute whobletchthe program might produce:foobarbazarnold ttyv0 Jul 13 14:22miriam ttyp0 Jul 13 14:23 (murphy:0)bill ttyp1 Jul 13 14:23 (murphy:0)bletchNotice that this program ran the command who and printed the previous result. (If you trythis program yourself, you will of course get different results, depending upon who is loggedin on your system.)This variation of getline splits the record into fields, sets the value of NF, and recomputesthe value of $0. The values of NR and FNR are not changed.According to POSIX, ‘expression | getline’ is ambiguous if expression contains unparenthesizedoperators other than ‘$’—for example, ‘"echo " "date" | getline’ is ambiguousbecause the concatenation operator is not parenthesized. You should write it as‘("echo " "date") | getline’ if you want your program to be portable to other awk implementations.NOTE: Unfortunately, gawk has not been consistent in its treatment of a constructlike ‘"echo " "date" | getline’. Up to and including version 3.1.1 ofgawk, it was treated as ‘("echo " "date") | getline’. (This how Unix awkbehaves.) From 3.1.2 through 3.1.5, it was treated as ‘"echo " ("date" |getline)’. (This is how mawk behaves.) Starting with version 3.1.6, the earlierbehavior was reinstated. In short, always use explicit parentheses, and thenyou won’t have to worry.

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

Saved successfully!

Ooh no, something went wrong!