Quickzi: How To Add a Line into the middle of a Text File

Here is a quick tip on how to use sed to add a line into the middle of a text file from the command line, without opening it.

To clarify, let’s say you have a text file that has four lines:


Using sed, you can append a line anywhere you want with a simple command without even knowing the line numbers.

Add a Line into the Middle of a Text File

For this example, lets say we want to append a new line under Line3Text:

# sed '/^Line3Text/a NewLineText' textFile > newFile

You’ll notice that we output the results to a newFile so that we can make sure the new line appended correctly before overwriting the original file.  If you check the newFile, you should see a correct output, then you can overwrite the original textFile.

# mv newFile textFile

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>