TransWikia.com

How do you “chomp” a string in Vim?

Vi and Vim Asked by bdesham on August 31, 2021

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?

4 Answers

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.)

Correct answer by Ingo Karkat on August 31, 2021

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()

Answered by pR0Ps on August 31, 2021

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]

Answered by joeytwiddle on August 31, 2021

let @z = systemlist('date')[0]

removes the newline for you.

Answered by romainl on August 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP