There two steps, first check if exist the host in the file
If have the file:
# FILE: /etc/hosts:
192.168.0.10 srv-db srv-db-home
192.168.0.15 srv-db1
192.168.0.20 srv-db-2
192.168.0.20 srv-db-work srv-db-
Would execute:
sed -n -e '/\<srv-db\>/p' /etc/hosts
Which results to:
192.168.0.10 srv-db
192.168.0.20 srv-db-2
192.168.0.20 srv-db-
It ignores the number at the end just fine... but it does not ignore the dash (-).
I have found a bunch of regex that works parcially... as these two below:
and
How to match exact string using `sed`? But not the part of it.?
The answer below from @steeldriver helped with that:
awk '$NF == "srv-db"' /etc/hosts
But, when going to update the IP Address, it becames fuzzy, here is the full code I have camed up with:
sed -i -e "s/\(^ *[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\)\(\s*\)\<srv-db\>/192.168.9.9\2/" /etc/hosts
It should update only the first line, but instead it updates the same results as of above.
But none of them has worked perfectly is this particular case.