0

我想创建一个脚本来注释掉我的 Mac OS X 主机文件中包含.com. 还有一个可以扭转它。

所以这:

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

会成为:

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

我在 Google 和 sed 手册页上环顾四周,并用 bash 和 sed 尝试了一些东西,但我还没有接近。

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

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

感谢您的任何帮助!

4

2 回答 2

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

解释:

  • /\.com/- 仅在与此正则表达式匹配的行上执行其余命令
  • s/^/#/ -#在行首插入

如果要替换原始文件,请使用 sed 的-i选项:

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

这将重命名hosts并使用更新的内容hosts.bak创建一个新的。hosts

要撤消它,请使用:

sed -i.bak '/^#.*\.com/s/^#//' hosts
于 2013-02-05T19:11:26.237 回答
0

用 awk

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

输出

#127.0.0.1    foo.com
#127.0.0.1    bar.com
127.0.0.1    baz
127.0.0.1    qux
于 2013-02-06T01:28:35.403 回答