1

I have requirement where I want to delete a entry from /etc/hosts file matching a particular entry

For example

I want to delete an entry like below

192.168.1.1 test001 test001.test.test.com

How can I do this either using a single line command or a script.

oguz ismail
  • 1
  • 16
  • 47
  • 69

2 Answers2

0

This deletes the string from your hosts file

sed -i -e "/192.168.1.1 test001 test001.test.test.com/d" filename

You might need regular expressions to catch whitespace between the words which might be blanks or tabs:

sed -i -e "/192.168.1.1.*test001.*test001.test.test.com/d" filename
nullPointer
  • 4,419
  • 1
  • 15
  • 27
ennox
  • 206
  • 1
  • 5
  • 1
    `-i` is a non-standard, non-portable GNU extension to [the POSIX `sed` utility](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html) and potentially not available on Solaris. [GNU `sed` also does not do an actual in-place edit](https://stackoverflow.com/questions/12696125/sed-edit-file-in-place), instead creating a temporary file, then renaming that temporary file to the original file name, thus actually deleting the original file. Since `/etc/hosts` on Solaris is actually a link to `/etc/inet/hosts`, this answer will break that link. – Andrew Henle Nov 07 '19 at 17:24
  • Any other way we can achieve this – Yogesh Dalal Nov 08 '19 at 12:09
  • @YogeshDalal Use an `ed` script such as this: https://unix.stackexchange.com/a/493806/111943 – Andrew Henle Nov 08 '19 at 16:22
0

You can try something like:

grep -v "192.168.1.1 test001 test001.test.test.com" /etc/inet/hosts >/tmp/hosts
mv /tmp/hosts /etc/inet/hosts

The file and path differ because /etc/hosts in Solaris is softlink to /etc/inet/hosts

Romeo Ninov
  • 6,538
  • 1
  • 22
  • 31