4

I have a CSV that uses ,(comma) as the delimiter. This CSV is nearly 20K lines long and there are 10 instances where a comma was used INSIDE the data. These errant commas are breaking my processor.

In VIM, how would you locate ONLY the lines that have more than 1 comma?

I can find all commas using

:%s/,//gn

This tells me I have 17655 commas on 17646 lines. There should only be 17646 commas, 1 per line, in the entire file. What is an easy way to locate any line with more than one comma on it?

  • 6
    If it's just the lines with more than one comma, you could search /,.*,/ – kba Feb 18 '16 at 16:59
5

I can think of two expressions offhand that may work for you. They both worked on some quick, limited test data I tried. The first expression is

\(.\{-},\)\{2,}

This translates to "match at least 2 sequences of (as few as possible of anything followed by a comma)." In other words this tries to find matches of two or more sequences of comma-delimited text ranges.

Another is

.\{-},\@<=.*,

Which is "find anything followed by a comma, but only if immediately prior to that you could find as few as possible of anything followed by a comma."

I'm not sure if one or the other is more preferable. I find the first one easier to reason about, even though I came up with the second, more complex one first. You may need to anchor them with ^ to the start of the line.

Karl Yngve Lervåg's answer has an even simpler regex that works just as well as my overengineered options.

With them, you can use the global command (:help global) to operate on the matching lines with some Ex command: :g/.\{-},\@<=.*,/d for example, will delete all the lines with more than one comma in them.

  • The second one worked perfect for my needs. Thank you for the help! – ILikeTurtles Feb 18 '16 at 17:05
8

A simple search should suffice:

/,.*,

This will match any line that has at least two commas.

  • 2
    Well, there's nothing like regex to make me feel like I'm over-complicating everything. :( – user72 Feb 18 '16 at 17:11
  • 6
    @JoshPetrie While we are complicating... /,.*, – muru Feb 18 '16 at 19:08
  • @muru I think it is convenient to include the starting /^.*, in order to match only once per line (cf. the original question). – Karl Yngve Lervåg Feb 19 '16 at 6:50
  • 1
    @KarlYngveLervåg because of greedy matching, I'd think it would match only once per line anyway. – muru Feb 19 '16 at 6:53
  • Ah, yes, you are right! I've updated the answer accordingly. Thanks! – Karl Yngve Lervåg Feb 19 '16 at 7:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.