There two steps, first check if exist the host in the fileIf have the file:# FILE: /etc/hosts:192.168.0.10 srv-db srv-db-home192.168.0.15 srv-db1192.168.0.20 srv-db-2192.168.0.20 srv-db-work srv-db-Would execute:sed -n -e '/\<srv-db\>/p' /etc/hostsWhich results to:192.168.0.10 srv-db192.168.0.20 srv-db-2192.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:Match exact string using grepand 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/hostsBut, 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/hostsIt 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.
Match EXACT string in file and update IP Address
sed;scripting;ip
The \> word boundary anchor treats - as a boundary.If you know that there is no trailing whitespace, you could anchor to the end of line /\<srv-db$/ - to allow for trailing whitespace you could modify that to /\<srv-db[[:blank:]]*$/ or /\<srv-db[[:space:]]*$/Or use awk and do a string match instead:awk '$NF == srv-db' /etc/hostsIf you can't necessarily anchor to the end of line (even with trailing whitespace) then you will beed to construct an expression that (for example) tests for whitespace or end of line (i.e. word boundary without hyphen) e.g. (using extended regular expression mode)sed -En -e '/\<srv-db(\s|$)/p'If you can use perl (or grep in PCRE mode) then there are possibly more elegant options such asperl -ne 'print if /\bsrv-db(?![\w-])/'orgrep -P '\bsrv-db(?![\w-])'