Are there 2 ways to set awk vars via command line?

I noticed an O’Reilly awk example (1997) which assigned an awk variable by setting it on the command line after the program-text. It does work, but I can’t find this syntax in man / info awk. Have I just missed it; is it depricated…? The only syntax I’ve seen in the manual is the -v option.

awk '/home/{print foo, bar}' foo="cat" bar="dog" /proc/$$/cmdline

Output: cat dog

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It’s actually in POSIX awk (link to POSIX 2008, previous versions had it too I believe). -v is described in the Options section, the other way is in the Operands section.

There’s a difference between -v and passing the assignments at the end with the file names:

  • With -v:

The application shall ensure that the assignment argument is in the same form as an assignment operand. The specified variable assignment shall occur prior to executing the awk program, including the actions associated with BEGIN patterns (if any). Multiple occurrences of this option can be specified.

  • Mixed in with the file names:

[…] Each such variable assignment shall occur just prior to the processing of the following file, if any. Thus, an assignment before the first file argument shall be executed after the BEGIN actions (if any), while an assignment after the last file argument shall occur before the END actions (if any). If there are no file arguments, assignments shall be executed before processing the standard input.

Example:

$ cat input 
hello
hello
$ awk -v var=one 'BEGIN{print var} /hello/{print var} END{print var}' 
    var=two input var=three input var=four
one
two
two
three
three
four

Method 2

This is an old style of setting variables externally in awk. It was ambiguous (what if you had a filename named foo=cat), so later versions added a -v option. It should probably work for backward-compatibility, but you can’t guarantee. And as I said, the -v option is newer, so not all versions of awk may support it.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x