开发者

How can I save each match in a different file with Vim

I would like to save the output of g/pattern1/,/pattern2/ to a file (for each match, a different file).

e.g.

def
.......
end

def
.......
end

you would end up with a file for each "def...end".

Tried using tempname() like so:

g/pattern1/,/pattern2/exe 'w ' . tempname() but this fails with no range allowed for exe

also tried

g/pattern1/,/pattern2/w `tempname()`

to get tempname() evaluated but this failed with a "too many filenames" error.

What am I missing? Can this be done by using global and other commands, or would you 开发者_开发问答need vimscript to do it?


g/pattern1/,/pattern2/execute "w ".fnameescape(tempname())<CR>

Use execute whenever you want to insert variable into command-line if it is a mapping. If it is not, try using

g/pattern1/,/pattern2/w <C-r>=fn<Tab>e<Tab>te<Tab>)<CR><CR>

Here fn<Tab> with wildmode=longest,list:full will expand to fname, fnamee<Tab> will expand to fnameescape(, te<Tab> will expand to tempname(), so this is a short way to input <C-r>=fnameescape(tempname())<CR>. You can omit fnameescape if you are sure that tempname will not return filename with special characters.

And note that backticks will not execute vimscript function, they execute shell command, so `tempname()` tries to call tempname() in a shell and substitute filename with the result of this call. According to the help, you should have written `=tempname()`.


Try :g/pattern1/normal! :.,/pattern2/w `tempname()`^M with ^M entered as CTRL-V then ENTER

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜