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”的变量的所有名称?
5 个解决方案
#1
46
Use the builtin command compgen:
使用builtin命令compgen:
compgen -A variable | grep X
#2
6
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 $1}' | 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 $1}' | grep ".*X.*"
#3
3
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 '(?<==).*'
#4
2
Easiest might be to do a
最简单的可能是做一个
printenv |grep D.*=
The only difference is it also prints out the variable's values.
唯一的区别是它还打印出变量的值。
#5
1
env | awk -F= '{if($1 ~ /X/) print $1}'
#1
46
Use the builtin command compgen:
使用builtin命令compgen:
compgen -A variable | grep X
#2
6
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 $1}' | 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 $1}' | grep ".*X.*"
#3
3
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 '(?<==).*'
#4
2
Easiest might be to do a
最简单的可能是做一个
printenv |grep D.*=
The only difference is it also prints out the variable's values.
唯一的区别是它还打印出变量的值。
#5
1
env | awk -F= '{if($1 ~ /X/) print $1}'