Substitution on range of lines

后端 未结 4 2026
独厮守ぢ
独厮守ぢ 2021-01-26 16:58

I have in 3rd line of a file. I want to replace that with my_dB. How to do this with sed

相关标签:
4条回答
  • 2021-01-26 17:21

    To replace all instances of <host></host> with <host>my_dB</host> in your file, run:

    sed 's|<host></host>|<host>my_dB</host>|g' file
    
    0 讨论(0)
  • 2021-01-26 17:29

    Each can be done with something similar to this:

    sed -i "s/<host><\/host>/<host>my_db<\/host>/" foo.txt
    

    The -i means that it'll overwrite the file in-place. Remove that flag to have the changes written to stdout.

    If this is for a regular task to fill in details for the file, consider adding anchors to the file to make it easier. For example:

    <host>DB_HOST</host>
    

    Then the sed would just need to be:

    sed -i 's/DB_HOST/my_db/'
    
    0 讨论(0)
  • 2021-01-26 17:31

    Like this:

    $ sed '3,6 s/<host>/<host>my_dB/' file
    

    Demo:

    $ cat file
    1: <host></host>
    2: <host></host>
    3: <host></host>
    4: <host></host>
    5: <host></host>
    6: <host></host>
    7: <host></host>
    
    $ sed '3,6 s/<host>/<host>my_dB/' file
    1: <host></host>
    2: <host></host>
    3: <host>my_dB</host>
    4: <host>my_dB</host>
    5: <host>my_dB</host>
    6: <host>my_dB</host>
    

        7:

    To store the changes back to the file use the -i option

    $ sed -i '3,6 s/<host>/<host>my_bd/' file
    

    However you really should be using a XML parser. Getting into parsing XML with regexp is really a bad idea.

    0 讨论(0)
  • 2021-01-26 17:37

    try this:

     sed -r '3,5s#(<host>)(</host>)#\1my_dB\2#' file
    
    0 讨论(0)
提交回复
热议问题