Filter items from an array based on input with wildcard
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.
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
Note to the overly enthusiastic quoters: the right-hand side in assignments (such as *tr*
in input=*tr*
) doesn't need quoting.