如何检测Vimscript中是否存在特定文件?

ste*_*anB 94 vim file-exists

我正在Vimscript中寻找一种优雅的方法来检查函数中当前目录中是否存在文件.

我想出了这个,但不确定这是否是最优雅的解决方案(我将设置vim选项,如果它存在) - 是否有任何方法不必再进行文件名的比较 - 可能使用不同的__CODE__内置函数( ?):

:function! SomeCheck()
:   if findfile("SpecificFile", ".") == "SpecificFile"
:       echo "SpecificFile exists"
:   endif
:endfunction
Run Code Online (Sandbox Code Playgroud)

ste*_*anB 128

通过一些搜索,vim man我发现了这个,看起来比原来好多了:

:function! SomeCheck()
:   if filereadable("SpecificFile")
:       echo "SpecificFile exists"
:   endif
:endfunction
Run Code Online (Sandbox Code Playgroud)

  • 如果filereadable(expand("〜/ .vim/bundle/vundle/README.md"))让g:hasVundle = 1 endif (7认同)
  • 如果存在SpecificFile,但当前用户无法读取,该怎么办?也许findfile更好. (4认同)
  • `filereadable`的帮助提到你可以使用`glob`如果你不关心可读性. (2认同)

bri*_*rns 49

一些评论表达了对filereadable使用的关注和使用glob.这解决了存在确实存在的文件的问题,但权限阻止了它被读取.如果要检测此类情况,以下内容将起作用:

:if !empty(glob("path/to/file"))
:   echo "File exists."
:endif
Run Code Online (Sandbox Code Playgroud)


icc*_*c97 7

使metaphy对已接受答案的评论更具可见性:

如果文件可读(expand(“〜/ .vim / bundle / vundle / README.md”)),则让g:hasVundle = 1 endif

filereadable是必需的,但expand如果您~在自己的路径中使用,则还有一个额外的方便步骤:

:function! SomeCheck()
:   if filereadable(expand("SpecificFile"))
:       echo "SpecificFile exists"
:   endif
:endfunction 
Run Code Online (Sandbox Code Playgroud)

例如

  • :echo filereadable('~/.vimrc')0
  • :echo filereadable(expand('~/.vimrc'))1


小智 6

抱歉,如果为时已晚,但正在做

if !empty(expand(glob("filename")))
    echo "File exists"
else
    echo "File does not exists"
endif
Run Code Online (Sandbox Code Playgroud)

对我来说效果很好