Zombo
Zombo

Reputation: 1

Check if an awk 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 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?

Upvotes: 26

Views: 41477

Answers (5)

ExpertNoob1
ExpertNoob1

Reputation: 932

In the spirit of a one-liner (see Thamme's answer) that sticks more to the OP's perl reference (ternary operator):

echo -e "a\nb\nc" | awk '{t[$1]}END{print (("a" in t) ? "yes":"no")}' # prints yes, try with ("m" in t)

Upvotes: 0

NicolasK
NicolasK

Reputation: 31

BEGIN {
  split("value1 value2 value3", valueArray)
  # valueArray is {1: "value1", 2: "value2", 3: "value2"}
}
{
  # given $1 is the value to test for
  for (i in valueArray) {
    if ( $1 == valueArray[i] ) {
      print $1
      # OR 
      print "True"
      # ...
    }
  }
}

Upvotes: 0

Ryan Liu
Ryan Liu

Reputation: 537

gawk 'BEGIN { split("a b c d",parts); for (i in parts) dict[parts[i]]=1 } $1 in dict {print}' some.log

Upvotes: 0

Bob Makowski
Bob Makowski

Reputation: 973

what I do is structure my data to take advantage of what the language provides.

So instead of saying :

BEGIN {split("444 555 666", foo); .... }

say :

BEGIN { bar[ "444" ] ; ... }

or ala another suggestion:

BEGIN { 
  split("444 555 666", foo);
  for( i in FOO ) bar[foo[i]];
}

remember arrays in awk are really associative arrays.

Upvotes: 0

phunehehe
phunehehe

Reputation: 8778

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'

Upvotes: 33

Related Questions