Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a bunch of lines that I want to write out to a different file.
How can I do that?

share|improve this question
add comment

3 Answers

up vote 11 down vote accepted

You can do

:100,200w filename

Of course 100,200 is the range of lines you want to write.

share|improve this answer
    
Are the addresses inclusive or exclusive? –  Marcin Jul 19 '12 at 15:34
2  
Inclusive. Also inclusive if you use patterns: :/^something/,/^else/ w filename, or marks: 'a,'b w filename includes the lines marked 'a' and 'b'. –  Bruce Ediger Jul 19 '12 at 15:46
add comment

To add to Bernhard's answer, you can also select a region using visual mode and then enter :w filename.

share|improve this answer
add comment

The most general:

  1. Move cursor to first line of the group you want to write. Hit m and a sequentiall. That's "set mark named 'a'".

  2. Move cursor to last line of the group, hit 'm' and 'b'.'

  3. Change over to command mode hit: as a sequence do :'a,'b w filename then hit return.

That will work in vi, nvi and vim.

Another method, works in more modern vim:

  1. Put cursor on first line of the group of lines you want to write out. Hit V, for "start visual block of lines".

  2. Move cursor to the bottom of the group of lines. Vim will highlight with reverse video each line.

  3. Write out. Hit : to go into command line mode. That will give you a prompt at the bottom of the scren that looks like: `:'<,'>" That means from the start of the visual block to the end. Type the filename and hit return.

You can add singled lines to the end of the file as you need to by putting your cursor on the line you want to write out then typing: :.w >> filename and hitting return.

The "write a group of lines" commands also work with ">> filename" instead of just "filename". The ">>" causes vi or vim to append to the file, rather than just writing it.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.