I've an array coming from the output of a command:

array=(saf sri trip tata strokes)

Now I want to filter items based on user input. The user can also use wildcards, so if the user enters *tr*, the output should be

trip strokes
  • What should the output be if the user enters tr with no wildcard? Nothing?
    – terdon
    Dec 7, 2016 at 16:12
  • yes, nothing, it should be exact without wildcard.
    – Sharique
    Dec 8, 2016 at 7:52

2 Answers 2


It's easier with zsh:

$ array=(saf sri trip tata strokes)
$ pattern='*tr*'
$ printf '%s\n' ${(M)array:#$~pattern}
  • ${array:#pattern}: expands to the elements of the array that don't match the pattern.
  • (M) (for match): reverts the meaning of the :# operator to expand to the elements that match instead
  • $~pattern, causes the content of $pattern to be taken as a pattern.
  • On GNU bash, version 5.1.4(1)-release (x86_64-pc-linux-gnu) I get this error: ${(M)array:#$~pattern}: bad substitution
    – Xaqron
    Mar 15, 2021 at 9:35
  • 1
    @Xaqron, GNU bash is not zsh. Mar 15, 2021 at 9:36

One way to do it:

array=(saf sri trip tata strokes)                      
for foo in "${array[@]}"; do
    case "$foo" in
        $input) printf '%s\n' "$foo" ;;

Note to the overly enthusiastic quoters: the right-hand side in assignments (such as *tr* in input=*tr*) doesn't need quoting.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .