Bash: How to Replace Line in File By Line Number


Often you may want to use Bash to replace a line in a file based on line number.

The easiest way to do so is by using sed with the following syntax:

sed -i '2 cBoston Celtics' teams.txt

This particular example will replace the text in line number 2 of the file named teams.txt with the text “Boston Celtics” instead.

Here is what the various commands do:

  • -i: Specifies that the file should be modified in-place
  • 2: Specifies the line number to match in the file
  • c: Specifies that the line should be changed to the text following the c

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

Example: How to Replace Line in File Based on Line Number in Bash

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

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

Suppose that we would like to change the text on line number 2 of the file to be “Boston Celtics” instead.

We can use the following syntax to do so:

sed -i '2 cBoston Celtics' teams.txt

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

Bash replace line in file based on line number

Notice that when we use the cat command to view the updated contents of the file we can see that line number 2 now contains the text “Boston Celtics”, just as we specified.

All other lines in the file have remained unchanged.

Feel free to replace 2 with the specific line number that you would like to replace in your own file.

Related Tutorials

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

Bash: How to Find Duplicate Lines in File
Bash: How to Delete All Empty Lines in File
Bash: How to Count Number of Unique Lines in File

Leave a Reply