Insert Text at Beginning of File in Linux

Insert Text at Beginning of File in Linux

Linux provides various commands to process the text files. Sometimes we may need to insert a text at the beginning of a file. This tutorial shows how to do this in Linux.

Create a new file for testing:

printf "Line2\nLine3\nLine4\n" > test.txt

Text files can be processed with sed command. Execute the following command to insert a text at the beginning of a file:

sed -i "1s/^/Line1\n/" test.txt

The -i option will edit file in-place. The 1s indicates the first line of file. The ^ means the beginning of the line.

Leave a Comment

Cancel reply

Your email address will not be published.