awk Variables Local variables


Example

The awk language does not directly support variables local to functions. It is however easy emulate them by adding extra arguments to functions. It is traditional to prefix these variables by a _ to indicate that they are not actual parameters.

We illustrate this technique with the definition of a single_quote function that adds single quotes around a string:

# single_quote(TEXT)
#  Return a string made of TEXT surrounded by single quotes

function single_quote(text, _quote) {
  _quote = sprintf("%c", 39)
  return sprintf("%s%s%s", _quote, text, _quote);
}

The simpler approach of using sprintf("'%s'", text) leads to practical problems because awk scripts are usually passed as single quoted arguments to the awk program.