Monday, October 26, 2009

Find n-th occurrence of pattern - vim tip


Question: In vi editor, how can I find or locate the nth occurrence of a particular search pattern ?

Answer: With new vim editor, once you search a pattern say /queryname , type 4n in command mode which will leap to the 4th occurrence of the word 'queryname' from where you are.

So to find or locate the 10th occurrence of a particular pattern, go to the top of the file (:1), search for the pattern (/pattern) and then in command mode type 10n.

2 comments:

bex said...

This is slightly incorrect... if you wanted the 10th occurrence AFTER going to the first occurrence, you'd type 9n and not 10n. Typing 'n' takes you to the next one. If you run the search and are on the first one then typing 9n will take you to the 9th next one... which is the 10th.

MikeC711g said...

That's exactly what I needed (I did go to home before my 163n). I am doing Machine Learning and verifying some PMML models where the JSON includes an untyped array (all scalar though) of 169 columns. Counting them one at a time was pretty heinous. Looking for the 165th comma ... and then verifying that there were just 3 more ... worked out perfect. Thanks,

© Jadu Saikia www.UNIXCL.com