gpt4 book ai didi

zsh 相当于 bash ${!name*} 或 ${!name@}

转载 作者:行者123 更新时间:2023-12-02 08:06:19 25 4
gpt4 key购买 nike

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

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

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

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

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

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

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

似乎没有任何方法可以对参数名称执行任何类型的通配,只能对参数的扩展执行任何类型的通配。

(这似乎是“Use wildcard expansion to echo all variables in zsh ”解决方案的必要前提,尽管我可能会弄错。)

最佳答案

typeset -m可以拯救:

-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
<小时/>

或者$parameters来自 zsh/parameters 模块可以提供帮助:

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

关于zsh 相当于 bash ${!name*} 或 ${!name@},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59008514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com