Linux (sed 初学者) 替换环境变量中的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11297610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:12:30  来源:igfitidea点击:

(sed beginner) replace characters in an env variable

linuxshellsed

提问by PapelPincel

How can I replace caracters "on the fly" when using sed ? Example :

使用 sed 时如何“即时”替换字符?例子 :

I want this command to be executed : /bin/sed 's/HOSTNAME=.*/HOSTNAME=server_domain_com/g' /etc/sysconfig/network

我希望执行此命令: /bin/sed 's/HOSTNAME=.*/HOSTNAME= server_domain_com/g' /etc/sysconfig/network

Instead of this one : /bin/sed 's/HOSTNAME=.*/HOSTNAME=server.domain.com/g' /etc/sysconfig/network

而不是这个: /bin/sed 's/HOSTNAME=.*/HOSTNAME= server.domain.com/g' /etc/sysconfig/network

the string "server.domain.com" is contained in a env variable and I would like to replace the dots by an underscore before replacing the appropriate line in /etc/sysconfig/network.

字符串“server.domain.com”包含在环境变量中,我想在替换 /etc/sysconfig/network 中的相应行之前用下划线替换点。

Thank you!

谢谢!

采纳答案by lynxlynxlynx

You can do this with bash substitution too:

你也可以用 bash 替换来做到这一点:

/bin/sed -i "s/HOSTNAME=.*/HOSTNAME=${HOSTNAME//./_}/g" /etc/sysconfig/network

The //instructs it to change all occurences (like g in sed). Do not forget the -iflag to actually change the file, not just print it.

//指示它改变所有出现(如克SED)。不要忘记-i实际更改文件的标志,而不仅仅是打印它。

回答by Igor Chubin

HOSTNAME=$(echo $HOSTNAME | sed s/from/to/g)