Search an array and return index (bash)

Hi all,

In bash, is there any way of searching an array and returning the index?

For example, how could I write a script that would do the following:
>> search note_array=(C D E F G A B) for F
return the value 3 (or 4)

Thanks,
R

Like this?...

#!/bin/bash

arr[1]=A
arr[2]=B
arr[3]=C
arr[4]=D

srch="B"

for (( i=1;i<=${#arr
[*]};i++ ))
do
        if [ ${arr[$i]} == $srch ]
        then
                echo "$srch found at index $i"
                break
        fi
done

--ahamed

1 Like

Thanks, Ahamed.

Rather than writing a script with a for-loop and if-statement, I was wondering if there was a single utility that could do it. I know in awk there's the index utility, but that only works for strings rather than arrays.

Is there an analogous utility for arrays?

in awk you can split a string into an array and index the array:

$ nawk 'BEGIN { n=split("A|B|C|D",a,"|"); print a[3]}' < /dev/null
C

Array can contain ANY kind of data...

1 Like

Thanks vgersh99.

Is there a way of searching the array and returning the index, though?

sure, but you have to search/iterate:

$ nawk -v s='C' 'BEGIN { n=split("A|B|C|D",a,"|"); for(i=1;i in a;i++) if (a==s) {print i;break}}' < /dev/null

or you can invert the split array to make a truly associative to be index by your A|B|etc letters with value of 1,2,3,etc... And then you can simply do: invertedArray["A"] and it will return the 'index'.
But either way you have iterate through the array...

Or as an alternative... your string are in the file strings.txt:

A
B
C
D
E

you could do:

nawk s='C' '{a[$1]=FNR}END{print a}' strings.txt
1 Like