100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

User-Defined Variables in AWK

Beyond built-ins, AWK lets you create your own scalar and associative-array variables with dynamic typing and automatic initialization, powering counters, accumulators, and lookups.

Patterns & VariablesBeginner9 min readJul 10, 2026
Analogies

Declaring and Using Scalar Variables

In AWK you create a variable simply by assigning to it — there is no declaration keyword. Variables are dynamically typed and hold either a number or a string, with AWK converting between them based on context. Crucially, an uninitialized variable starts as both the empty string "" and the number 0, so count++ works on a fresh variable without any setup and sum += $2 begins accumulating from zero. This automatic initialization is what makes AWK one-liners so terse: you can write total += $1 in the main block and reference total in END without ever declaring it.

🏏

Cricket analogy: An uninitialized AWK variable is like a batter's score starting at 0 the moment they take guard — you never set it, the scoreboard assumes zero and counts up from the first run.

Associative Arrays

AWK's arrays are associative, meaning their subscripts are strings (or numbers coerced to strings), not just contiguous integers. You never declare or size them; count["error"]++ creates the entry on first use. This makes arrays perfect for counting, grouping, and lookups: use a field value as the key, as in freq[$1]++ to tally occurrences of each value in column one. You iterate with for (key in array) { ... }, though the traversal order is unspecified unless you use gawk's PROCINFO["sorted_in"] or sort separately. Multidimensional access like matrix[i,j] is simulated by joining subscripts with the SUBSEP character into a single string key.

🏏

Cricket analogy: An associative array keyed by batter name is like a scorebook page per player — freq["Kohli"]++ tallies his runs, no fixed slots, a new page appears the moment a new batter arrives.

Scope, the -v Flag, and String/Number Duality

By default, user-defined variables in AWK are global — visible in BEGIN, the main rules, and END alike, and even across function calls. The one exception is a function's extra parameters, which AWK treats as local variables, a common idiom for declaring locals. You can inject a variable from outside using the -v name=value flag, which sets it before the BEGIN block runs, unlike a plain name=value argument in the file list that only takes effect when reached. Because values carry a dual string/number nature, AWK compares them numerically when both look numeric and as strings otherwise; force a type with value+0 for a number or value"" for a string.

🏏

Cricket analogy: The -v flag is like the captain setting the field before the first ball, whereas an inline name=value argument is a mid-innings field change that only applies once you reach that over.

awk
# Accumulate a sum and count without declaring variables
awk '{ sum += $1; n++ } END { print "avg =", sum/n }' numbers.txt

# Frequency count with an associative array
awk '{ freq[$2]++ } END { for (k in freq) print k, freq[k] }' data.txt

# Inject a threshold from outside with -v
awk -v limit=100 '$3 > limit { print $1, $3 }' report.txt

# Local variable idiom: extra function parameter 'i' is local
function join(arr,   i, s) { for (i in arr) s = s arr[i] " "; return s }

The -v flag processes standard C-style escape sequences in the value, so awk -v sep='\t' sets sep to an actual tab character. A plain assignment in the file argument list does not run before BEGIN, which is why -v is preferred for values that BEGIN needs.

Merely referencing an array element in a condition, such as if ("key" in arr) versus if (arr["key"]), differs: the second form creates the element as a side effect if it does not exist. Use the (key in array) test to check membership without accidentally creating empty entries.

  • Variables need no declaration; assigning to a name creates it.
  • Uninitialized variables are simultaneously 0 and "", enabling count++ and sum+= without setup.
  • Arrays are associative with string keys and grow on first use.
  • Iterate arrays with for (key in array); order is unspecified without gawk sorting.
  • User variables are global except a function's extra parameters, which are local.
  • The -v name=value flag sets a variable before BEGIN and honors escape sequences.
  • Values have dual string/number nature; force type with value+0 or value"".

Practice what you learned

Was this page helpful?

Topics covered

#Programming#AWKStudyNotes#UserDefinedVariablesInAWK#User#Defined#Variables#AWK#StudyNotes#SkillVeris#ExamPrep