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
2010-02-05 18:39:43
i modifier? afraid you'll miss some lowercase spaces?
ithcy
2010-02-05 18:43:25
This will replace all spaces on all lines. The question asked for a single space, which would be `:s/ /\r/`
mwc
2010-02-05 18:45:05
@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
2010-02-05 18:46:05
:1,$s/ /\n/g - replaces space with "n":1,$s/ /\r/g - replaces space with "r"
2010-02-05 18:47:22
@jball: good point. i am using capital spaces for emphasis here.
ithcy
2010-02-05 18:50:26
@icthcy, they are a very interesting counterpoint to your completely lowercase text.
jball
2010-02-05 19:14:39
Lol, didn't think the 'i' was going to generate such controversy. :P
ruibm
2010-02-05 19:19:30
+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
2010-02-05 18:44:28
you might just want to forget it actually, it's not correct either... but ^V^M is what you're really looking for :)
ithcy
2010-02-05 19:34:43
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
2010-02-06 16:58:29
A:
\([^ ]\|^\)\([^ ]\|$\)
will find lone spaces only if that's what you need.
nickd
2010-02-06 16:12:12