« Back to Data processing: Frequently Asked Questions

How to insert a line at the beginning of a file

How to insert a line at the beginning of a file?

Use the sed command and let it perform an inline replacement.

sed -i '1i # New first line' FILE

To insert a line at the beginning of a file, we can use sed to achieve this task. By using in-place editing -i, we can instruct sed to make a change to an existing file. The next step is to tell sed what to change or insert and at what place.

sed -i '1i # New first line' mytextfile.txt

Explanation

  • -i = inline file edit
  • 1i = insert at first line
  • # New first line = Text to add

Other questions related to Data processing

    Related articles

    Like to learn more? Here is a list of articles within the same category or having similar tags.

    Feedback

    Small picture of Michael Boelen

    This article has been written by our Linux security expert Michael Boelen. With focus on creating high-quality articles and relevant examples, he wants to improve the field of Linux security. No more web full of copy-pasted blog posts.

    Discovered outdated information or have a question? Share your thoughts. Thanks for your contribution!

    Mastodon icon