Say I had the following text
word1 word2 word3 word4
and the cursor was somewhere between word2
and word3
.
word2
and word3
with a single space in Vim?: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
.
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.
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.
This works for me:
:s/\s\+/ /g
ciw
and then escape back to normal mode, although it will only work if you're on a space.
Try replacing all double spaces (repeated zero or more times) with a single space.
:s/ \+/ /g
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
.
%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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With