External variable in awk

后端 未结 4 1461
Happy的楠姐
Happy的楠姐 2021-01-07 22:23

I have a script, in which a script snippet is:

x=3
awk \'$2=$x{print $1}\' infile

The external variable is x,

but it p

4条回答
  •  醉话见心
    2021-01-07 23:02

    You pass an external variable for use in awk with the -v option:

    some_variable=3
    awk -v x=$some_variable '$2 == x {print $1}' infile
    

    Also note that you need to change your code from $2=$x to $2 == x

    • Use == instead =: the latter is assignment
    • Do not prefix normal variables with $ inside the awk script.

    Aside: You need to specify one -v for each variable you want to pass in, e.g:

    var1=2
    var2=4
    awk -v x=$var1 -v y=$var2 '$2 == x {print y " " $1}' infile
    

提交回复
热议问题