Search code examples
regexsedcommand-linebackslashbabun

Issues replacing backslashes in paths


I am trying to replace backslashes in Windows paths so that I can paste the path in Filezilla to open the folder without having to browser in the directory structure. I use the following command:

echo '\path\to\the\05_directory' | sed -e 's/\\/\//g'

My expected result is

/path/to/the/05_directory

but instead I get

/path   o       he_directory

it seems \t and \05 are interpreted as something other than literal strings.

Why does this happen? How can I work this around?


Solution

  • You can use printf "%q" to print the literal \ vs having them interpreted as tabs:

    printf "%q" '\path\to\the\05_directory' 
    \\path\\to\\the\\05_directory   
    

    Then you can use sed to get your output:

    printf "%q" '\path\to\the\05_directory' | sed -e 's|\\\\|/|g'
    /path/to/the/05_directory 
    

    The "%q" field prepares a string to be used in the shell. That of course means that ' ' will be escaped:

    printf "%q" '\path\to\the\05 directory' 
    \\path\\to\\the\\05\ directory
    

    Which you can clean up separately:

    printf "%q" '\path\to\the\05 directory' | sed -e 's|\\\\|/|g; s|\\||g'
    /path/to/the/05 directory