Get list of variables whose name matches a certain pattern

流过昼夜 提交于 2019-12-18 10:39:37

问题


In 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?


回答1:


Use the builtin command compgen:

compgen -A variable | grep X



回答2:


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

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:

set | awk -F "=" '{print $1}' | grep ".*X.*"



回答3:


This will search for X only in variable names and output only matching variable names:

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:

set | grep -P '^\w*X\w*(?==)'

and if you want to match X inside variable names, but output only value, then:

set | grep -P '^\w*X\w*(?==)' | grep -oP '(?<==).*'



回答4:


Easiest might be to do a

printenv |grep D.*=

The only difference is it also prints out the variable's values.




回答5:


env | awk -F= '{if($1 ~ /X/) print $1}'


来源:https://stackoverflow.com/questions/511694/get-list-of-variables-whose-name-matches-a-certain-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!