3

I'm looking for something similar to the suggestion in this answer:

Given a zsh array I want a count of how many elements match a pattern (rather than obtain the first/last match or the index of the first/last match, like the rRiI subscripting flags would do).

myarray=(-test.list -test.v -c spam fiddle)

if ((${myarray[(I)-test.*]})); then
   echo "there is at least one test flag"
   echo "there are <solution here> test flags"
   if ((<solution here> >= 5)); then
      echo "seriously, there are many test flags"
   fi
fi

Ideally this should be possible to combine with slicing

if ((${array[2,$end][(I)-test.*]})); then
   echo "there are <solution> test flag(s) in the range I consider interesting"
fi
pseyfert
  • 868

1 Answers1

2

Combine three parameter expansion features:

  • ${…:#PATTERN} to filter elements that match PATTERN;
  • (M) to keep matching elements (without this flag, the filter removes matching elements);
  • ${#…} to count the resulting elements.
if [[ -n ${(M)myarray:#-test.*} ]]; then
   echo "there are ${(M)#myarray:#-test.*} test flags"
    …

And you can even combine this with subscripting.

% echo ${(M)#myarray[1,-1]:#-test*}
2
% echo ${(M)#myarray[2,-1]:#-test*}
1