views:

494

answers:

4

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  A: 

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.*"
diciu
Only gets environment variables, not local ones. Although using "set" instead of "env" might work.
Paul Tomblin
Thanks, I didn't know about set, I usually "export" any vars I'm interested in so I only use env.
diciu
set also print out function, not only local variables and environment variables
赵如飞
A: 

Easiest might be to do a

printenv |grep D.*=

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

alxp
A: 
env | awk -F= '{if($1 ~ /X/) print $1}'
dsm
+2  A: 

Use the builtin command compgen:

compgen -A variable | grep X
Johannes Schaub - litb
(+1) This works with local variables as well. This compgen has been today's revelation - I think I should *study* all bash builtins...
Paolo Tedesco