3

This question already has an answer here:

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?

marked as duplicate by Luc Hermitte, Herb Wolfe, guillem, Naumann, 8bittree Apr 17 '18 at 19:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

6

If 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
  • Nice. I wasn't aware of trim(). It may do more than _chomp_ing the last newline though. – Luc Hermitte Apr 16 '18 at 15:55
5

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.