Created at:
AWK notes
Tips
Using getline
getline can be used for several different purposes, like reading from a pipe. Its usage can be strange for those who come from other programming languages. For instance, program 1 and 2 differ from only one slash. Compare the output of both:
**Program 1**::
{
"ls /" | getline var
print var
"ls /" | getline var
print var
}
**Program 2**::
{
"ls /" | getline var
print var
"ls //" | getline var
print var
}
The output of the command awk -f program.awk /etc/fstab
are:
**Program 1**::
altroot
bin
boot
boot.cfg
dev
disk
etc
export
home
...
**Program 2**::
altroot
altroot
bin
bin
boot
boot
boot.cfg
boot.cfg
dev
dev
...
awk
program memorizes the string you used to pass to pipe and constantly
reads from it if you use it several times. It is a very powerful tool and can
be used in a loop::
while ((command | getline) > 0)
...
So, if you want to use different commands, you have to take care to use different strings or close the latest command::
command = "ls /"
command | getline var
close(command)
This problem came up when I needed to use two temporary files, but the following code didn't work::
command = "mktemp /tmp/file.XXXX"
command | getline file1
command | getline file2
Instead, I had to use::
command = "mktemp /tmp/file.XXXX"
command | getline file1
close(command)
command | getline file2
close(command)