Iterate using vimscript regexp results

In vimscript, how can I iterate over all regular expression matches in the current file and then run a shell command for each result?

I think this is the beginning, but I cannot figure out how to transfer it to the whole file and get each match.

while search(ENTIRE_FILE, ".*{{\zs.*\ze}}", 'nw') > 0 system(do something with THIS_MATCH) endwhile 
+4
source share
2 answers

Suppose we have a file with the contents:

 123 a shouldmatch 456 b shouldmatch 111 c notmatch 

And we like to match

 123 a shouldmatch 456 b shouldmatch 

with regex

 .*shouldmatch 

If you have only one match per line, you can use readfile() and then loop through the lines and check each line with matchstr() . [1]

 function! Test001() let file = readfile(expand("%:p")) " read current file for line in file let match = matchstr(line, '.*shouldmatch') " regex match if(!empty(match)) echo match " your command with match endif endfor endfunction 

You can put this function in your ~/.vimrc and call it with call Test001() .

[1] http://vimdoc.sourceforge.net/htmldoc/eval.html#matchstr%28%29

+1
source

You can use subtitute() . For instance...

 call substitute(readfile(expand('%')), '.*{{\zs.*\ze}}', \ '\=system("!dosomething ".submatch(1))', 'g') 
0
source

Source: https://habr.com/ru/post/1441388/


All Articles