How to Use sed to Replace First Line in a File


Often you may want to use sed to replace only the first line in a particular file.

You can use the following basic syntax to do so:

sed '1 s/^.*$/City Team Conf/' teams.txt

This particular example replaces the first line in the file named teams.txt with the text City Team Conf.

Here is what the various sed commands do:

  • 1: Match the first line of the file
  • s: Substitute one pattern for another pattern
  • ^.*$: Substitute everything from the start (^) to the end ($) of the line

Note that you can also use the -i flag if you would like to modify the file in-place:

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

Example: Use sed to Replace First Line in a File

Suppose that we have a file named teams.txt that contains information about various basketball teams:

Notice that the first line in the file contains the following text:

  • Location Name Conference

Suppose that we would like to replace this first line with the following text:

  • City Team Conf

We can use the following syntax to do so:

sed '1 s/^.*$/City Team Conf/' teams.txt

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

sed replace first line in file

Notice that the first line has been replaced with the exact text that we specified and all other lines in the file have remained the same.

Note: If you would like to modify the file in-place, then you can use the -i flag as follows:

sed -i '1 s/^.*$/City Team Conf/' teams.txt

This would replace the first line of the teams.txt file in-place.

Related Tutorials

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

How to Use sed to Replace All Text After Match
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace Last Occurrence of Character in String

Leave a Reply