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

In Linux, there are several ways to insert text at the beginning of a file. The most common and efficient method uses the sed command, which stands for stream editor. This command performs various operations like find, replace, insert, and delete on files without opening them in an editor.

Using the sed Command

The sed command can modify files in-place using the -i flag, making it perfect for inserting text at the beginning of files. Let's explore this with a practical example.

Example Setup

Consider a directory d1 containing text files. First, let's check the directory contents:

$ ls -ltr
total 8280
-rwxrwxrwx 1 user staff 4234901 Jul  7 17:41 file.txt
-rw-r--r-- 1 user staff     105 Jul 16 09:30 somefile.txt

Let's examine the current contents of somefile.txt:

$ 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

sed Command Syntax

The basic syntax for inserting text at the beginning of a file varies slightly between different Linux distributions:

For Ubuntu/Fedora/Most Linux Distributions

sed -i '1s/^/Text to insert<br>/' filename

For macOS

sed -i "" '1s/^/Text to insert<br>/' filename

Practical Example

Now let's insert the text "Is this text added" at the beginning of somefile.txt:

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

After running the command, let's verify the changes:

$ 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

Breaking Down the Command

Component Purpose
sed Stream editor command
-i Edit file in-place (modify original file)
1s Apply substitution to line 1 only
^ Match beginning of line

Insert newline character

Alternative Methods

Besides sed, you can also use other commands like echo with redirection or the printf command combined with file concatenation for the same purpose.

Using echo and cat

echo "Text to insert" | cat - somefile.txt > temp && mv temp somefile.txt

Conclusion

The sed command provides a powerful and efficient way to insert text at the beginning of files in Linux. Understanding the syntax differences between distributions ensures compatibility across different systems. This method is particularly useful in shell scripts and automated workflows where file modification is required.

Updated on: 2026-03-17T09:01:38+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements