I want to basically search for a pattern in the current file on another file, from vim, using the current visual selection.

I know doing:

:grep pattern otherfile

works, but i want the 'pattern' to be the current visual selection instead (from the current opened file)

How could i do that?


One thought that occurs to me: yank the text (y), and then paste it at the :grep command:

:grep <C-r>" ...

Note that this doesn't work too well for multi-line selections, and you may want something more like

<C-r>=escape(@", '/\')<CR>

to handle some escape sequences.

I'm making use of the "insert register" keystroke (:help <C-r>) and the fact that registers can be used as expressions when prefixed with @.

  • how do i add support for more escape sequences to the second method? (like for example, to escape the character '#' so that it look like '\#') Sep 4 '20 at 20:34
  • 1
    You can add more characters to the second argument of escape()
    – D. Ben Knoble
    Sep 4 '20 at 21:00
  • you're right, seems doing it as '\#/\' work :) (don't know if you meant doing it that way though) Sep 4 '20 at 21:15
  • 1
    You probably dont need the extra backslash, but yes that’s what I meant.
    – D. Ben Knoble
    Sep 4 '20 at 21:20
  • 1
    Hm, looks like a newline. Not sure what’s happening there.
    – D. Ben Knoble
    Sep 4 '20 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.