【发布时间】:2010-11-05 03:18:30
【问题描述】:
我想知道为 linux 路径转义所需的所有字符是什么。例如,路径 /home/user1/My Music/song 1.mp3 需要在 ls 命令 'ls /home/user1/My\ Music/song\ 1.mp3' 的 shell 中进行转义。
我想编写一个函数,将字符串作为路径并转义所有需要的字符。在斯卡拉我有:
def normalizePath(path: String): String = {
var normPath = path.replaceAll(" ", "\\\\ ")
normPath = normPath.replaceAll("\\]", "\\\\]")
normPath = normPath.replaceAll("\\[", "\\\\[")
normPath
}
知道有更多的字符需要转义。另外,这可能可以通过一个命令来完成(更复杂的正则表达式)?
【问题讨论】:
-
是的
string normalize(string s) { return "\"" + s + "\""; } -
为什么不首先不使用外壳呢?
-
答案取决于您计划在哪里使用该路径。例如,如果要传递给 shell,那么您需要转义 shell 解释的特殊字符(可能包括 '!'、'*'、'?' 等,并且可能取决于 shell 是什么正在使用)。如果将路径放入 URL,则需要转义一组不同的字符,并使用不同的转义机制(%-encode)。而且,如果您将路径直接用于 Linux 系统调用,则根本不需要转义。
-
当您必须处理这么多反斜杠时,您可以使用不需要转义反斜杠的多行字符串文字。例如。
"\\\\"将变为"""\\"""。 -
无效字符(以及其他路径限制)部分取决于文件系统。