How to Use sed to Replace Path with Another Path


Often you may want to use sed to replace one path in a file with another path.

You can use the following syntax to do so:

sed 's|c/users/bobbi/data1|c/users/bobbi/data2|g' team_info.txt

This particular example replaces the file path c/users/bobbi/data1 with the new path of c/users/bobbi/data2 within the file named team_info.txt.

Note that the s command in sed is used to “substitute” one pattern for another pattern and typically uses the following syntax:

  • s/old_pattern/new_pattern/flags

However, the / characters are allowed to be uniformly replaced by any other single character.

When replacing file paths, we can simply use a character that is different than a slash.

In our particular example we chose to use a pipe ( | ) character instead, but you can choose any character that you would like.

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

Example: How to Use sed to Replace Path with Another Path

Suppose that we have a file named team_info.txt that contains information about file names for some basketball team.

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

Notice that the first line of the file contains the path c/users/bobbi/data1.

Suppose that we would like to change this file path to c/users/bobbi/data2 instead.

We can use the following syntax to do so:

sed 's|c/users/bobbi/data1|c/users/bobbi/data2|g' team_info.txt

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

sed replace path with another path

Notice that the path in the first line of the file has been replaced with the new path that we specified.

Note that if you would like to save these changes to the file in-place then you can add the -i flag as follows:

sed -i 's|c/users/bobbi/data1|c/users/bobbi/data2|g' team_info.txt

This will save the changes to the team_info.txt file in-place.

Related Tutorials

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

How to Use sed to Replace Tab Characters
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 Entire Line that Contains Pattern

Leave a Reply