Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
    
What should the output be if the user enters tr with no wildcard? Nothing? – terdon 9 hours ago

It's easier with zsh:

$ array=(saf sri trip tata strokes)
$ pattern='*tr*'
$ printf '%s\n' ${(M)array:#$~pattern}
trip
strokes
  • ${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.
share|improve this answer

One way to do it:

array=(saf sri trip tata strokes)                      
input=*tr*
for foo in "${array[@]}"; do
    case "$foo" in
        $input) printf '%s\n' "$foo" ;;
    esac
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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