31

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?

24

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

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

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

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

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

  • 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
23
let @z = systemlist('date')[0]

removes the newline for you.

  • 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
4

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]
  • 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

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.