I would like to store the result of a system()
call in a variable without the trailing ^@
character. At the moment I do something like
var = system('command | xargs -i echo -n "{}"')
but it feels convoluted. Is there a simpler solution?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityIf you don't want to use systemlist
for whatever reason, you can explicitly remove the newline and/or whitespace. Since vim 8.0.1630 (very recent), there is a trim()
function which removes whitespace, including newline, from the front and the back of a string.
trim(system('command'))
A common way, if you know there will always be a trailing newline is:
system('command')[:-2]
Or, you can use substitute:
substitute(system('command'), '\n$', '', '') " newline only
substitute(system('command'), '\_s*$', '', '') " any whitespace
trim()
. It may do more than _chomp_ing the last newline though.
Apr 16, 2018 at 15:55
You probably want to use :h systemlist()
:
systemlist({expr} [, {input}]) *systemlist()* Same as system(), but returns a List with lines (parts of output separated by NL) with NULs transformed into NLs.
This is usally a good way to handle system call without having to handle the new line characters.