How to use sed to insert a block of lines from an external file into the second-to-last line of file

2012 October 2
by Colin

Let’s say you have file #1 that says…

Line 1
Line 2
Line 3

ENDFILEFLAG

You have file #2 that is:

Line 4
Line 5
Line 6

Using this sed command first goes through file1 and sets a MARKER by replacing the line right before the ENDFILEFLAG. The second pass (after the pipe) adds the contents of file2 into file1 at the MARKER, deletes the MARKER and outputs it as a newfile.txt

sed '/ENDFILEFLAG/i MARKER' file1 | sed -e '/MARKER/r file2' -e '/MARKER/d' > newfile.txt

Find this page useful? Save you a few dollars fixing something?
If you so desire, feel free to kick back a dollar or two to help site upkeep.

2 Responses leave one →
  1. 2015 July 12

    May I just say what a relief to uncover someone that genuinely knows what they’re
    talking about on the web. You definitely understand how to bring
    a problem to light and make it important. More
    and more people have to read this and understand this side
    of the story. I was surprised that you aren’t more popular since you most certainly have the gift.

  2. 2017 August 27

    Thanks for evеry other wonderful article. Where else may anybody get that type оf information in such a perfect way of writing?
    I have a presentation next week, and I am at the looҝ foor such information.

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS