Getline into a variable

In this method, we fetch the next input line of the current file into a variable instead of storing it in $0. Its syntax is getline var. The following example illustrates how this method works:

$ vi getline_var.awk

{
print "$0 -> : ",NR, $0
getline tmp;
print "tmp -> : ",NR, tmp;
}

$ awk -f getline_var.awk cars.dat

The output of the execution of the previous code is as follows:

$0 ->    :  1 maruti          swift       2007        50000       5
tmp -> : 2 honda city 2005 60000 3
$0 -> : 3 maruti dezire 2009 3100 6
tmp -> : 4 chevy beat 2005 33000 2
$0 -> : 5 honda city 2010 33000 6
tmp -> : 6 chevy tavera 1999 10000 4
$0 -> : 7 toyota corolla 1995 95000 2
tmp -> : 8 maruti swift 2009 4100 5
$0 -> : 9 maruti esteem 1997 98000 1
tmp -> : 10 ford ikon 1995 80000 1
$0 -> : 11 honda accord 2000 60000 2
tmp -> : 12 fiat punto 2007 45000 3

In the previous example, at the beginning of the body block, before executing any statement, AWK reads the first line from the current input file and stores it in $0. The print statement prints the first line from the current input file. Using the getline command, we force the AWK to read the next line from the current input file and store it in the tmp variable. Then we print the second line stored in the tmp variable. This body block continues to work in the same manner for the rest of the current input file's lines. The $0 will print the odd-numbered line and the tmp variable will print the even-numbered lines of the input file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.161.225