如何 `==` 到 vim 中的换行符

How to `==` to a newline character in vim

我想匹配 vim 脚本中 if 语句的测试用例中的换行符。

如何匹配换行符?
这样做的原因是,当我想获取系统命令的输出并检查它是否匹配某些内容,然后执行命令时,vim 中的 system() 命令可以完成工作,但是它returns 最后换行。所以我无法正确匹配。

例如,我希望你知道 git rev-parse --is-inside-work-tree,如果我们在 git 存储库中,它会在末尾打印 true 和换行符,而 false如果我们不在 git 存储库中,则末尾有换行符。

我想在 vim 脚本和 运行 一个命令中使用这个命令,只有在 git 存储库中。
但是由于此命令 returns truefalse 末尾有换行符,因此我无法使用以下代码片段来执行此操作。因为 system("git rev-parse --is-inside-work-tree") returns truefalse 末尾有一个换行符。

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

我可以用什么代替 if system("git rev-parse --is-inside-work-tree") == 'true' 来匹配末尾的换行符?

您可以通过替换删除换行符:

system("git rev-parse --is-inside-work-tree")->substitute('\n','','') == 'true'

或与正则表达式进行比较:

system("git rev-parse --is-inside-work-tree") =~ 'true'

或者从外部命令获取列表,只有一个项目,因为输出中只有一行:

systemlist("git rev-parse --is-inside-work-tree")[0] == 'true'

参见 :help substitute()help expr-=~:help systemlist()

您可以使用"true\n"来检查换行符。请注意,双引号用于特殊字符。参见 :h string

echo system('git rev-parse --is-inside-work-tree') == "true\n"
" 1