Home » Linux » bash: get list of variables whose name matches a certain pattern

bash: get list of variables whose name matches a certain pattern

Posted by: admin November 29, 2017 Leave a comment

Questions:

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?

Answers:

Use the builtin command compgen:

compgen -A variable | grep X

Questions:
Answers:

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.*"

Questions:
Answers:

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 '(?<==).*'

Questions:
Answers:

Easiest might be to do a

printenv |grep D.*=

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

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