Given the following array in Shell Programming
foo=(spi spid spider spiderman bar lospia)
I would like to use GREP to search for all words in the array which has the 3 letters spi
Correct output : spi spi spider spiderman lospia
I have tried something like this
foo=(spi spid spider spiderman)
grep "spi" foo
But it seems it is wrong , what is the correct way to go about it ???
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With