How to export the matches only in a pattern search in vim?
-
27-09-2019 - |
Question
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.
Solution
Just change your order:
:w newfile.txt
:e newfile.txt
:%s/.\{-}\(http:\/\/.\{-}\)".\{-}/\1/g
:w
OTHER TIPS
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 ing: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.
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').
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow