LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   replace space with new line in vi (https://www.linuxquestions.org/questions/linux-newbie-8/replace-space-with-new-line-in-vi-659368/)

ufmale 07-30-2008 07:55 PM

replace space with new line in vi
 
how to replace every space with newline?

For example, if I have "i want to go to school", i want to convert it to
=====
I
want
to
go
to
school
======

I try :%s/ /\n/g , but it does not seem to work

Also is there a way to count the number of space or number of word within vi?

Mr. C. 07-30-2008 07:58 PM

Use Control-V and then Enter key instead of \n.

Control-V is the special character escape key.

ufmale 07-30-2008 08:05 PM

wow! it works great..
Do you happen to know how to count number of word, or number of provided character?

For example, I want to know how many character "x" or number of "<tag>" is in the text. Is there a way to do it?

Mr. C. 07-30-2008 08:13 PM

Vim doesn't do this natively, but there may be plug-ins that can help at vim.org.

This is the type of thing you can write a script for, and call from vim.

You can do some trickery. Perform a global substitution of your char or word, and see the status line at the bottom. It will tell you the number of replacements. Then, just undo!

:%s/x/Z/g

then see at the bottom:

4 substitutions on 3 lines

ghostdog74 07-30-2008 08:29 PM

another way, without undo
Code:

:%s/e/&/g

ne pas 07-30-2008 08:29 PM

Quote:

Originally Posted by ufmale (Post 3231497)
Also is there a way to count the number of space or number of word within vi?

Press g followed by <Ctrl-g> or use substitute with the 'n' flag to count anything else:
Code:

:%s/\u//gn
counts uppercase characters.

Mr. C. 07-30-2008 08:34 PM

These are good suggestions. The thing that I don't like about not undo'ing is that it changes the file modified status. I've been a :set autowrite/^Z user for 25+ years, and don't want file modifications times changing unless there really are changes. No big deal if the file is changing anyway though. Good suggestions.

graywh 09-26-2008 11:32 AM

Quote:

Originally Posted by ufmale (Post 3231497)
how to replace every space with newline?

For example, if I have "i want to go to school", i want to convert it to
=====
I
want
to
go
to
school
======

I try :%s/ /\n/g , but it does not seem to work

Also is there a way to count the number of space or number of word within vi?

I know you kind of got an answer already, but I wanted to shed some more light on the issue.

The reason it doesn't work is that \n has a different meaning in the replacement part of :substitue. See :help sub-replace-special for more information. Instead, you'll want to use the command :%s/ /\r/g. Use \s instead of a space if you want to include tabs, too. And \s\+ if you want it to replace consecutive spaces and/or tabs with one newline.


All times are GMT -5. The time now is 03:47 AM.