What is the tersest way to efficiently iterate over all matches in a file for a regex pattern in zsh?
I’d prefer a completely zsh-native method, if possible, instead of using external commands like grep
.
Some possibilities:
- Iterate over an array created from a command substitution of a
grep
(or similar external command) of the file - Use process substitution to read the file into a variable, then use some bash syntax / expansion / builtin / whatever either to iterate over matches or to save the matches into an array over which to iterate. The simplest way I know to do this is to loop using the
=~
conditional and thematch
variable to obtain one match per iteration, and to truncate the value to remove the most recent match on each iteration. That seems overly verbose, and that would presumably copy the remaining text of the value on each iteration. It would presumably be more performant (but also more verbose) to specify a start index for each regex match, progressing the start index past the most recent match on each iteration instead of truncating the value, but I don’t know if that’s possible in zsh. A dedicated syntax to iterate over all regex matches from the variable (or from the file) or to output an array containing all matches from the variable (or from the file) would be nicer, if either exists. - Something else…