jar*_*ack 0 unix bash terminal awk sed
我想创建一个脚本来注释掉包含我的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
Run Code Online (Sandbox Code Playgroud)
会成为:
#127.0.0.1 foo.com
#127.0.0.1 bar.com
127.0.0.1 baz
127.0.0.1 qux
Run Code Online (Sandbox Code Playgroud)
我环顾了谷歌和sed手册页,用bash和sed尝试了一些东西,但我还没有接近.
sed 's/^/^#/' | grep '.com' < hosts
grep '.com' | sed 's/^/^#/' < hosts
感谢您的任何帮助!
sed '/\.com/s/^/#/' < hosts
Run Code Online (Sandbox Code Playgroud)
解释:
/\.com/
- 仅在与此正则表达式匹配的行上执行其余命令s/^/#/
- 插入#
行的开头如果要替换原始文件,请使用sed -i
选项:
sed -i.bak '/\.com/s/^/#/' hosts
Run Code Online (Sandbox Code Playgroud)
这将重命名hosts
为hosts.bak
并hosts
使用更新的内容创建新的.
要撤消它,请使用:
sed -i.bak '/^#.*\.com/s/^#//' hosts
Run Code Online (Sandbox Code Playgroud)