删除awk中的变量 [英] Delete a variable in awk
问题描述
我想知道是否可以删除awk
中的变量.对于数组,您可以说delete a[2]
,并且数组a[]
的索引2
将被删除.但是,对于变量我找不到方法.
I wonder if it is possible to delete a variable in awk
. For an array, you can say delete a[2]
and the index 2
of the array a[]
will be deleted. However, for a variable I cannot find a way.
最接近的意思是var=""
或var=0
.
但是,似乎不存在的变量的默认值是0
或False
:
But then, it seems that the default value of a non-existing variable is 0
or False
:
$ awk 'BEGIN {if (b==0) print 5}'
5
$ awk 'BEGIN {if (!b) print 5}'
5
所以我也想知道是否可以区分设置为0
的变量和尚未设置的变量,因为似乎没有:
So I also wonder if it is possible to distinguish between a variable that is set to 0
and a variable that has not been set, because it seems not to:
$ awk 'BEGIN {a=0; if (a==b) print 5}'
5
推荐答案
没有用于取消设置/删除变量的操作.当变量的未使用函数参数用作局部变量时,唯一一次将变量重新设置为函数调用结束时:
There is no operation to unset/delete a variable. The only time a variable becomes unset again is at the end of a function call when it's an unused function argument being used as a local variable:
$ cat tst.awk
function foo( arg ) {
if ( (arg=="") && (arg==0) ) {
print "arg is not set"
}
else {
printf "before assignment: arg=<%s>\n",arg
}
arg = rand()
printf "after assignment: arg=<%s>\n",arg
print "----"
}
BEGIN {
foo()
foo()
}
$ awk -f tst.awk file
arg is not set
after assignment: arg=<0.237788>
----
arg is not set
after assignment: arg=<0.291066>
----
因此,如果要执行某些操作A,然后取消设置变量X,然后执行操作B,则可以使用X作为局部变量将A和/或B封装在函数中.
so if you want to perform some actions A then unset the variable X and then perform actions B, you could encapsulate A and/or B in functions using X as a local var.
请注意,尽管默认值是零或null,而不是零或false,因为它的类型是数字字符串".
Note though that the default value is zero or null, not zero or false, since its type is "numeric string".
通过将其与null和零进行比较来测试未设置的变量:
You test for an unset variable by comparing it to both null and zero:
$ awk 'BEGIN{ if ((x=="") && (x==0)) print "y" }'
y
$ awk 'BEGIN{ x=0; if ((x=="") && (x==0)) print "y" }'
$ awk 'BEGIN{ x=""; if ((x=="") && (x==0)) print "y" }'
如果需要删除变量,则可以始终使用单元素数组:
If you NEED to have a variable you delete then you can always use a single-element array:
$ awk 'BEGIN{ if ((x[1]=="") && (x[1]==0)) print "y" }'
y
$ awk 'BEGIN{ x[1]=""; if ((x[1]=="") && (x[1]==0)) print "y" }'
$ awk 'BEGIN{ x[1]=""; delete x; if ((x[1]=="") && (x[1]==0)) print "y" }'
y
但是恕我直言,这会混淆您的代码.
but IMHO that obfuscates your code.
取消变量设置的用例是什么?您将如何处理var=""
或var=0
无法做到的事情?
What would be the use case for unsetting a variable? What would you do with it that you can't do with var=""
or var=0
?
这篇关于删除awk中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!