Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Close D.B.The AWK manual.1995.pdf
Источник:
Скачиваний:
7
Добавлен:
23.08.2013
Размер:
679.83 Кб
Скачать

Chapter 3: Reading Input Files

33

print

}'

The close function is called to ensure that if two identical `@execute' lines appear in the input, the command is run for each one. See Section 3.8 [Closing Input Files and Pipes], page 33.

Given the input:

foo bar baz

@execute who bletch

the program might produce:

foo bar baz

hack

ttyv0

Jul 13 14:22

 

hack

ttyp0

Jul 13

14:23

(gnu:0)

hack

ttyp1

Jul 13

14:23

(gnu:0)

hack

ttyp2

Jul 13

14:23

(gnu:0)

hack

ttyp3

Jul 13

14:23

(gnu:0)

bletch

 

 

 

 

Notice that this program ran the command who and printed the result. (If you try this program yourself, you will get di erent results, showing you who is logged in on your system.)

This variation of getline splits the record into elds, sets the value of NF and recomputes the value of $0. The values of NR and FNR are not changed.

command | getline var

The output of the command command is sent through a pipe to getline and into the variable var. For example, the following program reads the current date and time into the variable current_time, using the date utility, and then prints it.

awk 'BEGIN {

"date" | getline current_time close("date")

print "Report printed on " current_time

}'

In this version of getline, none of the built-in variables are changed, and the record is not split into elds.

3.8 Closing Input Files and Pipes

If the same le name or the same shell command is used with getline more than once during the execution of an awk program, the le is opened (or the command is executed) only the rst time. At that time, the rst record of input is read from that le or command. The next time the same le or command is used in getline, another record is read from it, and so on.

This implies that if you want to start reading the same le again from the beginning, or if you want to rerun a shell command (rather than reading more output from the command), you must take special steps. What you must do is use the close function, as follows:

34

The AWK Manual

close( lename)

or

close(command)

The argument lename or command can be any expression. Its value must exactly equal the string that was used to open the le or start the command|for example, if you open a pipe with this:

"sort -r names" | getline foo

then you must close it with this:

close("sort -r names")

Once this function call is executed, the next getline from that le or command will reopen thele or rerun the command.

close returns a value of zero if the close succeeded. Otherwise, the value will be non-zero.