Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to remove multiple spaces between two words in Vim

Tags:

vim

Say I had the following text

 word1 word2              word3 word4

and the cursor was somewhere between word2 and word3.

Question

  • What's the quickest way to replace the multiple spaces between word2 and word3 with a single space in Vim?

Initial thoughts

  • :s/ */ /g

However, I thought there might be something quicker like diw but for spaces.

It would also be good if the strategy also worked when the cursor was on the w of word3 or the 2 or word2.

like image 853
Jeromy Anglim Avatar asked Mar 01 '11 05:03

Jeromy Anglim


People also ask

How do I remove spaces between words in Vim?

e l d w will do it. If your cursor is in the middle of some whitespace, d i w will delete whitespace left and right of the cursor.

How to replace multiple spaces with single space in vim?

The basic construct of the command is s#search#replace#. Sometimes you see it as s///. The % before the s tells the regex to work on all lines in the vim buffer, not just the current. The space followed by \+ matches one or more spaces.


5 Answers

This works for me:

:s/\s\+/ /g

like image 139
Shad Avatar answered Sep 29 '22 05:09

Shad


ciw and then escape back to normal mode, although it will only work if you're on a space.

like image 34
Hank Gay Avatar answered Sep 29 '22 04:09

Hank Gay


Try replacing all double spaces (repeated zero or more times) with a single space.

:s/  \+/ /g
like image 39
Peter Olson Avatar answered Sep 29 '22 05:09

Peter Olson


I use (bound to a hotkey)

i<enter><esc>kJ

i - insert mode

k - up a line

J - join lines together

This works no matter where the cursor is inside the whitespace or on the w of word3, and puts the cursor on the beginning of the word that just got joined. If you want it to work with the 2 on word2, just replace the first i with a.

like image 31
Seb Avatar answered Sep 29 '22 05:09

Seb


%s/\(\w\)\s\+\(\w\)/\1 \2/g
%  - global
s - search
\( - escape (
\w - (any letter, digit)
\) - escape )
\(\w\) - remember letter/digit before space as \1
\s - whitespace
\+ - escape +
\s\+ - 1 or more whitespace space
\(\w\) - remember letter/digit after space(s) as \2
/ - replcae with
\1 - remembered last letter/digit before space
' ' - space character here - single space
\2 - remembered first letter/digit after white space(s).
/ - end of replace
g - globally
like image 30
Gryglicki Łukasz Avatar answered Sep 29 '22 05:09

Gryglicki Łukasz