Use sed to replace all backslashes with forward slashes
Solution 1
sed can perform text transformations on input stream from a file or from a pipeline. Example:
echo 'C:\foo\bar.xml' | sed 's/\\/\//g'
gets
C:/foo/bar.xml
Solution 2
for just translating one char into another throughout a string, tr is the best tool:
tr '\\' '/'
Solution 3
Just use:
sed 's.\\./.g'
There's no reason to use / as the separator in sed. But if you really wanted to:
sed 's/\\/\//g'
Solution 4
If your text is in a Bash variable, then Parameter Substitution ${var//\\//} can replace substrings:
$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
C:\foo\bar.xml
$ printf '%s\n' "${p//\\//}"
C:/foo/bar.xml
This may be leaner and clearer that filtering through a command such as tr or sed.
Solution 5
$ echo "C:\Windows\Folder\File.txt" | sed -e 's/\\/\//g'
C:/Windows/Folder/File.txt
The sed command in this case is 's/OLD_TEXT/NEW_TEXT/g'.
The leading 's' just tells it to search for OLD_TEXT and replace it with NEW_TEXT.
The trailing 'g' just says to replace all occurrences on a given line, not just the first.
And of course you need to separate the 's', the 'g', the old, and the new from each other. This is where you must use forward slashes as separators.
For your case OLD_TEXT == '\' and NEW_TEXT == '/'. But you can't just go around typing slashes and expecting things to work as expected be taken literally while using them as separators at the same time. In general slashes are quite special and must be handled as such. They must be 'escaped' (i.e. preceded) by a backslash.
So for you, OLD_TEXT == '\\' and NEW_TEXT == '\/'. Putting these inside the 's/OLD_TEXT/NEW_TEXT/g' paradigm you get
's/\\/\//g'. That reads as
's / \\ / \/ / g' and after escapes is
's / \ / / / g' which will replace all backslashes with forward slashes.
Emily
Updated on August 10, 2020Comments
-
Emily over 2 yearsI want to be able to use sed to take an input such as:
C:\Windows\Folder\File.txtto
C:/Windows/Folder/File.txt -
Jimmy over 11 yearsThat's neat, I guess you don't need to escape the forward slash in the first case, because the separator is '.' But you do for the second case. Even the following works!$ echo "C:\Windows\Folder\File.txt" | sed -e 'sf\\f/fg' C:/Windows/Folder/File.txtDoes sed just take the first character after the 's' and further occurances of that character must be escaped? -
Michał Šrajer over 11 yearsBTW, "tr" is much simpler binary than "sed" and faster. -
Mad Physicist over 6 yearstris not the best tool. String substitution is. Whiletris simpler thansed, it is still much more work than using a shell builtin. -
AlikElzin-kilaka over 6 years\\ - first '\' escapes the seconds one in order to be used as character and not as directive. -
Sandburg almost 4 yearsyou can give sed another separator, for example.and then write without double escapements.\\./.g -
Timo almost 2 yearsI need it for wsl2, I use debian in wsl, but here it does not work, result isC: \n oar.xml. tr does not either..