首页 > 解决方案 > 如何在 grep 等 python 中使用通配符搜索环境变量

问题描述

假设在我的环境变量中有一个关键字,其值如下

search_env_keyword_mytest=test1234

如果我在命令下运行,则在 unix shell 中

search_env="search_env_keyword_"
find_match=`printenv | grep ${search_env}* `
then
echo $find_match will be search_env_keyword_mytest=test1234

如何在python中实现相同的效果这是我所做的,但它不起作用。

pattern = "search_env_keyword_\\w+"
myPattern = re.compile(r'{linehead}'.format(linehead=pattern))
for a in os.environ:
        match = re.findall(myPattern, a)

它不起作用,它只是打印,我如何在 pythonsearch_env_keyword_中打印作为结果。search_env_keyword_mytest=test1234search_env_keyword_mytest=test1234

标签: python

解决方案


re.findall只返回字符串的匹配部分,而不是整个字符串。(这相当于grep -o.)由于您的正则表达式应该只匹配每个环境变量一次,因此您应该只使用re.match.

此外,os.environ是一个字典,所以a只有键。如果您还想打印该值,则需要手动添加。

myPattern = re.compile(r'search_env_keyword_\w+')
for key, val in os.environ.items():
    if myPattern.match(a):
        print(f'{key}={val}')

推荐阅读