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:

Line1Text
Line2Text
Line3Text
Line4Text

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

Popularity: 4% [?]

Tagged with:

Filed under: Linux

Like this post? Subscribe to my RSS feed and get loads more!