-1

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

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

Count
  • 1,395
  • 2
  • 19
  • 40

1 Answers1

2

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

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.

Hope that it helps!

Allan
  • 12,117
  • 3
  • 27
  • 51
  • 2
    Like maybe using `sed -i.bak "s/$oldIP/$newIP/g" /etc/hosts` ?? – David C. Rankin Nov 10 '17 at 08:02
  • Thanks for the answer ,this works .can you also tell advantage of changing the regex. – Count Nov 10 '17 at 08:12
  • 1
    The regex is more compact. less writing/less reading for the same behavior -> gain in productivity, and better for your fingers, eyes . :-) In term of performances, I don't know if using `\d` is better but the regex string will be smaller (little gain in memory consumption) – Allan Nov 10 '17 at 08:23
  • Thanks for the explanation – Count Nov 13 '17 at 16:23