"who am i" | getline
That expression sets "$0" to the output of the who am
i command.
dale ttyC3 Jul 18 13:37
The line is parsed into fields and the system variable NF
is set. Similarly, you can assign the result to a variable:
"who am i" | getline me
By assigning the output to a variable, you avoid
setting $0 and NF, but
the line is not split into fields.
The following script is a fairly simple example of piping the output
of a command to getline. It uses the output from the
who am i command to get the user's name. It then looks up
the name in /etc/passwd, printing out the fifth
field of that file, the user's full name:
awk '# getname - print users fullname from /etc/passwd
BEGIN { "who am i" | getline
name = $1
FS = ":"
}
name ~ $1 { print $5 }
' /etc/passwd
The command is executed from the BEGIN procedure,
and it provides us with the name of the user that will be used to find
the user's entry in /etc/passwd. As explained
above, who am i outputs a single line, which
getline assigns to $0. $1, the first field of that
output, is then assigned to name.
The field separator is set to a colon (:) to allow us to access
individual fields in entries in the /etc/passwd
file. Notice that FS is set after
getline or else the parsing of the command's output
would be affected.
Finally, the main procedure is designed to test that the
first field matches name. If it does, the fifth
field of the entry is printed. For instance, when Dale runs
this script, it prints "Dale Dougherty."
When the output of a command is piped to getline
and it contains multiple lines, getline reads a
line at a time. The first time getline is called
it reads the first line of output. If you call it again, it reads the
second line. To read all the lines of output, you must set up a loop
that executes getline until there is no more
output. For instance, the following example uses a
while loop to read each line of output and assign
it to the next element of the array, who_out:
while ("who" | getline)
who_out[++i] = $0
Each time the getline function is called, it reads
the next line of output. The who command, however,
is executed only once.
The next example looks for "@date" in a document and replaces it with
today's date:
# subdate.awk -- replace @date with todays date
/@date/ {
"date +'%a., %h %d, %Y'" | getline today
gsub(/@date/, today)
}
{ print }
This script might be used to insert the
date in a form letter:
To: Peabody
From: Sherman
Date: @date
I am writing you on @date to
remind you about our special offer.
All lines of the input file would be passed through as is, except
the lines containing "@date", which are replaced with
today's date:
$ awk -f subdate.awk subdate.test
To: Peabody
From: Sherman
Date: Sun., May 05, 1996
I am writing you on Sun., May 05, 1996 to
remind you about our special offer.