Insert Text at Specific Line of File in Linux

Insert Text at Specific Line of File in Linux

Using text editor can be hard to insert text at specific line of a large file because need to scroll to the correct line. We can achieve the same result using the command. This tutorial shows how to do this in Linux.

Create a new file for testing:

printf "Line1\nLine2\nLine4\n" > test.txt

The sed command can be used for text files processing. To insert text at specific line of a file, use the ni modifier, where n is a line number. For example, the following command inserts text at line 3:

sed -i "3i Line3" test.txt

The -i option will edit file in-place.

Leave a Comment

Cancel reply

Your email address will not be published.