Adding Text to First and Last Line of File in Linux

Hi everyone,

Let’s assume that you have many files to that you wanted to add some text to the first line or end line.

If you are a Linux user, this is easy to do. I am using sed and tee commands to add something to the file.

Firstly, I would like to show you how to add some text to the first line of the file. For this purpose, I am going to use the sed command.

Before beginning, I created a file that has some text like the one below This is our sample file.

sample-file

If you would like to add a test to the first line of your file, you can use the sed command like below. The below command will insert the text in the first line, which is defined 1i .

sed -i '1i this-text-will-be-adding-to-the-first-line' test-file.txt

You can also add the text that you need to more than one file by just changing the file name to the pattern you need. Let’s assume that you have some files that name is test1.txt - test2.txt, test3.txt . You just change test* .

sed -i '1i this-text-will-be-adding-to-the-first-line' test-file.txt

append to the first line

tee command will help you more about adding to the end of the line of your files that you would like to change.

echo 'this-text-will-be-adding-to-the-end-of-the-file' | tee -a test-file.txt

You can also add test to more than one file with that command, just you need to change the file name like the pattern you need. Let’s assume that you have some files that name is test1.txt - test2.txt, test3.txt . You just change test* .

echo 'this-text-will-be-adding-to-the-end-of-the-file' | tee -a test*

append to the end line

If you are working on many files, these commands help you to do something easily and fastly. For more information about the commands that I used, please use man sed and man tee .

I hope you enjoy while reading.