bash 在 sed 替换中使用 $HOSTNAME
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24168129/
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
Use $HOSTNAME in sed substitution
提问by stephenmurdoch
I want to use my Centos VM's $HOSTNAME inside a call to sed
like so:
我想在调用中使用我的 Centos VM 的 $HOSTNAMEsed
像这样:
sed -i 's/Apache 2 Test Page/$HOSTNAME Test Page/g' /var/www/error/noindex.html
But this just replaces Apache 2 Test Page
with $HOSTNAME Test Page
... I know I can do it manually, but I've got a good reason for wishing to do it this way.
但这只是替换Apache 2 Test Page
为$HOSTNAME Test Page
......我知道我可以手动完成,但我有充分的理由希望这样做。
FWIW, I'm actually doing this inside a bash script that gets called from a Vagrantfile, which in turn provisions multiple VM's (each with Apache2 installed), so that I can test-out the load-balancing capabilities of HAProxy. so I just want a simple way to differentiate between my 3 web-servers, and II figure that modifying the default Apache page is the easiest way to do that.
FWIW,我实际上是在从 Vagrantfile 调用的 bash 脚本中执行此操作,该脚本又提供多个 VM(每个都安装了 Apache2),以便我可以测试 HAProxy 的负载平衡功能。所以我只想要一种简单的方法来区分我的 3 个网络服务器,并且我认为修改默认的 Apache 页面是最简单的方法。
回答by Avinash Raj
Enclose sed
's s///
with double quotes instead of single quotes for variable expansion.
用双引号代替单引号将sed
'ss///
括起来以进行变量扩展。
sed -i "s/Apache 2 Test Page/$HOSTNAME Test Page/g" /var/www/error/noindex.html
Example:
例子:
$ echo 'foo Apache 2 Test Page bar' | sed "s/Apache 2 Test Page/$HOSTNAME Test Page/g"
foo avinash-Lenovo-IdeaPad-Z500 Test Page bar