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
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With