Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an awk array contains a value

Tags:

arrays

awk

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 is checking the array indexes rather than values

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

How can I check if an array contains a particular value with awk?

like image 392
Zombo Avatar asked Nov 04 '14 22:11

Zombo


1 Answers

Awk noob here. I digested Steven's answer and ended up with this hopefully easier to understand snippet below. There are 2 more subtle problems:

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

So you have to convert your array (which is actually a dictionary) to a dictionary with the values as 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 one-liners:

echo "A:B:C:D:E:F" | tr ':' '\n' | \
awk 'BEGIN{ split("A D F", parts); for (i in parts) dict[parts[i]]=""}  $1 in dict'
like image 52
phunehehe Avatar answered Oct 16 '22 09:10

phunehehe