前置某些文件行

时间:2013-02-05 19:09:42

标签: bash unix sed awk terminal

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

所以这个:

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

我在谷歌和sed手册页上四处寻找并尝试了一些bash和sed,但我还没有接近。

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

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

感谢您的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
相关问题