Bash: How to Replace Specific Line in File (With Example)


You can use the following syntax to replace a specific line in a file using Bash:

sed -i '4s/.*/new text/' some_file.txt

This particular example will replace line 4 in the file named some_file.txt with new text.

Note that the -i operator specifies that the line should be replaced in the file in-place.

If you’d like, you could use the following syntax to instead replace the line in the file and save the results to a new file:

sed '4s/.*/new text/' original_file.txt > new_file.txt

The following example shows how to replace a specific line in a file in practice.

Example: How to Replace Specific Line in File Using Bash

Suppose that we have a file saved in the following location on our computer:

  • c:/users/bobbi/city_names.txt

The file contains the names of various U.S. cities:

Suppose that we would like to replace the city name in line 4 (Houston) with a new city name of San Francisco.

We can use the following syntax to do so:

sed -i '4s/.*/San Francisco/' c:/users/bobbi/city_names.txt

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

Bash replace specific line in file

If we navigate to where the file is saved on our computer, we can view the updated contents of the file:

We can see that the city name Houston on line 4 has been replaced with San Francisco, just as we specified.

All other lines in the file have remained untouched.

Note: To replace a different specific line in the file, simply change 4 in the code to a different number.

Related Tutorials

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

Bash: How to Replace Text in String
Bash: How to Replace Special Characters in String
Bash: How to Replace Multiple Characters in String

Leave a Reply