Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all spaces and tabs at the end of my lines

Tags:

vim

Any idea on how to delete all the spaces and tabs at the end of all my lines in my code using vim? I sometimes use commands to add things at the end of my lines, but sometimes, because of these unexpected blanks (that is, I put these blanks there inadvertently while coding), which serve no purpose whatsoever, these commands don't do the right job... so i'd like to get rid of the blanks once and for all using some vim command. Thanks in advance!

like image 790
Nigu Avatar asked Aug 13 '10 07:08

Nigu


People also ask

How do you remove all spaces at the end of a string?

String result = str. trim(); The trim() method will remove both leading and trailing whitespace from a string and return the result.

How do I get rid of extra spaces in a text file?

Press Shift + Alt then press the down button before "56". Then backspace . You will see the cursor becomes big and then you can remove the spaces all at once.


2 Answers

In vim:

:%s/\s\+$// 

Explanation:

  • : command
  • % apply to entire file
  • s search and replace
  • /\s\+$/ regex for one or more whitespace characters followed by the end of a line
  • // replacement value of an empty string
like image 104
Amber Avatar answered Sep 23 '22 07:09

Amber


I use this function :

func! DeleteTrailingWS()   exe "normal mz"   %s/\s\+$//ge   exe "normal `z" endfunc 

Leader,w to remove trailing white spaces

noremap <leader>w :call DeleteTrailingWS()<CR> 

Remove trailing white spaces when saving a python file:

autocmd BufWrite *.py :call DeleteTrailingWS() 
like image 42
Drasill Avatar answered Sep 22 '22 07:09

Drasill