Table of Contents
Let’s suppose we need to insert some data at a specific line of a large file. Because of its size, it’d take a lot of time to open it in an editor and add it manually. Also, it might be hard to scroll to the correct line.
In this post, we’ll see how to insert text at a specific line of a file using Linux commands. We’ll be looking at sed command that allow us to modify and manipulate text files.
Using sed to insert a line
The sed command is a powerful utility for editing files in Linux. It offers lots of operations on files. In this section, we’re going to insert text in the third line of file1.txt. Indeed, we’ll set the modification commands in the same line:
The content of the file before inserting a new line using sed command:
# cat file1.txt Line #1 Line #2 Line #3 Line #4
Run the following command to insert a line at the third line of the file:
In the single quotations, = the line number for insertion.
sed -i '3 i New Line with sed' file1.txt
As you can see that the new line was inserted successfully into the file1.txt.
# cat file1.txt Line #1 Line #2 New Line with sed Line #3 Line #4
Using sed to insert a line to a new file
If you don’t want to change the input file, you can use redirection to save the output to a new file. In this case, we don’t need to use the -i option:
sed '3 i New Line with sed' file1.txt > file2.txt
The source file file1.txt still remains, and the new line was inserted into a new file file2.txt.
# cat file1.txt Line #1 Line #2 Line #3 Line #4 # cat file2.txt Line #1 Line #2 New Line with sed Line #3 Line #4