Delete variable in awk

I wonder if it is possible to delete a variable in awk . For the array, you can say delete a[2] , and index 2 array a[] will be deleted. However, for the variable, I cannot find a way.

The closest I want to say is var="" or var=0 .

But then it seems that the default value of a nonexistent variable is 0 or False :

 $ awk 'BEGIN {if (b==0) print 5}' 5 $ awk 'BEGIN {if (!b) print 5}' 5 

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 is not:

 $ awk 'BEGIN {a=0; if (a==b) print 5}' 5 
+6
source share
2 answers

There is no operation to delete / delete a variable. The only time a variable becomes unset again is at the end of a function call when its unused function argument is 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> ---- 

therefore, if you want to perform some actions of A, then reset the variable X and then perform actions B, you can encapsulate A and / or B in the function using X as a local variable.

Note that the default value is zero or zero, not zero or false, because its type is "numeric string".

You check for an undefined variable by comparing it with zero 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 that you delete, you can always use a singleton 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 what confuses your code.

What would be the use case to reset a variable? What would you do with this that you cannot do with var="" or var=0 ?

+8
source

An uncorrected variable expands to "" or 0 , depending on the context in which it is running.

For this reason, I would say that this is a matter of preference and depends on the use of the variable.

Given that we use a + 0 (or slightly inconsistent +a ) in the END block to force a potentially disabled variable a to a numeric type, I think you could argue that the natural "empty" value would be "" .

I'm not sure if there is too much to read in the cases that you indicated in the question, given the following:

 $ awk 'BEGIN { if (!"") print }' 5 

( "" wrong, not surprising)

 $ awk 'BEGIN { if (b == "") print 5 }' 5 

(unset variable has a value of "" , just like 0 )

+2
source

Source: https://habr.com/ru/post/1236916/


All Articles