sed 命令不通过变量替换 ip 地址 [英] sed command not replacing ip address via variables

查看:180
本文介绍了sed 命令不通过变量替换 ip 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的开发环境设置要求我在/etc/host 文件中有特定的主机名到 localIP 条目.(原因是多个微服务和存储,即 Cassandra 和 Redis 绑定到主机名)我已经创建了这个简单的 bash 脚本

My development environment setup is such that it requires me to have certain host-name to localIP entry in /etc/host file .( Reason being multiple micro-services and storage i.e Cassandra and Redis bound to host-name ) I have created this simple bash script

newIP=`ip a | grep wlp5s0 | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | head -1`
echo $newIP
oldIP=`ping -q -c 1 -t 1 dummy | grep PING | sed -e "s/).*//" | sed -e "s/.*(//"`
echo $oldIP
sed -i 's/$oldIP/$newIP/g' /etc/hosts

虽然这打印了正确的 ip,但没有发生替换, 在我看来是 sed 的问题,但不确定

Althrough this is printing correct ip but the replacement is not happening , looks to me as an issue with sed but not sure

推荐答案

您应该按以下方式更改您的 sed 命令:

You should changed your sed command in the following way:

sed -i "s/$oldIP/$newIP/g" /etc/hosts

如果您使用简单的引号 " ' " 您的变量将不会被其值替换!

if you use simple quotes " ' " your variable will not be replaced by its value!

您还可以通过以下方式编辑您的第一个正则表达式:

You can also edit your first regex in the following way:

\b(\d{1,3}\.){3}\d{1,3}\b

最后但并非最不重要的一点是,在就地模式下使用 sed 之前,您应该备份 /etc/hosts 文件,以避免出现意外.

Last but not least, you should take a backup of your /etc/hosts file before using sed in in-place mode, to avoid bad surprises.

希望能帮到你!

这篇关于sed 命令不通过变量替换 ip 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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