用shell变量的扩展替换字符串的一部分 [英] Replace a part of a string with a shell variable's expansion

查看:69
本文介绍了用shell变量的扩展替换字符串的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是替换文本文件中的所有特殊"字符串,并将其替换为系统变量.例如,输入将是这样的行:

My goal is to replace all "special" strings from text file and replacing them with system variables. For example as input would be line like this one:

__HOME__/properties/common/file.properties

在这里,特殊字符串是__HOME__,我应该将其替换为系统$ HOME变量.输出应为:

Here the special string is __HOME__ and I should replace it with the system $HOME variable. As output it should be:

/home/user/properties/common/file.properties

我正尝试使用 sed 命令解决此问题,而我到了这一点:

I was trying to resolve this problem with sed command and I came to this point:

echo __HOME__/properties/common/file.properties | sed -e 's/\(__\)\([A-Z]*\)\(__\)/\2/g'

作为输出,我得到 HOME/properties/common/file.properties ,这是错误的.我试图用 echo \ 2 之类的东西替换 sed (在这里是 \ 2 )中的反向引用,但这是行不通的.Bash有什么可以做的吗?

As output i get HOME/properties/common/file.properties which is wrong. I was trying to replace the back reference from sed (here \2) with something like echo \2 but this is not going to work. Is there anything which could be done in Bash?

推荐答案

可以使用perl

perl -lpe 's/__(.+?)__/$ENV{$1}/g' file

只需检查具有 __ something __ 的字符串,并将其替换为shell中的环境变量.

Just checks for strings which have __something__ and replaces them with the environment variable from your shell.

这篇关于用shell变量的扩展替换字符串的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆