20

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?

Rastapopoulos
  • 533
  • 3
  • 14

2 Answers2

26

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
Mass
  • 14,080
  • 1
  • 22
  • 47
6

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.

statox
  • 49,782
  • 19
  • 148
  • 225