Skip to content

Adding a Line in Middle of File using Linux command

Adding line in middle of file using command in linux

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

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

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