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 '16 at 16:12
  • yes, nothing, it should be exact without wildcard. – Sharique Dec 8 '16 at 7:52

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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.