Get list of variables whose name matches a certain pattern

后端 未结 5 500
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 09:21

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 ar

相关标签:
5条回答
  • 2020-12-13 09:37

    Easiest might be to do a

    printenv |grep D.*=
    

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

    0 讨论(0)
  • 2020-12-13 09:37
    env | awk -F= '{if($1 ~ /X/) print $1}'
    
    0 讨论(0)
  • 2020-12-13 09:39

    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.*"
    
    0 讨论(0)
  • 2020-12-13 09:49

    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 '(?<==).*'
    
    0 讨论(0)
  • 2020-12-13 09:54

    Use the builtin command compgen:

    compgen -A variable | grep X
    
    0 讨论(0)
提交回复
热议问题