Bash: How to Insert Text at the Beginning of File


Often you may want to use Bash to insert text at the beginning of a particular file.

You can use the following syntax with sed to do so:

sed -i '1iCharlotte Hornets' teams.txt

This particular example will insert the text ‘Charlotte Hornets’ at the beginning of the file named teams.txt.

Note that we use the –i flag to modify the file in-place and we use 1i to specify that we’d like to insert new text into line 1 of the file.

Note that you could also use the > command to insert text at the beginning of the file and save the results to a new file instead:

sed '1iCharlotte Hornets' teams.txt > teams_new.txt

This particular example will insert the text ‘Charlotte Hornets’ at the beginning of the file named teams.txt and save the results to a new file named teams_new.txt.

The following example shows how to use this syntax in practice.

Example: How to Use Bash to Insert Text at Beginning of File

Suppose that we have a file in our current directory named teams.txt that contains the names of various basketball teams.

We can use the cat command to view the contents of this file:

We can use the following syntax to insert the text ‘Charlotte Hornets’ at the beginning of this file:

sed -i '1iCharlotte Hornets' teams.txt

The following screenshot shows how to use this syntax in practice:

Bash insert text at beginning of file

Notice that when we use the cat command again to view the contents of the file we can see that the text ‘Charlotte Hornets’ has been added at the beginning of the file.

All other lines in the file have remained unchanged.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to List All Files in Folder by Size
Bash: How to List All Files in Folder Without Extension
Bash: How to List All Files Matching a Specific Pattern

Leave a Reply