Suppose you run the following piece of vimscript:

let @z = system("date")

This will put a string version of the current date into the z register, but the string will end with a newline that I don’t want. Is there a built-in way (similar to Perl’s chomp) to get rid of a string’s trailing newlines?


You can use substitute(), or define a function:

function! Chomp(string)
    return substitute(a:string, '\n\+$', '', '')

This variant will call system for you and then chomp the result:

function! ChompedSystem( ... )
    return substitute(call('system', a:000), '\n\+$', '', '')

(This function is also available in my ingo-library plugin as ingo#system#Chomped.)

| improve this answer | |
  • This works, but why the weird call syntax? Why not just give Chomp a parameter called string and then pass a:string to substitute? – bdesham Apr 9 '15 at 15:03
  • 2
    @bdesham Because Chomp() is passing whatever arguments it gets on to system(), stripping the trailing newline from its output, and returning that. – jamessan Apr 9 '15 at 15:22
  • Right. system() has an optional {input} argument, and this handles any of these generically. If you don't need this, just do it the conventional way. – Ingo Karkat Apr 9 '15 at 16:12
let @z = systemlist('date')[0]

removes the newline for you.

| improve this answer | |
  • I think this is probably the approach I’ll actually use, but I accepted the other answer because it’s more generally applicable. (For example, it will remove trailing newlines from a multiline string while leaving other newlines alone.) – bdesham Apr 10 '15 at 2:28
  • 5
    Note that this won't work correctly for systems which use something other than \n for newline. systemlist() only removes the \n, not any \r. – jamessan Apr 10 '15 at 14:12
  • 1
    Note that this will cause an error if the called function doesn't produce any output. To avoid this and get an empty string instead: get(systemlist("date"), 0, "") – pR0Ps Jul 21 at 18:12

Christian Brabandt has listed a number of different methods over on superuser.com.

I like this one because it is short:

let @z = system("date")[:-2]
| improve this answer | |
  • 1
    I wonder how it handles \r\n type of line endings... – x-yuri Nov 16 '18 at 16:27
  • @x-yuri That is certainly worth checking Don't quote me on this, but I think Vim-on-Windows will normalise those line-endings to \n before returning them. – joeytwiddle Nov 18 '18 at 4:33

Vim v8.0.1630 added a trim() function that removes characters (by default whitespace) from the end or beginning (both by default) of strings:

let @z = trim(system("date"))

For more details see :help trim()

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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