The getline Function

The getline function is used to read another line of input. Not only can getline read from the regular input data stream, it can also handle input from files and pipes.

The getline function is similar to awk’s next statement. While both cause the next input line to be read, the next statement passes control back to the top of the script. The getline function gets the next line without changing control in the script. Possible return values are:

1

If it was able to read a line.

0

If it encounters the end-of-file.

-1

If it encounters an error.

Note

Although getline is called a function and it does return a value, its syntax resembles a statement. Do not write getline( ); its syntax does not permit parentheses.

In the previous chapter, we used a manual page source file as an example. The -man macros typically place the text argument on the next line. Although the macro is the pattern that you use to find the line, it is actually the next line that you process. For instance, to extract the name of the command from the manpage, the following example matches the heading “Name,” reads the next line, and prints the first field of it:

# getline.awk -- test getline function
/^\.SH "?Name"?/ { 
	getline # get next line
	print $1 # print $1 of new line.
}

The pattern matches any line with “.SH” followed by “Name,” which might be enclosed in quotes. Once this line is matched, we use getline to read the next input line. When the new line is read, getline assigns it $0 and parses it ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.