How to insert a text at the beginning of a file in Linux?


In order to insert text at the beginning of a text file we must be familiar with either the sed command as the sed commands can be used to solve the above problem.

Let’s first explore the sed command, which is short for stream editor. This command is used to perform different functions like find, replace, insert and many more on a particular file.

Consider we have a directory d1 in which two .txt files are present and the directory looks something like this −

immukul@192 d1 % ls -ltr
total 8280
-rwxrwxrwx 1 immukul staff 4234901 Jul  7 17:41     file.txt
-rw-r--r-- 1 immukul staff     105 Jul 16 09:30 somefile.txt

Now we want to change the contents of the file named somefile.txt and insert some text of our choice at the first line of the .txt file.

The contents of the somefile.txt before inserting anything in the file looks something like this

immukul@192 d1 % cat somefile.txt
this file contains
a new text stream
and i am going to edit
that stream
yes i can do that
ask jeffrey

Now in order to add some text to the first line we will make use of the command shown below

Command

For Mac OS

sed -i "" '1s/^/Is this text added
/' somefile.txt

For Ubuntu/Fedora

sed -i '1s/^/Is this text added
/' somefile.txt

Output

immukul@192 d1 % cat somefile.txt
Is this text added
this file contains
a new text stream
and i am going to edit
that stream
yes i can do that
ask jeffrey

Updated on: 30-Jul-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements