Given a Zsh array myarray, I can make out of it a subset array
set -A subarray
for el in $myarray
do
if [[ $el =~ *x*y* ]]
then
subarray+=($el)
fi
done
which, in this example, contains all elements from myarray which have somewhere an x and an y, in that order.
Question:
Given the plethora of array operations available in zsh, is there an easier way to achieve this? I checked the man page and the zsh-lovers page, but couldn't find anything suitable.
This should do the trick
subarray=(${(M)myarray:#*x*y*z})
You can find the explanation in the [section about Parameter Expansion] in the zsh manpage. It is a bit hidden as ${name:#pattern}
without the flag (M)
does the opposite of what you want:
${name:#pattern}
If the
pattern
matches the value ofname
, then substitute the empty string; otherwise, just substitute the value ofname
. Ifname
is an array the matching array elements are removed (use the(M)
flag to remove the non-matched elements).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With