Use sed to replace all backslashes with forward slashes

后端 未结 9 998
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 04:09

I want to be able to use sed to take an input such as:

C:\\Windows\\Folder\\File.txt

to

C:/Windows/Folder/File.txt
<         


        
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 04:31

    $ 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.

提交回复
热议问题