Replace text between two lines with contents of a file stored in a variable in sed

后端 未结 3 1967
别那么骄傲
别那么骄傲 2021-01-19 04:15

Let\'s say I have a file called original.txt with this content:

red
blue
water
food
tree

3条回答
  •  無奈伤痛
    2021-01-19 04:51

    I see you asked for sed help, but ex handles this use-case in a bit more straightforward way. This may work for you (in a shell script):

    ex original.txt << EOF_EX
    /blue/+1,/gray/-1 d
    r new.txt
    w edited.txt
    q!
    EOF_EX
    

    The above opens original.txt for editing, deletes the range of lines one past blue through one before gray, reads the file new.txt, and writes out file edited.txt.

    Result:

    $ cat edited.txt
    red
    blue
    gray
    green
    black
    yellow
    purple
    white
    

    Alternatively you could replace "w edited.txt" with "wq" and it would save the changes in the original.txt file.

    Also, notice the +1 and -1 syntax in the range, which can be very handy. For example if you had wanted to also remove the range-bounding patterns, "blue" and "gray" you could remove the +1 and -1 and it would mean delete the range, including the range-boundary patterns.

提交回复
热议问题