【问题标题】:Issues replacing backslashes in paths替换路径中的反斜杠的问题
【发布时间】:2017-02-15 19:43:28
【问题描述】:

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

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

我的预期结果是

/path/to/the/05_directory

但我得到了

/path   o       he_directory

似乎\t\05 被解释为文字字符串以外的东西。

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

【问题讨论】:

  • 你在用什么?在linux命令行echo '\path\to\the\05_directory' | sed -e 's/\\/\//g'输出/path/to/the/05_directory
  • 您确定是echo 而不是echo -e
  • 顺便说一句,对于单个字符,您可以使用 tr:tr '\\' '/',而不是使用 sed
  • 对不起,我忘了补充:我在Windows下使用的是babun(一个类似于cygwin的命令行模拟器)。使用 tr '\\' '/' 会得到相同的结果。
  • @msoutopico,您可以尝试使用文件输入而不是 echo 的 sed 命令吗?例如:sed -e 's/\\/\//g' file.txt 其中 file.txt 包含 \path\to\the\05_directory

标签: regex sed command-line backslash babun


【解决方案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" 字段准备一个要在 shell 中使用的字符串。这当然意味着' ' 将被转义:

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

【讨论】:

  • 谢谢。由于我不再使用 babun,我无法测试您的解决方案。现在我使用 WSL 的终端,我无法重现该问题,我的初始方法按预期工作。由于您的建议适用于 WSL 并且看起来很有帮助,我会接受您的回答(知道我不知道它是否真的解决了我当时使用的环境中的原始问题 - 3 年前)
猜你喜欢
  • 2013-07-23
  • 1970-01-01
  • 2021-07-13
  • 2017-03-21
  • 2012-04-14
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
相关资源
最近更新 更多