prePEND文件的某些行 [英] Prepend certain lines of file

查看:79
本文介绍了prePEND文件的某些行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个脚本来注释掉包含 .COM 我的Mac OS X主机文件的行。而且一个扭转它。

所以这个:

  127.0.0.1 foo.com
127.0.0.1 bar.com
127.0.0.1巴兹
127.0.0.1 qux

将变成:

 #127.0.0.1 foo.com
#127.0.0.1 bar.com
127.0.0.1巴兹
127.0.0.1 qux

我看了看周围的谷歌和sed的手册页,并试图使用bash和sed的几件事,但我还没有接近。

SED的/ ^ / ^#/'| grep的.com之间<主机

grep的.com之间| SED的/ ^ / ^#/'<主机

感谢您的帮助!


解决方案

 桑达'/\\.com/s/^/#/'<主机

国米pretation:


  • / \\ COM / - 只有匹配这个正则表达式的行执行的命令的其余部分

  • S / ^ /#/ - 插入在该行的开头

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

  SED -i.bak'/\\.com/s/^/#/'主机

这将重新命名主机有hosts.bak ,并创建一个新的主机与更新的内容。

要取消它,使用:

  SED -i.bak'/^#.*\\.com/s/^#//'主机

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!

解决方案

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

这篇关于prePEND文件的某些行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆