variable

A '''variable''' is a symbolic name associated with a [[value?]]. A variable acts as a container and the [[value?]] it contains may be changed from within a running [[program?]], enabling data manipulation to take place from within the [[script?]].

Variables are dynamic

In awk variables are [[dynamic?]] and can hold either [[numeric?]] or string values.

Variables do not need predefinition prior to use

In awk, there is no need to declare or initialize variables before they are used. By default, variables are initialized to the [[empty?]] string, which evaluates to [[zero?]] when [[convert?]]ed to a number.

Initialization within a begin block is possible

It is possible to initialize variables in a BEGIN block to make them obvious and to make sure they have proper initial values.

Variable names

As in most programming languages, the name of a variable must be a sequence of [[letter?]]s, [[digit?]]s, or [[underscore?]] symbols, and may not begin with a [[digit?]]. The awk interpreter is [[case_sensitive?]]. This means that variable names that have different letter cases are distinct and separate from each other:

 # The identifiers dog,Dog and DOG represent separate variables
 BEGIN {
	dog = "Benjamin"
	Dog = "Samba"
	DOG = "Bernie"
	printf "The three dogs are named %s, %s and %s.\n", dog, Dog, DOG
 }

Special variables

Some names are used for special variables.

Variables in awk do not need a sigil

In awk, variables are referenced using only the variable name and no [[sigil?]] prefix is used before the variable name:

awk '{var="foo";print var}'

Variable names inside string constants are not expanded in awk

Secondly, awk does not behave like the Unix [[shell?]]. Variables inside string constants are not expanded. The [[interpreter?]] has no way to distinguish words in a string constant from variable names, so this would never be possible. So "hello name" is a constant string, regardless of whether name is a variable in the AWK script. New strings can be constructed from string constants and variables, using concatenation:

# print the concatenation of a string and a variable directly
print "hello " name;

# concatenate, assign to 'newstr' and print that
newstr = "hello " name;
print newstr;

If the print statement is given several arguments (that is, they are separated by ","), it prints them separated by the OFS variable.

So, presuming OFS is " ", the following is the equivalent to the first example above:

print "hello", name;