4

I have an array

array=("a b" "c d")

Now I have to search for a b and find occurrence. How to approach?

4

4 Answers 4

6

When you print your array elements each on a new line, you can use grep:

printf '%s\n' "${array[@]}" | grep "a b"

If array elements contain \n, it's better to use \0 and grep -z (thanks @muru):

printf '%s\0' "${array[@]}" | grep -z "a b"
1
  • 4
    Consider using \0 and grep -z instead
    – muru
    Dec 12, 2017 at 14:07
2

With bash:

array=("a b" "c d")

for ((i=0; i<${#array[@]}; i++)); do
  if [[ ${array[$i]} == "a b" ]]; then
    echo "Element $i matched"
  fi
done

Output:

Element 0 matched

${#array[@]} contains number of last element in array.

1
  • 4
    You can also do for i in "${!array[@]}" to directly get the array indices, which will handle missing indices and associative arrays without problems.
    – muru
    Dec 13, 2017 at 5:17
0

This SO Q&A suggest a way to perform the search

Implementation for your question:

#!/bin/bash
array=("a b" "c d")
value="a b"
if [[ " ${array[@]} " =~ " ${value} " ]]; then
   echo found $value
fi

Output:

found a b
1
  • OK but note the comment below the SO answer "Not a good strategy if your fields contain spaces." - for example it will "match" if array=("a a" "b b") I think? Dec 12, 2017 at 14:06
0

A variant on Cyrus's answer in function form:

function find_in_array() {
    local needle="$1"
    shift
    local haystack=("$@")
    for ((i=0; i<${#haystack[@]}; i++)); do
      if [[ ${haystack[$i]} == "$needle" ]]; then
        echo $i
      fi
    done
}

This prints the index of the first position of the needle in the haystack array, and nothing if the needle is not found.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .