在AWK外部变量 [英] external variable in awk
本文介绍了在AWK外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个脚本,其中一个脚本片段是
I have a script, in which a script snippet is
x=3
awk '$2=$x{print $1}' infile
外部变量 X
,
但它提示在 AWK
所以在这种情况下,如何让 AWK
成功运行?
so in this situation, how to make awk
run successfully?
推荐答案
您传递 AWK
使用外部变量与 -v
选项:
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
另外请注意,您需要更改从 $ 2 = $的code X
到 $ 2 == X
- 使用
==
而不是=
:后者是分配 - 请不要使用
$
preFIX正常变量AWK
脚本中。
- Use
==
instead=
: the latter is assignment - Do not prefix normal variables with
$
inside theawk
script.
旁白:你需要指定一个 -v
为你想传递的每个变量,例如:
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
这篇关于在AWK外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文