Use GREP on array to find words
The simplest solution would be to pipe the array elements into grep:
printf -- '%s\n' "${foo[@]}" | grep spi
A couple of notes:
printf is a bash builtin, and you can look it up with man printf
. The --
option tells printf that whatever follows is not a command line option. That guards you from having strings in the foo
array being interpreted as such.
The notation of "${foo[@]}"
expands all the elements of the array as standalone arguments. Overall the words in the array are put into a multi-line string and are piped into grep, which matches every individual line against spi.
The following will print out all words that contain spi:
foo=(spi spid spider spiderman bar)
for i in ${foo[*]}
do
echo $i | grep "spi"
done
IFS=$'\n' ; echo "${foo[*]}" | grep spi
This produces the output:
spi
spid
spider
spiderman
lospia