Windows PATH在bash中进行posix路径转换

Ori*_*ent 35 windows string bash path msys

如何通过标准的msys功能将Windows目录路径(比方说c:/libs/Qt-static)转换为正确的POSIX目录路径(/c/libs/Qt-static)?反之亦然?

Rod*_*uis 40

我不知道msys,但快速谷歌搜索向我显示它包括该sed实用程序.因此,假设它的工作方式与在msys本机Linux上的工作方式类似,这里有一种方法:

从Windows到POSIX

你必须用斜杠替换所有反斜杠,删除驱动器号后面的第一个冒号,并在开头添加斜杠:

echo "/$pth" | sed 's/\\/\//g' | sed 's/://'
Run Code Online (Sandbox Code Playgroud)

或者,如xaizek所述,

echo "/$pth" | sed -e 's/\\/\//g' -e 's/://'
Run Code Online (Sandbox Code Playgroud)

从POSIX到Windows

你必须添加一个分号,删除第一个斜杠并用反斜杠替换所有斜杠:

echo "$pth" | sed 's/^\///' | sed 's/\//\\/g' | sed 's/^./\0:/'
Run Code Online (Sandbox Code Playgroud)

或更有效率,

echo "$pth" | sed -e 's/^\///' -e 's/\//\\/g' -e 's/^./\0:/'
Run Code Online (Sandbox Code Playgroud)

where分别$pth是存储Windows或POSIX路径的变量.

  • 你知道,没有必要管理几个`sed`的调用,只需要将多个`-e command`参数传递给单个实例(比如`sed -e one -e two`). (7认同)
  • @Dukales:...为什么?AFAIK,如果没有前导斜杠,它表示“相对”路径,而前导斜杠则使其成为文件系统根目录的“绝对”路径 (2认同)
  • 当使用git附带的bash时,驱动器号需要小写,一些文件夹名称可以以'$'开头 - 试试这个:`echo"$ pth"| sed -e's#\\#/#g'-e's#\ $#/ \\ $#g'-e's#^ \([a-zA-Z] \):#/\L\1#` (2认同)
  • 将具有多个路径的字符串从Windows转换为POSIX时,必须将前导/必须添加到每个路径.更有效的命令版本将成为:`echo"$ pth"| sed -e's/\\ /\// g'-e's/\([a-zA-Z] \):/\/\1/g'` (2认同)
  • 在 Git Bash 中(至少;我不知道 Windows 中的 Cygwin 或其他 POSIX 兼容 shell 如何处理 Windows 路径),路径前缀“X:”(其中“X”是驱动器字母)变成“/x”,所以`sed 's/://'` 应更改为 `sed -r 's|^([^:]+):|\/\L\1|'` (至少在 Git Bash 中使用时;我还冒昧地将“/”更改为“|”,因为我个人发现这在“sed”脚本中更容易混淆)。 (2认同)

ani*_*ane 26

你在cygwin上使用它吗?如果是的话,那么cygpath.exe在cygwin包中有一个现成的实用工具,只是为了做到这一点.

Output type options:
  -d, --dos             print DOS (short) form of NAMEs (C:\PROGRA~1\)
  -m, --mixed           like --windows, but with regular slashes (C:/WINNT)
  -M, --mode            report on mode of file (binmode or textmode)
  -u, --unix            (default) print Unix form of NAMEs (/cygdrive/c/winnt)
  -w, --windows         print Windows form of NAMEs (C:\WINNT)
  -t, --type TYPE       print TYPE form: 'dos', 'mixed', 'unix', or 'windows'

  • 安装 git-bash 时会包含“cygpath.exe”。您不需要拥有 cygwin,甚至不需要知道 cygwin 是什么。当你使用 git-bash 时它在路径中 (3认同)
  • cygpath似乎可以在MINGW64(git bash)上运行。不知道是因为我也安装了cygwin还是因为这个问题而添加了它-但是我从cygpath'd:\ something'`中得到了预期的结果-它如何自动从剪贴板或自定义环境变量转换字符串? (2认同)

ZYi*_*nMD 7

只需使用cygpath

$ cygpath -w "/c/foo/bar"
 -> C:\foo\bar
$ cygpath -u "C:\foo\bar"
 -> /c/foo/bar
Run Code Online (Sandbox Code Playgroud)

你可能想知道:“我cygpath安装了吗?” 好,

  1. 如果您使用的是 git-bash shell,那么是的。
  2. 如果您在 cygwin 中,那么是的。
  3. 如果您在另一个 shell 中,但之前安装了 git-bash,则cygpath可以在git-bash-install-folder\usr\bin\cygpath.exe.
  4. 否则:也许不是,但我相信您可以找到安装它的方法。


Pod*_*Pod 6

MSYS 中的“正确”方式是:

$ MSYS_NO_PATHCONV=1  taskkill /F /T /IM ssh-agent.exe
Run Code Online (Sandbox Code Playgroud)

这避免了必须手动翻译斜杠。它只是取消激活路径转换。