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

后端 未结 3 1870
别那么骄傲
别那么骄傲 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 05:02

    sed is for s/old/new/, that is all. For anything else you should be using awk:

    $ awk 'NR==FNR{new = new $0 ORS; next} /gray/{f=0} !f{print} /blue/{printf "%s",new; f=1}' new.txt original.txt
    red
    blue
    green
    black
    yellow
    purple
    gray
    white
    

    The above will work in any awk in any shell on any UNIX box and does not require any of the start/end regexps to be repeated. Very importantly it can also trivially be built upon to do anything else you want now or in future! For example to be able to specify the beginning and ending regexps as arguments would be:

    $ awk -v beg='blue' -v end='gray' 'NR==FNR{new = new $0 ORS; next} $0~end{f=0} !f{print} $0~beg{printf "%s",new; f=1}' new.txt original.txt
    

    ad then you can change them:

    $ awk -v beg='water' -v end='tree' 'NR==FNR{new = new $0 ORS; next} $0~end{f=0} !f{print} $0~beg{printf "%s",new; f=1}' new.txt original.txt
    red
    blue
    water
    green
    black
    yellow
    purple
    tree
    gray
    white
    

    Anything you might want to do is just a simple rearrangement using the same constructs, e.g. to not print the beginning line:

    $ awk -v beg='blue' -v end='gray' 'NR==FNR{new = new $0 ORS; next} $0~end{f=0} $0~beg{printf "%s",new; f=1} !f{print}' new.txt original.txt
    red
    green
    black
    yellow
    purple
    gray
    white
    

    and similar tweaks to not print the ending line or not print both or do anything else....

提交回复
热议问题