Check if the array contains a value

With Perl, you can check if an array contains a value

$ perl -e '@foo=(444,555,666); print 555 ~~ @foo ? "T" : "F"' T 

However, with awk, this similar command checks array indices, not Values

 $ awk 'BEGIN {split("444 555 666", foo); print 555 in foo ? "T" : "F"}' F 

How to check if an array contains a specific value with awk?

+5
source share
2 answers

Based on Thors comments , this function does the trick for me:

 function smartmatch(diamond, rough, x, y) { for (x in rough) y[rough[x]] return diamond in y } BEGIN { split("444 555 666", z) print smartmatch(555, z) ? "T" : "F" } 
+3
source

Awk noob is here. I digested Stephen's answer and as a result, with this, we hope it is easier to understand the fragment below. There are two more subtle issues:

  • Awk array is actually a dictionary. This is not ["value1", "value2"] , it is more like {0: "value1", 1: "value2"} .
  • in checks keys, and there is no built-in way to check values.

So, you need to convert your array (which is actually a dictionary) into a dictionary with values ​​in the form of keys.

 BEGIN { split("value1 value2", valuesAsValues) # valuesAsValues = {0: "value1", 1: "value2"} for (i in valuesAsValues) valuesAsKeys[valuesAsValues[i]] = "" # valuesAsKeys = {"value1": "", "value2": ""} } # Now you can use `in` ($1 in valuesAsKeys) {print} 

For single line:

 echo "A:B:C:D:E:F" | tr ':' '\n' | \ awk 'BEGIN{ split("ADF", parts); for (i in parts) dict[parts[i]]=""} $1 in dict' 
+6
source

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


All Articles