在路径中替换反斜杠的问题

时间:2016-10-06 22:25:01

标签: regex sed command-line backslash babun

我正在尝试替换Windows路径中的反斜杠,以便我可以在Filezilla中粘贴路径以打开文件夹而无需在目录结构中浏览。我使用以下命令:

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

我的预期结果是

/path/to/the/05_directory

但我得到了

/path   o       he_directory

似乎\t\05被解释为文字字符串以外的其他内容。

为什么会这样?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

相对于将它们解释为制表符,您可以使用printf "%q"打印文字\

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

然后您可以使用sed来获取输出:

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

"%q"字段准备在外壳程序中使用的字符串。当然,这意味着' '将被转义:

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

您可以单独清理:

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

答案 1 :(得分:0)

很明显,您的字符串是作为带有转义序列的字符串文字读取的。

确保将反斜杠加倍:

echo '\\path\\to\\the\\05_directory' | sed -e 's/\\\\/\\//g'
相关问题