[TriLUG] vi question

Kevin Hunter hunteke at earlham.edu
Wed Jul 16 13:46:20 EDT 2008


At 1:25p -0400 onGreg Brown wrote:
> I'm trying to match multiple commas in a line in vi so I can globally change
> them to a single comma (yup, I'm building a .csv file).

You want to reduce multiple commas to one comma?  ,,,,, -> , ?

> Here's an example line::
> 
> ,101.5000,WRAL,,,,,,,,,,,,,,,,,,,,,,Raleigh,,,,,,,,,,,,,,BF,,,,,,,,,,,,,,,,,,,,,,,Rock

Suggest you also give us what you want after you've run the regex.

> :1,$s/\,+/\,/g  is NOT working.  Grr.  Any hints?  I know I'm overlooking
> something extraordinarily simple here....

I still haven't learned the :a,b$ syntax of Vi, but I figure it out each
time I need it.  As an alternative, % says 'against all lines, do this
following action'.  So this might be for what you're looking:

:%s/[,][,]*/,/g

%   -- Apply following action to all lines
s/  -- begin a substitution action, search part
[,] -- define a character class with one character: ','
*   -- 0 or more occurrences of previous character
/   -- begin replace pattern of substitution action
/g  -- apply substitution to the entire line, not just 1st occurrence

Thus, this regexs says, in English, "Any comma, followed by 0 or commas
is to be replaced by a single comma."

I grew up with perl regex's, so I have a fairly hard time translating to
vi style regexes.  I know it's heresy to say this, but for tasks that
require stuffs more fancy than basic editing, I usually outsource to
another editor.  In this case, since regexes are it, I'd either use a
perl/python script and the commandline, or a GUI editor.

HTH,

Kevin



More information about the TriLUG mailing list