tags:

views:

54

answers:

2

Hi. 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?

A: 

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

Benoit
nope. still get `too many filenames`. I am on Windows by the way, in case this is some OS related behaviour.
frank
+1  A: 
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()`.

ZyX
I forgot about the `=` inside the backticks. now `=tempname()` works as expected. thank you.
frank