Bash: get a list of variables whose name matches a specific pattern

In bash

echo ${!X*} 

prints all variable names whose name begins with "X".
Is it possible to get the same with an arbitrary template, for example. get all variable names whose name contains "X" at any position?

+27
linux scripting bash
Feb 04 '09 at 14:55
source share
5 answers

Use the built-in compgen command:

 compgen -A variable | grep X 
+41
Feb 04 '09 at 15:50
source share

This should do it:

 env | grep ".*X.*" 

Edit: Sorry, this also distorts the value of X. This version is only looking for X in the name var

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

As Paul points out in the comments, if you are also looking for local variables, env must be replaced with set:

 set | awk -F "=" '{print $1}' | grep ".*X.*" 
+6
Feb 04 '09 at 15:05
source share

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

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

or to simplify editing the desired template

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

or simply (perhaps more easily remembered)

 set | cut -d= -f1 | grep X 

If you want to combine X inside variable names, but output in the form name = value, then:

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

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

 set | grep -P '^\w*X\w*(?==)' | grep -oP '(?<==).*' 
+3
Jan 13 '13 at 16:34
source share

The easiest way is to do

 printenv |grep D.*= 

The only difference is that it also displays the values โ€‹โ€‹of the variables.

+1
04 Feb '09 at 15:08
source share
 env | awk -F= '{if($1 ~ /X/) print $1}' 
+1
04 Feb '09 at 15:10
source share



All Articles