Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 501
aktivb Avatar asked Jan 22 '12 22:01

aktivb


People also ask

What is the difference between append and insert in Vim?

The append command will put the cursor after the current position, while the insert command will put the cursor before it. Using the append command is like moving the cursor one character to the right, and using the insert command.

How do you add a character at the end of each line in Vim?

On a character in the first line, press Ctrl-V (or Ctrl-Q if Ctrl-V is paste). Press jj to extend the visual block over three lines. Press $ to extend the visual block to the end of each line.


2 Answers

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
like image 130
ZyX Avatar answered Oct 29 '22 19:10

ZyX


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
like image 22
Herbert Sitz Avatar answered Oct 29 '22 21:10

Herbert Sitz