9

我想对任何路径字符串(不一定是当前文件的路径)执行与 vimscript 中的 bashdirname命令或 python相同的操作。os.path.split()[0]

示例所需的行为:

  • /a/b/->/a
  • /a/b->/a

我已经尝试过fnamemodify(),但对我来说,它的输出似乎取决于目录是否存在:

:ec fnamemodify( '/usr/idontexist', ':p:h')

给出:

/usr

这很好,但是:

:ec fnamemodify( '/usr/bin', ':p:h')

给出:

/usr/bin

这不是我想要的,我不知道它在做什么。

我希望找到一个跨平台的解决方案。

4

2 回答 2

18

你读过这部分描述吗:h

 When the file name ends in a path separator, only the path
            separator is removed. Thus ":p:h" on a directory name results
        on the directory name itself (without trailing slash).

这就是原因:

:ec fnamemodify( '/usr/bin/', ':p:h')  "directory, ending with /
-> /usr/bin
:ec fnamemodify( '/usr/bin/', ':h')  "directory, ending with /
-> /usr/bin
:ec fnamemodify( '/usr/bin', ':p:h')  "directory, not ending with /
-> /usr/bin
:ec fnamemodify( '/usr/bin', ':h')  "directory, not ending with /
-> /usr

所以有两个因素来决定输出。

  • 如果你的字符串以separator
  • 如果你用过:p

为了实现您的目标,如果字符串以/( 或结尾,则可以删除最后一个字符\ in win?),然后传递给函数而不:p

于 2013-05-10T16:01:52.183 回答
5
fnamemodify( '/usr/idontexist', ':h')

修饰符会将路径扩展为:p完整路径。因此,它必须是一条真实的路径。:p如果您没有弄乱真实路径,请不要使用。

:h filename-modifiers
于 2013-05-10T15:49:12.840 回答