Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use GREP on array to find words

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 ???

like image 621
Computernerd Avatar asked Jan 11 '14 03:01

Computernerd


3 Answers

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.

like image 81
mockinterface Avatar answered Sep 27 '22 17:09

mockinterface


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
like image 26
CrazyCasta Avatar answered Sep 27 '22 17:09

CrazyCasta


IFS=$'\n' ; echo "${foo[*]}" | grep spi

This produces the output:

spi
spid
spider
spiderman
lospia
like image 31
John1024 Avatar answered Sep 27 '22 16:09

John1024