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
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.GNU bash, version 5.1.4(1)-release (x86_64-pc-linux-gnu) I get this error: ${(M)array:#$~pattern}: bad substitution
bash is not zsh.
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.
trwith no wildcard? Nothing?