How to Use sed to Insert Line at Top of File


Often you may want to use sed to insert a line at the top of a file.

You can use the following methods to do so:

Method 1: Insert New Line at Top of File

sed -i '1i City Names' cities.txt

This particular example inserts a new line at the top of the file named cities.txt with the text City Names.

Note that we use the -i flag to modify the file in-place and we use the command 1i to insert a new line into row number 1 of the file.

Method 2: Append New Text to Existing First Line of File

sed -i '1s/^/City Names /' cities.txt

This particular example appends the text City Names (with a space after it) to the existing first line of the file named cities.txt.

Note that we use the s command to “substitute” the start ( ^ ) of the first line of the file with the text City Names.

The following examples show how to use each method in practice with the following file named cities.txt that contains the names of various U.S. cities:

Example 1: Use sed to Insert New Line at Top of File

We can use the following syntax to insert a new line at the top of the file with the text City Names:

sed -i '1i City Names' cities.txt

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

sed insert line at top of file

Notice that a new line with the text City Names has been insert at the top of the file.

Example 2: Use sed to Append New Text to Existing First Line of File

We can use the following syntax to append the text City Names to the existing first line of the file:

sed -i '1s/^/City Names /' cities.txt

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

sed insert text to beginning of first line in file

Notice that the text City Names has been appended to the existing first line of the file.

Related Tutorials

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

How to Use sed to Insert a Line After Match
How to Use sed to Insert Empty Line in a File
How to Use sed to Insert Line with Leading Spaces
How to Use sed to Insert Line at Specific Line Number

Leave a Reply