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.

56 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>3.8.6 Using getline into a Variable from a PipeWhen you use ‘command | getline var’, the output of command is sent through a pipe togetline and into the variable var. For example, the following program reads the currentdate and time into the variable current_time, using the date utility, and then prints it:BEGIN {"date" | getline current_timeclose("date")print "Report printed on " current_time}In this version of getline, none of the built-in variables are changed and the record isnot split into fields.3.8.7 Using getline from a CoprocessInput into getline from a pipe is a one-way operation. The command that is started with‘command | getline’ only sends data to your awk program.On occasion, you might want to send data to another program for processing and thenread the results back. gawk allows you to start a coprocess, with which two-way communicationsare possible. This is done with the ‘|&’ operator. Typically, you write data to thecoprocess first and then read results back, as shown in the following:print "some query" |& "db_server""db_server" |& getlinewhich sends a query to db_server and then reads the results.The values of NR and FNR are not changed, because the main input stream is not used.However, the record is split into fields in the 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 because this is thesection on getline. See Section 10.2 [Two-Way Communications with Another Process],page 170, where coprocesses are discussed in more detail.3.8.8 Using getline into a Variable from a CoprocessWhen you use ‘command |& getline var’, the output from the coprocess command is sentthrough a two-way pipe to getline and into the variable var.In this version of getline, none of the built-in variables are changed and the record isnot split into fields. The only variable changed is var.3.8.9 Points to Remember About getlineHere are some miscellaneous points about getline that you should bear in mind:• When getline changes the value of $0 and NF, awk does not automatically jump to thestart of the program 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 an awk program mayhave open to just one. In gawk, there is no such limit. You can open as many pipelines(and coprocesses) as the underlying operating system permits.

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

Saved successfully!

Ooh no, something went wrong!