0

I'd like to create a script to comment out lines of my Mac OS X hosts file that contain .com. And also one to reverse it.

So this:

127.0.0.1    foo.com
127.0.0.1    bar.com
127.0.0.1    baz
127.0.0.1    qux

would become:

#127.0.0.1   foo.com
#127.0.0.1   bar.com
127.0.0.1    baz
127.0.0.1    qux

I looked around on Google and the sed man page and tried a few things with bash and sed, but I haven't come close.

sed 's/^/^#/' | grep '.com' < hosts

grep '.com' | sed 's/^/^#/' < hosts

Thank you for any help!

jared_flack
  • 1,606
  • 2
  • 17
  • 24

2 Answers2

7
sed '/\.com/s/^/#/' < hosts

Interpretation:

  • /\.com/ - only perform the rest of the command on lines matching this regex
  • s/^/#/ - insert # at the beginning of the line

If you want to replace the original file, use sed's -i option:

sed -i.bak '/\.com/s/^/#/' hosts

This will rename hosts to hosts.bak and create a new hosts with the updated contents.

To undo it, use:

sed -i.bak '/^#.*\.com/s/^#//' hosts
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I think OP wants it to be saved onto a file cause if he wanted it at stdout he could have just added a `cat ` in front of his command and it would work – noMAD Feb 05 '13 at 19:22
  • @noMAD He used input redirection, which is the same thing. But I updated my answer to show how to replace with sed. – Barmar Feb 05 '13 at 19:25
0

With awk

awk '$2 ~ /.com/{$0 = "#"$0;}{print}' temp.txt

Output

#127.0.0.1    foo.com
#127.0.0.1    bar.com
127.0.0.1    baz
127.0.0.1    qux
Mirage
  • 30,868
  • 62
  • 166
  • 261