You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vim script中用==匹配换行符解决system()返回值对比问题

问题原因

Vim的system()函数会保留系统命令输出末尾的换行符,因此直接和无换行的字符串'true'对比会匹配失败。

可用解决方案

以下3种方案都可以实现需求,可根据场景选择:

  • 方案1:直接匹配带换行的结果(最轻量化)
    Vim script中双引号包裹的字符串支持转义字符,直接在匹配值末尾加\n即可:

    if system("git rev-parse --is-inside-work-tree") == "true\n"
      echo "Inside a git repository"
    else 
      echo "Not inside a git repository"
    endif
    
  • 方案2:移除末尾换行后匹配(精准匹配,无额外副作用)
    用substitute()函数正则匹配移除末尾的单个换行符,不会修改内容其他部分:

    if substitute(system("git rev-parse --is-inside-work-tree"), '\n$', '', '') == 'true'
      echo "Inside a git repository"
    else 
      echo "Not inside a git repository"
    endif
    
  • 方案3:用trim()清理首尾空白(适配性最强)
    如果不确定输出是否还有其他首尾空白(比如空格、制表符),可以用trim()函数统一清理,适合大多数调用系统命令的场景:

    if trim(system("git rev-parse --is-inside-work-tree")) == 'true'
      echo "Inside a git repository"
    else 
      echo "Not inside a git repository"
    endif
    

内容的提问来源于stack exchange,提问作者Sarvesh M.D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:36:03