Next: , Previous: , Up: Getline   [Contents][Index]


4.9.2 Using getline into a Variable

You can use ‘getline var’ to read the next record from awk’s input into the variable var. No other processing is done. For example, suppose the next line is a comment or a special string, and you want to read it without triggering any rules. This form of getline allows you to read that line and store it in a variable so that the main read-a-line-and-check-each-rule loop of awk never sees it. The following example swaps every two lines of input:

{
     if ((getline tmp) > 0) {
          print tmp
          print $0
     } else
          print $0
}

It takes the following list:

wan
tew
free
phore

and produces these results:

tew
wan
phore
free

The getline command used in this way sets only the variables NR, FNR and RT (and of course, var). The record is not split into fields, so the values of the fields (including $0) and the value of NF do not change.