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.

52 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>3.8 Explicit Input with getlineSo far we have been getting our input data from awk’s main input stream—either thestandard input (usually your terminal, sometimes the output from another program) orfrom the files specified on the command line. The awk language has a special built-incommand called getline that can be used to read input under your explicit control.The getline command is used in several different ways and should not be used bybeginners. The examples that follow the explanation of the getline command includematerial that has not been covered yet. Therefore, come back and study the getlinecommand after you have reviewed the rest of this book and have a good knowledge of howawk works.The getline command returns one if it finds a record and zero if it encounters the endof the file. If there is some error in getting a record, such as a file that cannot be opened,then getline returns −1. In this case, gawk sets the variable ERRNO to a string describingthe error that occurred.In the following examples, command stands for a string value that represents a shellcommand.3.8.1 Using getline with No ArgumentsThe getline command can be used without arguments to read input from the currentinput file. All it does in this case is read the next input record and split it up into fields.This is useful if you’ve finished processing the current record, but want to do some specialprocessing on the next record right now. For example:{}if ((t = index($0, "/*")) != 0) {# value of ‘tmp’ will be "" if t is 1tmp = substr($0, 1, t - 1)u = index(substr($0, t + 2), "*/")offset = t + 2while (u == 0) {if (getline "/dev/stderr"exit}u = index($0, "*/")offset = 0}# substr expression will be "" if */# occurred at end of line$0 = tmp substr($0, offset + u + 2)}print $0

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

Saved successfully!

Ooh no, something went wrong!