1826345 Members
4145 Online
109692 Solutions
New Discussion

Search in ksh array

 
Praveen Bezawada
Respected Contributor

Search in ksh array

Hi
I have an array containing string entries
arr[0]=Entry1
arr[1]=Entry2
.
When given any string I need to check if that string is present in this array. In there any way of doing it apart from looping over the whole array.
Like in TCL we have,"array exists " Is there something of this syntax in ksh.
Any ideas or suggestions most welcome.

- Praveen
5 REPLIES 5
Sanjay Kumar Suri
Honored Contributor

Re: Search in ksh array

I have following solution

testa[0]=first
testa[1]=second
echo ${testa[1]}
echo ${testa[*]} | grep first >/dev/null
echo $?
echo ${testa[*]} | grep third >/dev/null
echo $?

It will give following output

second
0 # true
1 # false

sks




A rigid mind is very sure, but often wrong. A flexible mind is generally unsure, but often right.
Florian Heigl (new acc)
Honored Contributor

Re: Search in ksh array

It might help to first check, if the entry is in the array and do the looping only if there was something found.

if `echo ${arr[*]} | grep searchstring \
2>&1 >/dev/null`
then
go looping
fi

[i hope the [*] was the correct way to address every value in the array, can't test it right now.]
yesterday I stood at the edge. Today I'm one step ahead.
Sanjay Kumar Suri
Honored Contributor

Re: Search in ksh array

Check this as well:

testa[0]=first
testa[1]=second
if `echo ${testa[*]} | grep ${testa[0]} > /dev/null`
then
echo "successful"
fi

sks
A rigid mind is very sure, but often wrong. A flexible mind is generally unsure, but often right.
Praveen Bezawada
Respected Contributor

Re: Search in ksh array

and perhaps
grep -x
won't hurt.
Sanjay Kumar Suri
Honored Contributor

Re: Search in ksh array

No. It is hurting.

testa[0]=first
testa[1]=second
if `echo ${testa[*]} | grep -x ${testa[0]} > /dev/null`
then
echo "successful"
else
echo "unsuccessful"
fi

sks

A rigid mind is very sure, but often wrong. A flexible mind is generally unsure, but often right.