5

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

2
  • What's your first guess? It's probably right. Commented Feb 5, 2010 at 18:39
  • (Or maybe not... I think I was wrong too.) Commented Feb 5, 2010 at 18:52

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

4 Comments

er... actually, that was a mistake... should be #2 above.
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 :)
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>).
5

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

i modifier? afraid you'll miss some lowercase spaces?
This will replace all spaces on all lines. The question asked for a single space, which would be :s/ /\r/
@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!
: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.
|
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.