Prepend certain lines of file

后端 未结 2 1689
长情又很酷
长情又很酷 2021-01-29 03:15

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.         


        
相关标签:
2条回答
  • 2021-01-29 03:39
    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
    
    0 讨论(0)
  • 2021-01-29 03:42

    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
    
    0 讨论(0)
提交回复
热议问题