• Home
  • Ubuntu 20.04
    • Upgrade Ubuntu
    • Install Java
    • Install Node.js
    • Install Docker
    • Install LAMP Stack
  • Tutorials
    • AWS
    • Shell Scripting
    • Docker
    • Git
    • MongoDB
  • Funny Tools
  • FeedBack
  • Submit Article
  • About Us
TecAdmin
Menu
  • Home
  • Ubuntu 20.04
    • Upgrade Ubuntu
    • Install Java
    • Install Node.js
    • Install Docker
    • Install LAMP Stack
  • Tutorials
    • AWS
    • Shell Scripting
    • Docker
    • Git
    • MongoDB
  • Funny Tools
  • FeedBack
  • Submit Article
  • About Us

Adding line in middle of file using command in linux

Written by Rahul, Updated on March 1, 2013

Hi Guys,

If you want to add a line in file at specific line number through script. Below examples will help you to do it.

For example you have a file named file1.txt, file content are as below.

[email protected]:~ # cat file1.txt
tecadmin 1
tecadmin 2
tecadmin 4

Now you required to add text “tecadmin 3” at line number 3, use below command

[email protected]:~ # sed '3itecadmin 3' file1.txt > file1.txt.tmp

Above command will create a new file file1.txt.tmp with expected output

[email protected]:~ # cat file1.txt.tmp
tecadmin 1
tecadmin 2
tecadmin 3
tecadmin 4

Replace origin file with tmp file

[email protected]:~ # cp file1.txt.tmp file1.txt

Details of the `sed` command:

sed: is the command itself.
2: line number where new line will be inserted.
i: parameter, which told sed to insert line.
tecadmin 2: text to be added.
file1.txt: is the file in which new line need to add.
file1.txt.tmp: New file with updated content.

Share it!
Share on Facebook
Share on Twitter
Share on LinkedIn
Share on Reddit
Share on Tumblr
Share on Whatsapp
Rahul
Rahul
Connect on Facebook Connect on Twitter

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. Avatar Javier Reply
    October 20, 2015 at 8:44 am

    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 Cancel reply

Popular Posts

  • How To Install Python 3.9 on Debian 10
  • Download Ubuntu 20.04 LTS – DVD ISO Images
  • Linux Run Commands As Another User
  • How to Check PHP Version (Apache/Nginx/CLI)
  • How To Install and Configure GitLab on Ubuntu 20.04
  • How to Install PyCharm on Ubuntu 20.04
  • How to Check Ubuntu Version with Command or Script
  • How to Set all directories to 755 And all files to 644
© 2013-2021 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy