在文件中查找并用SED替换变量 [英] Find and replace variables with SED in a file

查看:403
本文介绍了在文件中查找并用SED替换变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在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=value1var_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

我要做的事情:

  1. 在随后的conf文件中找到$ var_1和$ {var_2}(使用通用正则表达式,我想我不知道conf文件中是否有变量)
  2. 使用 export -p搜索每个值grep var_1 export -p | grep var_2
  3. 用先前搜索找到的值替换conf文件中的这两个变量
  1. 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)
  2. Search value of each with export -p | grep var_1 and export -p | grep var_2
  3. 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屋!

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