简体   繁体   English

bash脚本将ip地址插入属性文件

[英]bash script to insert ip address into property file

I have a property file with an entry such as this: 我有一个属性文件,其中包含这样的条目:

some.url={ipaddress}/blah

I want to substitute the {ipaddress} with the ip of machine its running on. 我想用运行它的机器的IP代替{ipaddress}。

I found this command: 我发现此命令:

ipconfig getifaddr en0

which outputs the ip. 输出ip。

I also found sed is useful for this sort of thing but I can't quite put it all together. 我还发现sed对于这种事情很有用,但我不能完全将其组合在一起。

sed -i '' 's/{ipaddress}/192.168.0.1/g' test.properties

Where the hard-coded ip address 192.168.0.1 needs to be substituted for the machine's one. 硬编码的IP地址192.168.0.1需要替换机器的IP地址。

Can anyone help? 有人可以帮忙吗?

You can store the result of the ipconfig command in a variable like this: 您可以将ipconfig命令的结果存储在这样的变量中:

ip=$(ipconfig getifaddr en0)

Then interpolate it into your sed command by surrounding the expression with double-quotes: 然后通过用双引号将表达式引起来将其插入到sed命令中:

sed -i "" "s/{ipaddress}/$ip/g" test.properties

Try this: 尝试这个:

cat file
some.url=10.10.10.5/blah

awk -F"=|/" '{print $1 "=" ip "/" $3}' ip=$(ip route get 8.8.8.8 | awk '{print $NF;exit}') file
some.url=192.168.1.30/blah

ip route get 8.8.8.8 | awk '{print $NF;exit}' ip route get 8.8.8.8 | awk '{print $NF;exit}' is one of the best way I have found to get correct IP. ip route get 8.8.8.8 | awk '{print $NF;exit}'是我发现获得正确IP的最好方法之一。 It works even on VPS servers and on servers with multiple IP 它甚至可以在VPS服务器和具有多个IP的服务器上运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM