I have an array
array=("a b" "c d")
Now I have to search for a b
and find occurrence. How to approach?
I have an array
array=("a b" "c d")
Now I have to search for a b
and find occurrence. How to approach?
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"
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.
for i in "${!array[@]}"
to directly get the array indices, which will handle missing indices and associative arrays without problems.
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
array=("a a" "b b")
I think?
Dec 12, 2017 at 14:06
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.