As the name indicates, getline function allows you to read a line from a file on demand. This is most useful when you need something based on line number. The following example shows how you can replace mth line from a file with nth line from another file. There are many syntax variations with getline, here the line read is saved in a variable.
$ # return value handling is not shown here, but should be done ideally $ awk -v m=3 -v n=2 'BEGIN{while(n-- > 0) getline s < "greeting.txt"} FNR==m{$0=s} 1' table.txt brown bread mat hair 42 blue cake mug shirt -7 Have a nice day
Here's an example where two files are processed simultaneously. In this case, the return value of getline is also used. It will be 1if line was read successfully, 0 if there's no more input to be read as end of file has already been reached and -1 if something went wrong. The ERRNO special variable will have details regarding the issues.
$ # print line from greeting.txt if last column of corresponding line $ # from table.txt is +ve number $ awk -v file='table.txt' '(getline line < file)==1{n=split(line, a); if(a[n]>0) print}' greeting.txt Hi there Good bye
If a file is passed as argument to awkcommand and cannot be opened, you get an error. For example:
$ awk '{print $2}' xyz.txt awk: fatal: cannot open file `xyz.txt' for reading: No such file or directory
It is recommended to always check for return value when using getline or perhaps use techniques from previous sections to avoid getline altogether.
$ # xyz.txt doesn't exist, but output doesn't show something went wrong $ awk '{getline line < "xyz.txt"; print $NF, line}' table.txt 42 -7 3.14 $ awk -v file='xyz.txt' '{ e=(getline line < file); if(e<0){print file ": " ERRNO; exit} print $NF, line }' table.txt xyz.txt: No such file or directory
See gawk manual: getline for details, especially about corner cases and errors. See also awk.freeshell: getline caveats.