bash 获取名称与特定模式匹配的变量列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/511694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get list of variables whose name matches a certain pattern
提问by Paolo Tedesco
In bash
在 bash 中
echo ${!X*}
will print all the names of the variables whose name starts with 'X'.
Is it possible to get the same with an arbitrary pattern, e.g. get all the names of the variables whose name contains an 'X' in any position?
将打印名称以“X”开头的变量的所有名称。
是否可以使用任意模式获得相同的结果,例如获得名称在任何位置包含“X”的变量的所有名称?
回答by Johannes Schaub - litb
Use the builtin command compgen:
使用内置命令 compgen:
compgen -A variable | grep X
回答by diciu
This should do it:
这应该这样做:
env | grep ".*X.*"
Edit: sorry, that looks for X in the value too. This version only looks for X in the var name
编辑:抱歉,它也在值中查找 X。此版本仅在 var 名称中查找 X
env | awk -F "=" '{print }' | grep ".*X.*"
As Paul points out in the comments, if you're looking for local variables too, env needs to be replaced with set:
正如 Paul 在评论中指出的那样,如果您也在寻找局部变量,则需要将 env 替换为 set:
set | awk -F "=" '{print }' | grep ".*X.*"
回答by anandi
This will search for X only in variable names and output only matching variable names:
这将仅在变量名称中搜索 X 并仅输出匹配的变量名称:
set | grep -oP '^\w*X\w*(?==)'
or for easier editing of searched pattern
或者为了更容易地编辑搜索的模式
set | grep -oP '^\w*(?==)' | grep X
or simply (maybe more easy to remember)
或者简单地(也许更容易记住)
set | cut -d= -f1 | grep X
If you want to match X inside variable names, but output in name=value form, then:
如果要匹配变量名内的 X,但以 name=value 形式输出,则:
set | grep -P '^\w*X\w*(?==)'
and if you want to match X inside variable names, but output only value, then:
如果你想在变量名中匹配 X,但只输出值,那么:
set | grep -P '^\w*X\w*(?==)' | grep -oP '(?<==).*'
回答by alxp
Easiest might be to do a
最简单的可能是做一个
printenv |grep D.*=
The only difference is it also prints out the variable's values.
唯一的区别是它还打印出变量的值。
回答by dsm
env | awk -F= '{if( ~ /X/) print }'

