我想在VimL中将字符串列表附加到文件中这是我的解决方法代码:
let lines = ["line1\n", "line2\n", "line3\n"]
call writefile(lines, "/tmp/tmpfile")
call system("cat /tmp/tmpfile >> file_to_append_to")
Run Code Online (Sandbox Code Playgroud)
有没有办法直接在vim中附加到文件?应该有,但我找不到任何东西
尝试使用readfile()+ writefile().
如果您使用的是Vim 7.3.150+,(或者如果您完全确定该文件以此结尾\n):
function AppendToFile(file, lines)
call writefile(readfile(a:file)+a:lines, a:file)
endfunction
Run Code Online (Sandbox Code Playgroud)
对于早于 7.3.150的Vim :
" 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
Run Code Online (Sandbox Code Playgroud)
该write命令可用于将整个当前缓冲区附加到文件:
:write >> append_file.txt
Run Code Online (Sandbox Code Playgroud)
如果需要,可以将其限制为当前缓冲区中的行范围.例如,这会将第1行到第8行附加到append_file.txt的结尾:
:1,8write >> append_file.txt
Run Code Online (Sandbox Code Playgroud)
Vim 7.4.503 添加了对writefile使用该"a"标志附加到文件的支持:
:call writefile(["foo"], "event.log", "a")
Run Code Online (Sandbox Code Playgroud)
来自: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")
Run Code Online (Sandbox Code Playgroud)