I'd like to define a mapping in vim which searches for a special place in the file (using a regex) and than executes an external command that depends on the matched pattern. I.e. I'm thinking about something like:
:g/set\ "\(.*\)"/!echo 'bla '\1' blubb' > file
or
:g:set\ "\(.*\)":call system("echo 'bla ". submatch(0) ." blubb' > file")
Here my aim is to search in my file for a line like
set "x=3"
and to create a new file with the content:
bla x=3 blubb
Unfortunately both tries (and several other ones) are not working. Thanks!
Edit: Adding the following to my .vimrc also didn't work:
:map <F4> :g:set\ "\(.*\)":call Gnutex(submatch(1))
function Gnutex(str)
return system("echo 'bla ". a:str ." blubb' > file")
endfunction
Edit: Working solution (together with the function from before):
:% s/set\ output\ "\(.*\)"/\=[submatch(0), Gnutex(submatch(1))][0]/
I think there are better solutions but this worked.
The \1 and submatch(0) expressions are available as part of the :s command. They are not automatically available for the :g command.
Something like
:g/set ".*"/execute "!echo 'bla" matchstr(getline("."), 'set "\zs.*\ze"') "blubb' > file"
should work. (I tested without the "> file" part.)
Note that you do not have to escape " " (space) as part of a regular expression.
The key thing is that the part after :g/<pattern>/ should be an ex command that will do what you want. In this case, I grab the current line with getline(), munge it with matchstr() (simpler but less flexible than substitute()) and :execute the result.
You should be able to do something similar with :call system().
I think that :g sets the search register, so you might avoid writing out your regular expression twice by using @/ in the matchstr() or substitute() call. In my example above, I removed the \(grouping\) characters, but you should restore them if you want to try this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With