在文件中查找并用SED替换变量 [英] Find and replace variables with SED in a file
问题描述
我想在KSH(使用SED)中的conf文件中查找和替换变量. 我的问题是:通过考虑变量名称可以包含特殊字符来识别KSH变量(例如$ toto或$ {toto})的正确正则表达式模式是什么?
I'd would like to find and replace variables in a conf file in KSH (with SED). My question is: what is the correct regex pattern to identify KSH variables (like $toto or ${toto}), by taking into account that variable's name can contains special characters ?
这里是一个例子:
比方说,我当前的外壳中有var_1=value1
和var_2=value2
(在export -p中是可伪造的).
Let's say I have var_1=value1
and var_2=value2
in my current shell (grepable in export -p).
查找和替换之前的配置文件
The configuration file before find and replace
PARAM1=$var_1/tata.txt
PARAM2=${var_2}/tata.txt
查找并替换后的配置文件
The configuration file after find and replace
PARAM1=value1/tata.txt
PARAM2=value2/tata.txt
我要做的事情:
- 在随后的conf文件中找到$ var_1和$ {var_2}(使用通用正则表达式,我想我不知道conf文件中是否有变量)
- 使用 export -p搜索每个值grep var_1 和 export -p | grep var_2
- 用先前搜索找到的值替换conf文件中的这两个变量
- Find $var_1 and ${var_2} in then conf file (with generic regex, I suppose I don't know if there are variables in the conf file)
- Search value of each with export -p | grep var_1 and export -p | grep var_2
- Replace these 2 variables in conf file by the value found by previous search
谢谢您的回答.
推荐答案
在这种情况下,邪恶和危险 eval
会派上用场: /p>
This is one those cases where the evil and dangerous eval
would come in handy:
while read line; do
eval echo "$line"
done < inputfile > outputfile
这篇关于在文件中查找并用SED替换变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!