Reputation: 360
I want to match newline character in test case of an if statement in vim script.
How do I match to a newline character ?
The reason for this is, when I want to get the output of a system command and check if it matches something, and then execute a command, the system()
command in vim can do the work, but it returns with a newline at the end. So I am not able to match properly.
For example, I hope you know about git rev-parse --is-inside-work-tree
, it prints true
with a newline at the end if we are inside a git repository, and false
with a newline at the end if we are not inside a git repository.
I want to use this command inside vim script and run a command only if I am inside a git repository.
But since this command returns true
or false
with a newline at the end, I am unable to use the following snippet of code to do this. Because system("git rev-parse --is-inside-work-tree")
returns true
or false
with a newline at the end.
if system("git rev-parse --is-inside-work-tree") == 'true'
echo "Inside a git repository"
else
echo "Not inside a git repository"
endif
What can I use instead of if system("git rev-parse --is-inside-work-tree") == 'true'
to match newline at the end ?
Upvotes: 1
Views: 250
Reputation: 1764
You can use "true\n"
to check the newline. Note that double quotes are used for special characters. See :h string
echo system('git rev-parse --is-inside-work-tree') == "true\n"
" 1
Upvotes: 1
Reputation: 196751
You can remove the newline with a substitution:
system("git rev-parse --is-inside-work-tree")->substitute('\n','','') == 'true'
or compare against a regular expression:
system("git rev-parse --is-inside-work-tree") =~ 'true'
or get a list from the external command, with a single item because there is only one actual line in the output:
systemlist("git rev-parse --is-inside-work-tree")[0] == 'true'
See :help substitute()
, help expr-=~
, and :help systemlist()
.
Upvotes: 1