Function to search recursively for patterns in vim

笑着哭i 提交于 2019-12-24 05:32:30

问题


I have a text file with simple text lines. I want to create a function for vim (and gvim) text editor which

can be sent a variable number of patterns and 
it should find lines will all patterns (in any order) 
and keep only these lines 
while deleting the rest. 

I searched the net and found some useful links but none that could do all above:

Following will find and delete all lines not containing the pattern:

 :v/pattern/d

Multiple searching and highlighting can be done with scripts as MultipleSearch http://www.vim.org/scripts/script.php?script_id=479 . Boolean logic searching can be done with LogiPat script https://vim.sourceforge.io/scripts/script.php?script_id=1290 . A filtering package is also available but I could not make it work: http://www.vim.org/scripts/script.php?script_id=2759

To search and keep lines with multiple patterns with AND :

":v/.*pattern1\&.*pattern2/d"

but I have enter the code everytime.

How can I create a function that recursively runs :v/pattern/d to find only lines that contain all the patterns? I expect the function can be run as:

:Myfn pattern1 pattern2 pattern3

Edit: I have tried to write following code for this function, trying to use Linux grep command from within vim:

:function Myfn (Title, ...)
  : let outstr=""
  : for s in a:000
  :   outstr=!echo outstr | grep s
  : endfor
  : return outstr
 : endfunction

But I get following error:

Not an editor command:   :   outstr=!echo outstr | grep s

回答1:


with OR

:v/pattern1\|pattern2\|pattern3/d

with AND

:v/pattern1\&.*pattern2\&.*pattern/d

any order

:v/.*pattern1\&.*pattern2\&.*pattern3/d

(sorry looks like you already had this in of your solutions)




回答2:


You can create a command Keepword:

com! -nargs=* Keepword v/\v<args>/d

and call it like:

Keepword word1|word2|word3

After using the command all lines (except those with the words provided) will be deleted.



来源:https://stackoverflow.com/questions/43570728/function-to-search-recursively-for-patterns-in-vim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!