insert text at beginning of file in linux

How to Insert Text to Beginning of File in Linux

Linux provides tons of tools to work with files and texts. Sometimes you may need to add one or more lines to the beginning of a file in Linux. There are several ways to do this. In this article, we will learn how to insert text to beginning of file in Linux. We will sed command for this purpose, since it provides many out-of-the-box options for it.


How to Insert Text to Beginning of File in Linux

sed command stands for stream editor and is useful to perform many functions to search, replace, insert and delete strings in files.

Let us say you want to add some text to the beginning of file named data.txt at /home/ubuntu/. Then here is the sed command to do this. Replace <added text> with the text you want to add to the beginning of your file.

$ sed -i '1s/^/<added text> /' /home/ubuntu/data.txt

In the above command, -i option will edit the file in place, without sending the output back to command line. While using sed, if we redirect the output back to original file, it produces a blank file. So we need to use -i in this case.

The part within single quotes consists of 3 parts as shown

'<line address>/<string to be replaced>/<new string>'

In the above command, we use 1s to indicate the first line of file. You can read more about line addressing in Linux here. Next, we use ^ to indicate the start of the line. <added text> is the text to be added.

If you want to add a newline at the end of inserted text, just add \n at the end of your added text in the above command.

$ sed -i '1s/^/<added text> \n/' /home/ubuntu/data.txt


How to Add Multiple Lines

If you want to add multiple lines, say first 10 lines, replace 1s in our command above with 1,10s to specify lines 1-10.

$ sed -i '1,10s/^/<added text> /' /home/ubuntu/data.txt

In this article, we have learnt how to add text at the beginning of the file. You can use these commands in your shell script to automate this process, or even create a cronjob from it, if you want to run the command regularly.

Also read:

How to Get My Public SSH Key
How to Revoke SSH Access & Keys in Linux
How to Create Man Page for Script, Package, Module
How to Keep SSH Session Alive After Disconnect
How to Limit CPU Usage Per User in Linux

Leave a Reply

Your email address will not be published. Required fields are marked *