Regex Question: how do I replace a single space with a newline in VI.
3 Answers
:%s/ /^V^M/g
note: hit ctrl-v, ctrl-m.
edit: if you really mean all single spaces, meaning spaces not followed by another space, use this:
:%s/ \{1\}/^V^M/g
and if you really meant just the first single space in the document, use this:
:%s/ /^V^M/
4 Comments
ithcy
er... actually, that was a mistake... should be #2 above.
user267324
Thanks again. I will save it for future reference. :%s/ /^V^M/ is all I need.
ithcy
you might just want to forget it actually, it's not correct either... but ^V^M is what you're really looking for :)
Caleb Huitt - cjhuitt
You can also type ^v<enter>, and it will insert the control character you want. I also use it to search for tabs (^v<tab>).
Just do the following in command mode:
:%s/ /\r/gic
gic in the end means:
- g: replace all occurrences in the same line (not just the first).
- i: case insensitive (not really helpful here but good to know).
- c: prompt for confirmation (nice to have to avoid you having to do immediate undo if it goes wrong :) ).
7 Comments
ithcy
i modifier? afraid you'll miss some lowercase spaces?
mwcz
This will replace all spaces on all lines. The question asked for a single space, which would be
:s/ /\r/jball
@ithcy, what, you've never used case sensitive whitespace? It's much more powerful. Think of the impact of a capital tab versus 4 lowercase spaces - a completely different emotional message to your code!
user267324
:1,$s/ /\n/g - replaces space with "n" :1,$s/ /\r/g - replaces space with "r"
ithcy
@jball: good point. i am using capital spaces for emphasis here.
|