tags:

views:

171

answers:

3

Regex Question: how do I replace a single space with a newline in VI.

+4  A: 

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

ruibm
i modifier? afraid you'll miss some lowercase spaces?
ithcy
This will replace all spaces on all lines. The question asked for a single space, which would be `:s/ /\r/`
mwc
@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!
jball
:1,$s/ /\n/g - replaces space with "n":1,$s/ /\r/g - replaces space with "r"
@jball: good point. i am using capital spaces for emphasis here.
ithcy
@icthcy, they are a very interesting counterpoint to your completely lowercase text.
jball
Lol, didn't think the 'i' was going to generate such controversy. :P
ruibm
+5  A: 

:%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/

ithcy
Thanks. :%s/ [^ ]/^V^M/g - worked.
er... actually, that was a mistake... should be #2 above.
ithcy
Thanks again. I will save it for future reference. :%s/ /^V^M/ is all I need.
you might just want to forget it actually, it's not correct either... but ^V^M is what you're really looking for :)
ithcy
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>).
Caleb Huitt - cjhuitt
A: 

\([^ ]\|^\)\([^ ]\|$\) will find lone spaces only if that's what you need.

nickd