vi substitute

My question is how would I substitute for ceratain number of occurences in a line? If this is my input

rjohns BFSTDBS01 Standard Silver NPRO30DINCR  2 Client

Is it possible to change the first 3 occurences of space " " to a comma?

:s/ /,/3

or by awk:

echo "rjohns BFSTDBS01 Standard Silver NPRO30DINCR 2 Client" |awk '{for (i=1;i<=3;i++) sub(/ /,",")}1'

I thought something like:

:,$s/ /,/3

But that replaces the third space on every line with a comma using vim. So you would have to do:

:,$s/ /,/1

three time instead.

Or using sed:

sed -e 's/ /,/' -e 's/ /,/' -e 's/ /,/'

Subststiutes the first space on the next three lines for me using vim. :confused:

sed 's/ /,/;s/ /,/;s/ /,/' file

Oops already posted above..

May be instead of executing it 3 times., Use the following.,

:s/ /,/gc

While it asks for confirmation, give yes only to the first three.

In vim substitution, the range specifier is for number of lines, and not for the number of occurrences.

:1,3s/ /,/

The above is for first to third line.

And the count is for.

From help :s

An optional number that may precede the command to multiply or iterate the command.

@TonyFullerMalv: So thats why it replaces first space on next three lines.

One more way for substitution in vim.

if you don't know the line numbers.

select the line in escape mode using " Shift + v " or "Ctrl+v".

Then press Colan ":" and execute the substitution command in command mode.

see the example:

:'<,'>s/ /,/g

It will substitute the space into comma, only selected lines.

Using sed:

sed -e 's/\([^ ]*\) \([^ ]*\) \([^ ]*\)\(.*\)/\1,\2,\3,\4/g' filename

cheers,
Devaraj Takhellambam

Using the grouping we can achieve it ,

Try the following,

:s/\([^ ]*\) \([^ ]*\) \([^ ]*\) /\1,\2,\3,/

Thanks