views:

39

answers:

3

Is there a way to grab and export the match part only in a pattern search without changing the current file?

For example, from a file containing:

57","0","37","","http://www.thisamericanlife.org/Radio_Episode.aspx?episode=175"
58","0","37","","http://www.thisamericanlife.org/Radio_Episode.aspx?episode=170"

I want to export a new file containing:

http://www.thisamericanlife.org/Radio_Episode.aspx?episode=175
http://www.thisamericanlife.org/Radio_Episode.aspx?episode=170

I can do this by using substitution like this:

:s/.\{-}\(http:\/\/.\{-}\)".\{-}/\1/g
:%w>>data

But the substitution command changes the current file. Is there a way to do this without changing the current file?

Update:

I am looking for a command like this:

:g/pattern/.w>>newfile

This command write the whole line where match occurs. I want to export only the match, not the whole line.

A: 

Do you mean this?

:e currfile.txt
:s/.\{-}\(http:\/\/.\{-}\)".\{-}/\1/g
:w newfile.txt

Or would you like to continue editing the previous file?

EDIT: Or you could simply undo (press 'u').

Umang
Yes, this is similar to what I do. I can undo but I wonder if there is a way to do it without changing current file like :g/pattern/.w>>newfile
Mert Nuhoglu
Ah. I get what you want now, but I don't know how to do it...
Umang
+2  A: 
redir >>newfile
g/^/let g:match=matchstr(getline(line('.')), pattern) | if g:match!=#"" | silent echo g:match | endif
redir END

Explanation:

redir >> newfile
Start redirecting messages to file newfile, append if it exists.
g/^/
For each line
getline(line('.'))
get line contents
let g:match(getline(line('.')), pattern)
find a part of the line which matches pattern and save it in g:match variable
if g:match!=#""
if line matched pattern
echo g:match
output matched line
silent echo g:match
but only to the location specified by the redir command.
redir END
Stop redirecting output.
ZyX
Wow, that's great but a little difficult. Thank you for the detailed instructions.
Mert Nuhoglu
+1  A: 

Just change your order:

 :w newfile.txt
 :e newfile.txt
 :%s/.\{-}\(http:\/\/.\{-}\)".\{-}/\1/g
 :w
rampion