zsh equivalent of bash ${!name*} or ${!name@}
Asked Answered
R

1

9

In bash, there is a parameter expansion to generate the names of variables matching a given prefix. For example:

$ foo1=a foo2=b four=4
$ echo "${!foo@}"
foo1 foo2

Is there an equivalent in zsh? I know the (P) parameter expansion flag is the equivalent of the similar bash indirection expansion ${!foo}:

# bash
$ foo=bar bar=3
$ echo ${!foo}
3

# zsh
% foo=bar bar=3
% echo ${(P)foo}
3

but as far as I can tell, (P) does not also handle prefix matching.

% echo "${(P}foo@}"
zsh: bad substitution

There doesn't seem to be any way to perform any type of globbing on a parameter name, only on the expansion of a parameter.

(This seems to be a necessary precursor for a solution for "Use wildcard expansion to echo all variables in zsh", though I could be mistaken about that.)

Reflect answered 23/11, 2019 at 14:13 Comment(0)
I
6

typeset -m could rescue:

-m

If the -m flag is given the name arguments are taken as patterns (use quoting to prevent these from being interpreted as file patterns). With no attribute flags, all parameters (or functions with the -f flag) with matching names are printed (the shell option TYPESET_SILENT is not used in this case).

-- zshbuiltins(1), shell builtin commands, typeset

% foo1=a foo2=b four=4
% typeset -m 'foo*'
foo1=a
foo2=b
% typeset +m 'foo*'
foo1
foo2
% setopt extendedglob
% print -l ${$(typeset +m 'foo*')/(#m)*/${(P)MATCH}}
a
b

Or $parameters from zsh/parameters module could help:

parameters

The keys in this associative array are the names of the parameters currently defined.

-- zshmodules(1), the zsh/parameter module, parameters

% foo1=a foo2=b four=4
% print -l ${(Mk)parameters:#foo*}
foo1
foo2
% setopt extendedglob
% print -l ${${(Mk)parameters:#foo*}/(#m)*/${(P)MATCH}}
a
b
Inosculate answered 23/11, 2019 at 16:36 Comment(1)
Ah, I thought I remembered parameters being defined, though couldn't remember where I saw it. Didn't see it in man zshparams, so thought I had imagined it.Reflect

© 2022 - 2024 — McMap. All rights reserved.