Unlike many other languages awk lets you declare and initialise user variables when you use
them (that is, you do not have to declare them before you use them).
An example piece of awk code that uses a variable is shown below :-
{
x="hello"
print x
}
The above awk program displays the word hello for each record it reads from
the input file. The above was an example of using a variable (x) in a string context.
In addition to user variables, awk also has a set of reserved program variables for your use. You can use both your own variables and the reserved variables in the pattern and action portion of an awk program.
The following is a list of the reserved awk program variables :-
| Variable | Represents |
|---|---|
|
NR $0 NF $1-$n FS OFS RS ORS FILENAME |
record number of current record the current record (as a single variable) number of fields in the current record fields in the current record input field seperator (default: SPACE or TAB) output field seperator (default: SPACE) input record seperator (default: NEWLINE) output record seperator (default: NEWLINE) name of the current input file |
The input and output record seperators are, by default, NEWLINE characters. Thus, awk takes each line in the input file to be a separate record and appends a NEWLINE to the end of each record that it sends to the standard output. The input field seperators are, by default, SPACES and TABS. The output field seperator is a SPACE. You can change the value of any of the seperators at any time by assigning a new value to its associated variable. Also, the input field seperator can be set on the command line using the -F command line option.
Test your knowledge on the above with the programming exercise for tutorial five.