2

I have a line that looks like the following, which I am viewing in vim.

 0,0,0,1.791759,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5.278115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

It is from a feature vector file, each row is an instance and each column is the feature value for that feature number. I would like to figure out which feature number 5.27 corresponds to. I know the

s/,//gn

will count the number of commas in the line, but how do I restrict the command to count the number of commas in the line up to the columns with the number 5.27?

I have seen these two posts that seem relevant but cannot seem to piece them together: How to compute the number of times word appeared in a file or in some range and Search and replace in a range of line and column

Community
  • 1
  • 1
Paul
  • 7,155
  • 8
  • 41
  • 40

3 Answers3

3
s/,\ze.*5\.27//gn

The interesting part is the \ze which sets the end of the match. See :h /\ze for more information

Peter Rincker
  • 43,539
  • 9
  • 74
  • 101
  • I was not aware of the \ze atom, which sets the end of the match to whatever is specified - in this case 5.27. Have to add that to the bag of search wizardry. – Paul Sep 19 '14 at 02:52
1

Select the wanted area with visual mode and do

:s/\v%V%(,)//gn

\v enables us to escape less operators with \

%V limits the search to matches that start inside the visual selection

%() keeps the search together if you include alternations with |

It's not pretty but it works. See help files for /\v, \%V and \%(

There are also several versions of a plugin called vis.vim, which offers easier commands that aim to do just the above. However I haven't gotten any of them to work so I'll not comment on that further.

Wiener Boat
  • 426
  • 2
  • 8
  • I contemplated restricting the question to non visual mode as on the machine I was using I didn't have visual. However, I thought that others could benefit (as would I) to see a visual solution. – Paul Sep 19 '14 at 02:45
0

try this

s/,.\{-}5.27//gn

it should work.

Jason Hu
  • 6,239
  • 1
  • 20
  • 41
  • This will not work as `\{-}` will prefer a match that starts earlier to a shorter match. See `:h non-greedy` – Peter Rincker Sep 18 '14 at 18:24
  • @PeterRincker it should. i need non-greedy here. it searches the string in the form of `comma-whatever string follows-5.27`. without non-greedy, `.*` will eat `5.27` too. – Jason Hu Sep 18 '14 at 18:38
  • It does consume the comma all the way though the end of `5.27` meaning that is what you are counting. This will yield only 1 match on the given text. You need either to use a positive look-ahead or end the match via `\ze`. – Peter Rincker Sep 18 '14 at 19:35
  • It looks to not work here in this case as is, but perhaps as @PeterRincker says the \ze will fix it. – Paul Sep 19 '14 at 02:43