user1067548
user1067548

Reputation: 31

how to copy a search selection in VI to the clipboard and paste into same file?

I will give you an example of what I'm trying to do. Say I have a file with the following data:

mv AB12350_PCOUTData.txt ./
mv AB12351_PCOUTData.txt ./
mv AB12352_PCOUTData.txt ./
mv AB12353_PCOUTData.txt ./
mv AB12360_PCOUTData.txt ./
mv AB12374_PCOUTData.txt ./

I'm trying to copy just the "AB123xx" portion and paste to the end to get the following:

mv AB12350_PCOUTData.txt ./AB12350

After which I will append with a ".txt" to shorten the file name. My thinking was that I could use the search feature with regex characters to highlight the desired piece of text like so:

/AB123[567][01234]  

Then I could simply copy this to the clipboard and paste it at the end of each line and append with ".txt". Apparently Shift+Ctrl+C doesn't work for searched text, only highlighted text. I also tried using yank and put with no success. Is there an easy way to do this? Or perhaps a better approach to accomplishing the same thing? My actual text files are much longer than the example above so doing it by hand is not really an option. Thanks!

Upvotes: 2

Views: 289

Answers (3)

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20620

This would be fairly easy with a macro.

However, in this particular case you can copy and paste the content using block visual mode (assuming you've actually got vim rather than just plain vi):

  1. Position your cursor on the first A.
  2. Type C-V to enter block selection mode (or C-Q if you're on Windows and have C-V mapped to paste).
  3. Use j and l repeatedly to highlight a block over the content you want to copy.
  4. Press y to yank the content. The cursor will return the the first line.
  5. Press $ to jump to the end of the first line.
  6. Press p to paste the content.

Upvotes: 1

Jon Carter
Jon Carter

Reputation: 3436

This worked for me, on your specific example:

:'<,'>s/\(.*\(AB\d\+\)_.*\)/\1\2/

Upvotes: 0

shellter
shellter

Reputation: 37268

I'm assuming that you have access to the directory where the files are and that you just want to batch operate on them and assume that your solution above was the result of saving the dir listing to a file and appending 'mv ' to the front of the line.

Another approach is just manipulate dir listings 'in-line' and thru pipes.

First

ls -1 *PCOUTData.txt | awk '-F_' '{printf("mv %s ./%s\n", $0, $1)}'
mv AB12350_PCOUTData.txt ./AB12350
mv AB12351_PCOUTData.txt ./AB12351

when your sure it is working the way you want it, redirect into your favorite shell, i.e.

ls -1 *PCOUTData.txt | awk '-F_' '{printf("mv %s ./%s\n", $0, $1)}' | ksh

If your filenames contain spaces, you'll have to read up on find -print0 -prune as the front-end name generator for your cleanup.

IHTH.

Upvotes: 1

Related Questions