python - 如何在 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=test1234
search_env_keyword_mytest=test1234
解决方案
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}')
推荐阅读
- android - 我不能使用 findViewById(int)。无法参考
- powershell - 尝试从多值属性“Proxyaddresses”导出到 csv
- java - Spring Boot 中的 TaskRejectedException
- c# - 如何创建到 Azure 数据湖存储到 API 的连接?
- vb.net - 打印报表查看器中的字符无效“$”
- c++ - C++ srand() 在函数调用中重置
- perl - 如何使用 Perl 的 Text::Aspell 对文本进行拼写检查?
- linux - Zenity 命令输出 SHA-256 哈希
- python - 从列表中提取唯一的 RGB 值
- hash - AIX中如何基于sha256算法为数据文件创建Hashvalue