Vim Tips Wiki

Searching for files

1,610pages on
this wiki
Revision as of 12:12, March 21, 2013 by (Talk)

Tip 799 Printable Monobook Previous Next

created October 3, 2004 · complexity intermediate · author elz · version 5.7

You can add the following to you vimrc file:

" find files
fun! FindFiles()
  let $filename = input("Enter file name to find: ")
  let $error_file = $HOME."/.findfile.output"
  silent! exe "!find . -iname \"".$filename."\" \| xargs file \| perl -pe 's/:/:1:/' > ".$error_file
  cfile $error_file
nmap \f :call FindFiles()<CR>

Then, when in normal mode, type "\f" (or any other mapping that you prefer). This will give a prompt for a file name pattern to search for. Then, all the file names that match this pattern (under the current directory) will be displayed in the quich fix window, along with a description of each of one of them.

Notice, the search is done in a recursive manner. It is case insensitive, and you can use wildcards. If you want to use a regular expression, you can call "find" with the "-regex" or "-iregex" flags.

The function uses some standard gnu *nix utitlities: find, file.

You also need perl to be installed.


I made the following minor modifications to your tip in order to get rid of the dependency on perl and to make it independent from the current errorformat.

fun! FindFiles(filename)
  let error_file = $HOME."/.findfile.output"
  silent exe "!find . -iname '".a:filename."' \| xargs file > ".error_file
  let errorformat=&errorformat
  let winNr = winnr()
  setlocal errorformat=%f:\ %m
  exe "cfile ". error_file
  let cwinNr = winnr()
  exec winNr ."wincmd w"
  exec "setlocal errorformat=". substitute(errorformat, ' ', '\\ ', 'g')
  exec cwinNr ."wincmd w"
command! -nargs=1 FindFile call FindFiles(<q-args>)

Anyway it's possible to use system commands. Example:

:! find foodir -iname "*bar*"

I use this little script. If we find an exact match (wc -l = 1), i open the file in vim. If I find more than one matches, open a list of the files. Then I can use 'gf' (gotofile) in vim to open the specific file.

#! /bin/sh
## fvim: finds files and opens them in vim

## Find files and store them in a list
find . -iname "$1" > $listfile

findcount=`cat $listfile | wc -l`
if [ $findcount -ge 2 ] ; then
 vim $listfile
 vim `cat $listfile`

Vim has also a built-in "find files" functionality. See ':help :find' for more information. Together with 'wildchar', 'wildmenu' and 'path' it is quite powerful.

Advertisement | Your ad here

Around Wikia's network

Random Wiki