3
myArray=('Prasanth' 'kumar' 'guru')

Is it possible to get element which ends with "santh" without iterating the array(myArray) with bash.

My expected output is to get Prasanth without iterating the above array, just by checking wildcard like ('santh')and get the element.

2
  • 3
    By "unix" you mean "bash", right? The answer is probably "no". You can't apply a condition to select values from an array without iterating through the array. Commented Apr 11, 2018 at 18:47
  • 2
    You can't really do that in any language -- finding elements of an array that match a test necessarily requires iterating through the array, being an O(n) operation, unless it's indexed to allow that specific test to be performed more quickly. Some languages have sorted sets or dictionaries that let you do prefix searches quickly, but I've never seen one that would let you do a suffix search, unless it's a language organized around a datastore. (Languages that hide the iteration, sure; languages that don't need to iterate, not without preconfigured indexing). Commented Apr 11, 2018 at 19:54

1 Answer 1

7

I suggest:

printf '%s\n' "${myArray[@]}" | grep 'santh$'

Output:

Prasanth
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.