zsh 相当于 bash ${!name*} 或 ${!name@} [英] zsh equivalent of bash ${!name*} or ${!name@}

查看:42
本文介绍了zsh 相当于 bash ${!name*} 或 ${!name@}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bash 中,有一个参数扩展来生成与给定前缀匹配的变量的名称.例如:

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

zsh 中是否有等价物?我知道 (P) 参数扩展标志相当于类似的 bash 间接扩展 ${!foo}:

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

但据我所知,(P) 不处理前缀匹配.

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

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

似乎没有任何方法可以对参数 name 执行任何类型的 globbing,只能对参数的扩展 执行.

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.

(这似乎是解决使用通配符扩展回显 zsh 中的所有变量"的必要前提,虽然我可能会误会.)

(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.)

推荐答案

typeset -m 可以拯救:

-m

如果给定 -m 标志,则名称参数被视为模式(使用引号防止这些被解释为文件模式).在没有属性标志的情况下,打印所有具有匹配名称的参数(或带有 -f 标志的函数)(在这种情况下不使用 shell 选项 TYPESET_SILENT).

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 内置命令, 排版

% 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

<小时>

$parameters 来自 zsh/parameters 模块可以帮助:

参数

这个关联数组中的键是当前定义的参数的名称.

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

-- zshmodules(1), zsh/参数模块,参数

% 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

这篇关于zsh 相当于 bash ${!name*} 或 ${!name@}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆