How to add a list to a file in vim?

I want to add a list of lines 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 add a file directly to vim? It must be, but I can't find anything

+6
source share
4 answers

Try using readfile() + writefile() .

If you are using Vim 7.3.150+, ( or if you are absolutely sure that this file 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 
+7
source

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

 :write >> append_file.txt 

You can limit it to the range of lines in the current buffer, if you wish. For example, this will add lines 1 through 8 to the end of append_file.txt:

 :1,8write >> append_file.txt 
+6
source

Vim 7.4.503 added support for adding 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") 
+4
source

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

Create an array that removes \n from each field.

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

And add to the end of the current file:

 :call append( line('$'), lines ) 
+3
source

Source: https://habr.com/ru/post/906609/


All Articles