How to Use sed to Insert Line at Specific Line Number


Often you may want to use sed to insert a line at a specific line number in a file.

You can use the following syntax to do so:

sed '4i D55John' employees.txt

This particular example inserts a line with the string D55John at line number 4 in the file named employees.txt.

If you would like to modify the file in-place then you can add the -i flag as follows:

sed -i '4i D55John' employees.txt

And if you would like to save the output to a new file, you can use the > command as follows:

sed '4i D55John' employees.txt > employees_out.txt

The following example shows how to use this syntax in practice.

Example: How to Use sed to Insert Line at Specific Line Number

Suppose we have a file named employees.txt that contains the ID numbers for various employees at some company:

We can use the following syntax to insert a new line in the file with the string D55John at line number 4:

sed '4i D55John' employees.txt

The following screenshot shows how to use this syntax in practice:

sed insert line at line number

Notice that a line with the string D55John has been inserted at line number 4 of the file.

If we would like to modify the file in-place then we can use the -i flag as follows:

sed -i '4i D55John' employees.txt

The following screenshot shows how to use this syntax in practice:

sed insert line at line number in-place

When we use the cat command to view the contents of employees.txt we can see that a line with the string D55John has been inserted at line number 4 of the file.

We could also use the following syntax to insert a new line at line number 4 and then save the results to a new file named employees_out.txt:

sed '4i D55John' employees.txt > employees_out.txt

The following screenshot shows how to use this syntax in practice:

sed insert line at line number and save results to new file

When we use the cat command to view the contents of employees_out.txt we can see that it contains all lines from the employees.txt file with a new line inserted at line number 4.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Insert a Line After Match
How to Use sed to Delete Specific Line Numbers from File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply