manpagez: man pages & more
info gawk
Home | html | info | man

File: gawk.info,  Node: Assignment Options,  Prev: Variables.php">Using Variables,  Up: Variables

6.1.3.2 Assigning Variables on the Command Line
...............................................

Any 'awk' variable can be set by including a "variable assignment" among
the arguments on the command line when 'awk' is invoked (*note Other
Arguments::).  Such an assignment has the following form:

     VARIABLE=TEXT

With it, a variable is set either at the beginning of the 'awk' run or
in between input files.  When the assignment is preceded with the '-v'
option, as in the following:

     -v VARIABLE=TEXT

the variable is set at the very beginning, even before the 'BEGIN' rules
execute.  The '-v' option and its assignment must precede all the file
name arguments, as well as the program text.  (*Note Options:: for more
information about the '-v' option.)  Otherwise, the variable assignment
is performed at a time determined by its position among the input file
arguments--after the processing of the preceding input file argument.
For example:

     awk '{ print $n }' n=4 inventory-shipped n=2 mail-list

prints the value of field number 'n' for all input records.  Before the
first file is read, the command line sets the variable 'n' equal to
four.  This causes the fourth field to be printed in lines from
'inventory-shipped'.  After the first file has finished, but before the
second file is started, 'n' is set to two, so that the second field is
printed in lines from 'mail-list':

     $ awk '{ print $n }' n=4 inventory-shipped n=2 mail-list
     -| 15
     -| 24
     ...
     -| 555-5553
     -| 555-3412
     ...

   Command-line arguments are made available for explicit examination by
the 'awk' program in the 'ARGV' array (*note ARGC and ARGV::).  'awk'
processes the values of command-line assignments for escape sequences
(*note Escape Sequences::).  (d.c.)

   Normally, variables assigned on the command line (with or without the
'-v' option) are treated as strings.  When such variables are used as
numbers, 'awk''s normal automatic conversion of strings to numbers takes
place, and everything "just works."

   However, 'gawk' supports variables whose types are "regexp".  You can
assign variables of this type using the following syntax:

     gawk -v 're1=@/foo|bar/' '...' /path/to/file1 're2=@/baz|quux/' /path/to/file2

Strongly typed regexps are an advanced feature (*note Strong Regexp
Constants::).  We mention them here only for completeness.

© manpagez.com 2000-2025
Individual documents may contain additional copyright information.