Jeff Roberts
RHCE #804006066322833
Vim-Fu is now iPhone and Android friendly

Check out the Vim-Fu Store!

Vim-Fu

selecting and writing out a portion of a file

Selecting and writing out a portion of a file into another one, or acting on it in some other way is a very handy thing to know how to do in VIM. There are many actions that you can perform, which will save you loads of time, if you just know some basics about selections.

:20, 40 w file_name

This says, “take the lines starting on 20 and ending on line 40, and put them into a file called file_name

If you don’t know what your current line number is you can find out with:

:.=

You could also find the current line number by turning on the ruler (if you are using non-compatible mode in VIM, see my current .vimrc file) with:

:set ruler

Or you could turn on line numbers for the entire file with:

:set number (:set nonumber to turn off)

The “.” represents the current line and the “$” represents the last line. So putting the cursor on the first line that you want to act on and typing:

: ., $ w file_name

Will write from here to the end, or if you want from here to a specific line, say 40 then do this:

: ., 40 w file_name

What if you start on line 40 and do this:

: ., 10 w file_name

Vim will catch this and ask you if it’s ok to swap these values so that they make sense. Thank you Vim!

These have all been “low-tech” examples, but there is a fancier way, using Visual Mode. Enter visual mode by pressing “v”.

In visual mode you can see what you are selecting while you work. After entering visual mode just move the cursor around to select charactors, line or paragraphs to act upon. You can then type your editing key (d:delete, y:yank, c:change, j:join, etc.) You can also select your text and then type “:” to enter a command. You’ll see this:

:’<,’>

This means “from the beginning of my selection, to the end”. you can then write the selected text out using this:

:’<,’> w file_name

To select a block of text, from say a table use V for Visual Block mode.

Try putting your cursor at the beginning of the text you want to select and then go straight down, then when you get to the last line it “$” and Vim will select to the end of all of the lines, from top to bottom. You can then use the Edit or Action commands on you selected text.

Enjoy!

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>