AWK Variables
awk variables are initialized to either zero or the empty string the first time they are used.Variables
- NR -- The current line's sequential number
- NF -- The number of fields in the current line
- FS -- The input field separator; defaults to whitespace and is reset by the -F command line parameter
abhishek@ubuntu-a:~/Desktop/test$ cat calc
3 56
567 89
awkuser@ubuntu-a:~/Desktop/test$ awk '{d=($2-($1-4));s=($2+$1);print d/sqrt(s),d*d/s }' calc
7.42077 55.0678
-18.5066 342.494
awkuser@ubuntu-a:~/Desktop/test$
in above example we have a file calc with two rows and two columns.
Note that the final statement, a "print" in this case, does not need a semicolon. It doesn't hurt to put it in, though.
Integer variables can be used to refer to fields. If one field contains information about which other field is important, this script will print only the important field:
$ awk '{imp=$1; print $imp }' calc
The special variable NF tells you how many fields are in this record. This script prints the first and last field from each record, regardless of how many fields there are:
if now calc file is
3 56 abd 567 89 xyz
$ awk '{print $1,$NF }' calc
3 abd
567 xyz
