How to Use sed to Replace All Backslashes with Forward Slashes


Often you may want to use sed to replace all backslashes with forward slashes in a particular file.

You can use the following syntax to do so:

sed 's.\\./.g' team_paths.txt

This particular example replaces all backslashes with forward slashes in the file named team_paths.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 period ( . ) instead, but you can choose any character that you would like.

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

Example: Use sed to Replace All Backslashes with Forward Slashes

Suppose that we have a file named team_paths.txt that contains the names of teams that various basketball players have played in which each team name is separated by a backslash.

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

Suppose that we would like to replace all backslashes with forward slashes in the file.

We can use the following syntax to do so:

sed 's.\\./.g' team_paths.txt

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

sed replace backslashes with forward slashes

Notice that all backslashes have been replaced with forward slashes instead.

Note that we could also use the -i flag if we would like to save these changes to the file in-place:

sed -i 's.\\./.g' team_paths.txt

This would replace all backslashes with forward slashes in the file named team_paths.txt and save the changes to the file in-place.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text Before Match

Leave a Reply