Remove Specific entries in etc/hosts

dpalmer_autoeve
New Contributor III

I have been looking around for some assistance on removing 2 lines from the hosts file. I would prefer a script as I need this done on 30+ MBP's, I did see a few scripts but the are adding entries not removing entries. Any help is appreciated.

4 REPLIES 4

mm2270
Legendary Contributor III

The hosts file isn't really made to be edited with a script, but I suppose it's possible to do. I would just be careful and test your process thoroughly before deploying it out to a lot of machines.

The command I would probably use for this is sed. But you have to direct sed to make changes directly to the file, because normally it takes a stream input and sends the changes to output, not back to a file. Directing sed to make edits directly to a file looks something like this:

/usr/bin/sed -i "" '/url_or_string_here/d' /etc/hosts

Replace the url_or_string_here with something that should be unique in the hosts file to locate the line to be deleted. If the string has any slashes in it, you'll need to either escape them or use some other divider with sed, since it uses / as the delimiter for what to look for and what action(s) to take by default.

As I said, I would be careful with this so as not to mess up the hosts file. Test it out a bunch on some machines that you can easily fix if something goes wrong.

LaMantia
New Contributor III

That worked like a charm for me. Thank You. 

JustinN
New Contributor III

I'm trying to do this now in Jamf School to a crontab file using a few variations of this.

if [ -e /etc/crontab ];then

  • usr/bin/sed -i "" '/words/d' /etc/crontab
  • sed -i "" '/words/d' /etc/crontab

fi

Am I missing some key text?

JustinN
New Contributor III

I thought I would be able to move it out of /etc/ to make changes, but I can't copy it back.