Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save selected text (partial line) from Vim

I try to save some selected text (part of a line) from Vim. Here is the line:

THIS TEST STRING - SELECTED_TARGET_WORLD

where the bold represents the select text. I do this:

:'<,'> w! test/selected_text

but in the file selected_text I find the string:

THIS TEST STRING - SELECTED_TARGET_WORLD

How do I make it save only the selected part of the line?

like image 654
mgramin Avatar asked Sep 05 '12 13:09

mgramin


People also ask

How to select specific lines in vim?

If you want to select the entire line in a file, press V. Now when you press k or j to go up and down, vim will select the entire line above and below your cursor. Finally, you can select text in columns by pressing ctrl+v and moving up or down the block.

How do I select a block of code in Vim?

Press v to begin character-based visual selection, or V to select whole lines, or Ctrl-v or Ctrl-q to select a block. Move the cursor to the end of the text to be cut/copied. While selecting text, you can perform searches and other advanced movement.

How will you copy the the 1st 5 lines in Vi then go to end of file and paste it?

You can copy to the end of the line with y$ and paste with p . To copy/paste between different instances, you can use the system clipboard by selecting the * register, so the commands become "*y$ for copying and "*p for pasting.


2 Answers

:[range]w filename only works with lines so… you have to put the selected text on its own line.

An alternative using :help :redir:

:'<,'>"ay
:redir filename
:echo @a
:redir END
like image 110
romainl Avatar answered Nov 15 '22 19:11

romainl


That case isn't documented in the help (:h :w) but :w handles only line ranges (you would have seen that on a example of multiple lines).

To do what you want, you will have to first paste your selection to a temporary buffer (or on its own line and then put it back in place) and then save that buffer. That can easily be automatized if it's something you're gonna do often.

like image 43
rks Avatar answered Nov 15 '22 18:11

rks