Chris R
Chris R

Reputation: 735

VIM - Fastest way to yank an awkward text block

I am using VIM 7.1.314 and would like to yank the names (chris, robert, ben) in the code shown below as fast as possible - how would I achieve this? Note the names are always aligned (regardless of users number).

user 1: chris (05/04/1984)
user 2: robert (11/12/1991)
user 3: ben (5/25/1993)

Also note, I'm looking for a solution where there is hundreds of names so scalability is important.

Upvotes: 3

Views: 442

Answers (5)

Drasill
Drasill

Reputation: 4016

I would use macros.

  1. qeq (to clear the "e" register)
  2. qa03w"Eywjq (to register a macro yanking the name)
  3. 200000@a (repeat the macro a lots of time)

And then your names are in the "e" register. Type "ep to view them !

Notes :

  • maybe the yw is not correct, maybe a yt( or something, depending on names.
  • :set lazyredraw can help with macro performance !

Upvotes: 0

Luc Hermitte
Luc Hermitte

Reputation: 32926

Here is a pure viml solution that leaves the original buffer unchanged:

:let names= []
:g/^user \d/let names+= matchstr(getline('.'), 'user \d\+:\s*\zs\S\+')
:new
:put=names

Upvotes: 0

ThePosey
ThePosey

Reputation: 2734

You can use a plugin called Tabularize which you can get from https://github.com/godlygeek/tabular. In the case you listed you could do

 :Tabularize /(.*

and it will change your text file to look like this:

user 1: chris  (05/04/1984)
user 2: robert (11/12/1991)
user 3: ben    (5/25/1993)

Then you can simply use visual block to pull the text. It's a great plugin that saves an incredible amount of time.

Upvotes: 1

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

Given that your names are not going to be longer than 16 characters, use a regex search and replace to add 16 spaces after each name, then use block visual mode to do the copy. First, do (on the command line):

:%s/: [^ ]*/&                /

That blank area is 16 spaces. Then, go to the start of the first name and press Control-V, then go 15 characters to the right and to the last line of the list of names and press Y to copy, then to your destination buffer and press P to paste.

Upvotes: 3

Greg Hewgill
Greg Hewgill

Reputation: 992757

An easy way to do this is to shell out to an external program to help. For example:

:%!awk '{ print $3 }'

That will replace your entire edit buffer with the results of running that awk command on the contents of the current buffer. You can then copy the result to another file or whatever, and u easily gets your original buffer back to its previous state.

Upvotes: 8

Related Questions