Skip to content

Adding a Line in Middle of File using Linux command

Advertisement

Sometimes we need to insert a line at middle of the existing file. You can add line at specific line number using Linux command line or shell scripts.

In this tutorial, we will discuss about adding a text line at middle of file as specific line number.

Let’s have an example, I have a text file named file1.txt with following content:

cat file1.txt 

this is line one
this is line two
this is line three

Now I have to insert text “HelloWorld” at the line number 3. To do this run the following command.

sed -i '3iHelloWorld' file1.txt 

Details of Parameters:

  • sed: is the command itself.
  • -i: : Update content in same file.
  • 3: line number where new line will be inserted.
  • i: parameter, which told sed to insert line.
  • HelloWorld: text to be added.
  • file1.txt: is the file in which new line need to add.

Above command will insert the content in file1.txt at line number 3. Let’s check the content of the file:

cat file1.txt 

this is line one
this is line two
HelloWorld
this is line three

Rahul

I, Rahul Kumar am the founder and chief editor of TecAdmin.net. I am a Red Hat Certified Engineer (RHCE) and working as an IT professional since 2009..

1 Comment

  1. You also can use -i modifier to edit the file itself without creating an intermediate file

    $ sed -i ‘3itecadmin 3’ file1.txt

    Moreover, if you are not sure about the changes that will be made, add a suffix to the -i flag that will make a backup of the original file

    $ sed -i.bak ‘3itecadmin 3’ file1.txt

Leave a Reply

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


Back to top