Does awk support dynamic user-defined variables?

后端 未结 3 2016
广开言路
广开言路 2020-12-10 08:04

awk supports this:

awk \'{print $(NF-1);}\'

but not for user-defined variables:

awk \'{a=123; b=\"a\"; print $($b);}\'
         


        
3条回答
  •  不知归路
    2020-12-10 08:20

    The $ notation is not a mark for variables, as in shell, PHP, Perl etc. It is rather an operator, which receives an integer value n and returns the n-th column from the input. So, what you did in the first example is not the setting/getting of a variable dynamically but rather a call to an operator/function.

    As stated by commenters, you can archive the behavior you are looking for with arrays:

    awk '{a=123; b="a"; v[b] = a; print v[b];}'
    

提交回复
热议问题