26

I know I can write to a file by simply doing :w <file>. I would like to know though how can I write to a file by appending to it instead of overwriting it.

Example use case: I want to take some samples out of a log file into another file. To achieve that today I can do:

  1. Open the log file
  2. Select some lines with Shift+v
  3. Write to a file: :w /tmp/samples
  4. Select some more lines with Shift+v
  5. Append to /tmp/samples with :w !cat - >> /foo/samples

Unfortunately step 5 is long, ugly and error prone (missing a > makes you lose data). I hope Vim has something better here.

1
  • 3
    If you're interested in using Vim better, do checkout sister site Vi and Vim. Commented Apr 4, 2016 at 15:50

3 Answers 3

46

From :h :w:

 :w_a :write_a E494 :[range]w[rite][!] [++opt] >> Append the specified lines to the current file. :[range]w[rite][!] [++opt] >> {file} Append the specified lines to {file}. '!' forces the write even if file does not exist. 

So, if you have selected the text using visual mode, just do :w >> /foo/samples (:'<,'> will be automatically prepended). If you miss out on a >, Vim will complain:

E494: Use w or w>> 
3
  • This is perfect :) Nothing like reading the docs. Didnt know about :h though. Will use it more Commented Apr 4, 2016 at 15:59
  • 1
    @BrunoPolaco :h is just shorthand for :help. Start with :help helphelp? :D Commented Apr 4, 2016 at 16:02
  • This is great when building shell scripts in combination with the fc command. Commented Dec 3, 2020 at 23:07
0

Define a function:

fun! App(filename) exec "w !cat - >> " . shellescape(a:filename) endfunc 

Call a function:

call App('/foo/samples') 
0
0

Append all contents of current file to file named filename

:w >> filename 

Append contents in line numbers 1 through 13 of current file to file named filename

:1,13w >> filename 
1

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.