aktivb
aktivb

Reputation: 2082

How do I append a list to a file in vim?

I want to append a list of strings to a file in VimL Here is my workaround code:

let lines = ["line1\n", "line2\n", "line3\n"]
call writefile(lines, "/tmp/tmpfile")
call system("cat /tmp/tmpfile >> file_to_append_to")

Any way to append to the file directly in vim? There should be, but I can't find anything

Upvotes: 6

Views: 4817

Answers (4)

Benoît Faucon
Benoît Faucon

Reputation: 278

Vim 7.4.503 added support for appending to a file with writefile using the "a" flag :

:call writefile(["foo"], "event.log", "a")

From :h writefile:

writefile({list}, {fname} [, {flags}])
    Write |List| {list} to file {fname}.  Each list item is
    separated with a NL.  Each list item must be a String or
    Number.

    When {flags} contains "a" then append mode is used, lines are
    appended to the file:
        :call writefile(["foo"], "event.log", "a")
        :call writefile(["bar"], "event.log", "a")

Upvotes: 5

ZyX
ZyX

Reputation: 53644

Try using readfile()+writefile().

If you are using Vim 7.3.150+, (or if you are absolutely sure that file in question ends with \n):

function AppendToFile(file, lines)
    call writefile(readfile(a:file)+a:lines, a:file)
endfunction

For Vim older than 7.3.150:

" lines must be a list without trailing newlines.
function AppendToFile(file, lines)
    call writefile(readfile(a:file, 'b')+a:lines, a:file, 'b')
endfunction

" Version working with file *possibly* containing trailing newline
function AppendToFile(file, lines)
    let fcontents=readfile(a:file, 'b')
    if !empty(fcontents) && empty(fcontents[-1])
        call remove(fcontents, -1)
    endif
    call writefile(fcontents+a:lines, a:file, 'b')
endfunction

Upvotes: 7

Herbert Sitz
Herbert Sitz

Reputation: 22256

The write command can be used to append the entire current buffer to a file:

:write >> append_file.txt

You can limit it to range of lines in current buffer if you want. E.g., this would append lines 1 through 8 to end of append_file.txt:

:1,8write >> append_file.txt

Upvotes: 6

Birei
Birei

Reputation: 36272

This may be useful, but it appends content to current file.

Create an array removing \n from each field.

:let lines = ["line1", "line2", "line3"]

And append at the end to current file:

:call append( line('$'), lines )

Upvotes: 3

Related Questions