如何获取路径字符串的父目录

Cir*_*四事件 4 vim

我希望在vimscript中为bash dirname命令或python os.path.split()[0]执行与任何路径字符串(不一定是当前文件的路径)相同的操作.

样本所需行为:

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

我试过fnamemodify()但对我来说它的输出似乎取决于dirs是否存在:

:ec fnamemodify( '/usr/idontexist', ':p:h')
Run Code Online (Sandbox Code Playgroud)

得到:

/usr
Run Code Online (Sandbox Code Playgroud)

哪个好,但是:

:ec fnamemodify( '/usr/bin', ':p:h')
Run Code Online (Sandbox Code Playgroud)

得到:

/usr/bin
Run Code Online (Sandbox Code Playgroud)

这不是我想要的,我无法弄清楚它在做什么.

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

Ken*_*ent 9

你读过这部分描述: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).
Run Code Online (Sandbox Code Playgroud)

这是因为:

: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
Run Code Online (Sandbox Code Playgroud)

所以决定输出有两个因素.

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

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


Pet*_*ker 5

fnamemodify( '/usr/idontexist', ':h')
Run Code Online (Sandbox Code Playgroud)

:p修改将扩大到全路径的路径.因此它必须是一条真正的道路.:p如果你没有弄乱真正的路径,就不要使用.

看到

:h filename-modifiers
Run Code Online (Sandbox Code Playgroud)