如何检测 Vimscript 中是否存在特定文件?
我正在 Vimscript 中寻找一种优雅的方式来检查当前目录中是否存在文件。
我想出了下面的代码,但我不确定这是否是最优雅的解决方案(如果文件存在,我将设置一个 Vim 选项)。有没有什么方法可以不必再次比较文件名?
也许使用与 Vim 不同的内置函数?
:function! SomeCheck()
: if findfile("SpecificFile", ".") == "SpecificFile"
: echo "SpecificFile exists"
: endif
:endfunction
I'm looking for an elegant way in Vimscript to check if a file exists in the current directory.
I came up with the code below but I'm not sure if that's the most elegant solution (I'll set a Vim option if the file exists). Is there any way of not having to do another comparison of the filename?
Maybe use a different built-in function from Vim?
:function! SomeCheck()
: if findfile("SpecificFile", ".") == "SpecificFile"
: echo "SpecificFile exists"
: endif
:endfunction
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过在 vim man 中进行一些搜索,我发现了这个,它看起来比原来的要好得多:
With a bit of searching in
vim man
I've found this, which looks much better that the original:一些评论表达了对
fileready
和使用glob
的担忧。这解决了文件确实存在但权限阻止读取的问题。如果您想检测此类情况,可以使用以下方法:Some of the comments express concerns about
filereadable
and usingglob
instead. This addresses the issue of having a file that does exist, but permissions prevent it from being read. If you want to detect such cases, the following will work:进一步了解 @thinker3 的评论 关于已接受的答案:
filereadable
是必需的,如果您在文件路径中使用~
,则还有一个额外方便的expand
步骤:例如
:echo fileread('~/.vimrc')
给出0
,:echo fileread(expand('~/.vimrc'))
给出1
Giving some more visibility to @thinker3's comment on the accepted answer:
filereadable
is what is required, if you are using~
in your file path, there's an extra handy step ofexpand
:For example
:echo filereadable('~/.vimrc')
gives0
,:echo filereadable(expand('~/.vimrc'))
gives1
抱歉,如果为时已晚,但这样做
对我来说效果很好
Sorry if it's too late, but doing
works fine for me