Featured post
Remove everything except regex match in Vim -
my specific case text document contains lots of text , ipv4 addresses. want remove except ip addresses.
i can use :vglobal search ([0-9]{1,3}\.){3}[0-9]{1,3} , remove lines without ip addresses, after know how search whole line , select matching text. there easier way.
in short, i'm looking way following without using external program (like grep):
grep --extended-regexp --only-matching --regexp="([0-9]{1,3}\.){3}[0-9]{1,3}" calling grep vim may require adapting regex (ex: removing \v). using vim's incremental search shows me i've got pattern right, , don't want verify regex in grep too.
edit: peter, here's function use. (c register clobber in functions.)
"" remove text except matches current search result "" opposite of :%s///g (which clears instances of current search). function! clearallbutmatches()     let old = @c     let @c=""     %s//\=setreg('c', submatch(0), 'l')/g     %d _     put c     0d _     let @c = old endfunction edit2: made command accepts ranges (but defaults whole file).
"" remove text except matches current search result. put each "" match on own line. opposite of :%s///g (which clears "" instances of current search). function! s:clearallbutmatches() range     let is_whole_file = a:firstline == 1 && a:lastline == line('$')      let old_c = @c      let @c=""     exec a:firstline .','. a:lastline .'sub//\=setreg("c", submatch(0), "l")/g'     exec a:firstline .','. a:lastline .'delete _'     put! c      "" want above replace whole selection c, i'll     "" settle removing blank line that's left when deleting file     "" contents.     if is_whole_file         $delete _     endif      let @c = old_c endfunction command! -range=% clearallbutmatches <line1>,<line2>call s:clearallbutmatches() 
this effect can accomplished using sub-replace-special substitution , setreg() linewise
:let @a="" :%s//\=setreg('a', submatch(0), 'l')/g :%d _ :pu :0d _ or in 1 line such:
:let @a=""|%s//\=setreg('a', submatch(0), 'l')/g|%d _|pu a|0d _ overview: using substitution append each match register "a" linewise replace entire buffer contents of register "a"
explanation:
- let @a=""empty "a" register appending into
- %s//\=setreg('a', submatch(0), 'l')/gsubstitute globally using last pattern
- the \=exprreplace pattern contents of expression
- submatch(0)entire string of matched
- setreg('a', submatch(0), 'l')append (note: capital "a") @a matched string, linewise
- %d _delete every line black hole register (aka @_)
- pu aput contents of @a buffer
- 0d _delete first line
concerns:
- this trash 1 of registers. example trashed @a
- uses last search pattern. although can modify substitute command whatever pattern want: %s/<pattern>/\=setreg('a', submatch(0), 'l')/g
for more help
:h :s\= :h :let-@ :h submatch() :h setreg() :h :d :h :p - Get link
- X
- Other Apps
Comments
Post a Comment