48

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?

codeforester
  • 34,080
  • 14
  • 96
  • 122
Paolo Tedesco
  • 52,498
  • 33
  • 138
  • 187

6 Answers6

70

Use the builtin command compgen:

compgen -A variable | grep X
Johannes Schaub - litb
  • 481,675
  • 123
  • 870
  • 1,191
  • 10
    (+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 Feb 04 '09 at 16:44
  • 2
    @AlexanderMills it works for bash. Checked with bash-3.2 on macos. – huch Sep 20 '18 at 08:35
14

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
  • 28,753
  • 4
  • 49
  • 68
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 '(?<==).*'
anandi
  • 101
  • 1
  • 4
  • this needs to note that -P may require additional library to be installed on some older platforms – noonex Mar 04 '17 at 13:50
3

Easiest might be to do a

printenv |grep D.*=

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

alxp
  • 5,886
  • 1
  • 21
  • 19
1
env | awk -F= '{if($1 ~ /X/) print $1}'
dsm
  • 10,053
  • 1
  • 36
  • 70
  • I needed to get the values also. By simply removing the `$1` from your solution, my problem was solved. Thanks. – jpbochi Aug 15 '16 at 19:36
1

Enhancing Johannes Schaub - litb answer removing fork/exec in modern bash we could do

compgen -A variable  -X '!*X*'

i.e an X in any position in the variable list.

Phi
  • 625
  • 7
  • 21