How to open a file in VIM and move cursor to the search result

cursorsearchvim

Consider the file tmp.txt whose contents are:

x
abcd

I want to open it in VIM and move cursor to the c character.
So I run VIM with the arguments:

$ vim -c "/c" tmp.txt

But it sets the cursor on a. It looks like VIM was able to find c but placed the cursor at the line begin. Why does it work different if I execute /c in VIM normal mode when file is open?

Best Answer

You can position the cursor on the first match using the -s (script) option. According to the vim manual:

-s {scriptin}
The script file {scriptin} is read. The characters in the file are interpreted as if you had typed them. The same can be done with the command ":source! {scriptin}". If the end of the file is reached before the editor exits, further characters are read from the keyboard.

You could use a temporary file with the keystrokes, or even (if you are using bash) process substitution. For example:

#!/bin/bash
vim -s <(printf '/c\n') tmp.txt

This approach works with more complicated searches than a single character.

Related Question