Search and Open files in vim

Posted April 23, 2022 by Priyadarshan Giri ‐ 2 min read

quick open files by searching into the folder

This is very useful if you want to make a quick edit in a file without having to remember the file name.

Binaries required:

  • skim (preferred) / fzf
  • neovim (preferred) / vim
  • ripgrep (preferred) / grep/ack/ag

skim has interactive mode which is pretty intuitive.

using that and ripgrep we can search for keywords in the current directory.

it returns file in the format filename:line:searched line

using cut command, we can sort it to open the file in the right line in vim/neovim.


You can either create different files and arrange it in your own logical way or add everything in your .bashrc or .zshrc file.

# I have aliased vim to neovim
# alias vim='nvim'

if type rg >/dev/null 2>&1; then
    SK_COMMAND='rg --color=always --line-number "{}"'
else
    SK_COMMAND='grep -rI --color=always --line-number "{}"'
fi

if type sk >/dev/null 2>&1; then
    alias search="sk --ansi -i -c '$SK_COMMAND'"
fi

function open() {
    search_result=$(search)
    if [[ $search_result == "" ]]; then
        return
    else
        line_number=$(echo "$search_result" | cut -d ':' -f 2)
        file_name=$(echo "$search_result" | cut -d ':' -f 1)
        vim +$line_number $file_name
    fi
}

just type open to run the command in the desired folder. Enter your search pattern. Press enter to open the file in vim or neovim.