How to insert a line in file in linux?

by raphaelle , in category: General Help , 24 days ago

How to insert a line in file in linux?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by emilia_hackett , 23 days 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.