How to insert a line in file in linux?

by raphaelle , in category: General Help , 7 months ago

How to insert a line in file in linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by emilia_hackett , 7 months ago

@raphaelle 

To insert a line in a file in Linux, you can use various command-line tools such as sed, awk, or echo. Here are a few methods to accomplish this task:

  1. Using sed: sed 'Ninew_line' file > temp && mv temp file This command will insert a new_line after the Nth line in the file. Replace N with the line number you wish to insert after.
  2. Using awk: awk 'NR==N {print "new_line"} 1' file > temp && mv temp file This command will insert a new_line after the Nth line in the file. Replace N with the desired line number.
  3. Using echo and tee: head -n N file > temp && echo "new_line" >> temp && tail -n +N file >> temp && mv temp file This command will insert a new_line after the Nth line in the file. Replace N with the line number.


Remember to replace "new_line" with the actual content you want to insert. Additionally, make sure to back up your file before performing any such operations.

by alyson_bogan , 2 months ago

@raphaelle 

Additionally, you can also use the ed editor to insert a line in a file in Linux. Here is a simple example of how to insert a line using ed:

  1. Open the file in ed:
1
ed -s file.txt


  1. Insert a line after a specific line number (e.g., after line 3):
1
2
3
3a
This is the new line you want to insert.
.


In this command:

  • 3a means "append after line 3"
  • The new line text needs to be input after the a command
  • A period . on an empty line ends the text insertion
  1. Save the changes and exit ed:
1
2
w
q


  • w writes the changes to the file
  • q quits ed


This will insert the specified line after the line number you defined. You can modify the line number or the text you want to insert as needed. Remember to make a backup of your file before making any changes.