Home > Mobile >  Using Bash, how can I replace characters in this variable in one location, but not another?
Using Bash, how can I replace characters in this variable in one location, but not another?

Time:11-04

Here's an example of my bash script and the output I currently get:

bash.sh

echo "$INSTANCE_IP ip-$INSTANCE_IP.hostname.com" | tee -a /etc/hosts

Here's what get's added to my /etc/hosts file:

10.0.2.110 ip-10.0.2.110.hostname.com

I would like to replace the . characters with -, but only in the domain name portion. So when it first passes in my variable $INSTANCE_IP I need it to be the actual IP address so the .'s need to be included and the domain name needs to have my IP address but with - instead.

So here's my desired output in my /etc/hosts file

10.0.2.110 ip-10-0-2-110.hostname.com

CodePudding user response:

You can use substitution on 2nd instance of variable like this:

echo "$INSTANCE_IP ip-${INSTANCE_IP//./-}.hostname.com"
  •  Tags:  
  • bash
  • Related