Search for files & file names using silver searcher

Jikku Jose picture Jikku Jose · Sep 10, 2013 · Viewed 31k times · Source

Using Silver Searcher, how can I search for:

  1. (non-binary) files with a word or pattern AND
  2. all filenames, with a word or pattern including filenames of binary files.

Other preferences: would like to have case insensitive search and search through dotfiles.


Tried to alias using this without much luck:

alias search="ag -g $1 --smart-case --hidden && ag --smart-case --hidden $1"

Answer

vincentleest picture vincentleest · Jan 20, 2015

According to the man page of ag

   -G --file-search-regex PATTERN
          Only search files whose names match PATTERN.

You can use the -G option to perform searches on files matching a pattern.

So, to answer your question:

root@apache107:~/rpm-4.12.0.1# ag -G cpio.c size
rpm2cpio.c
21:    off_t payload_size;
73:    /* Retrieve payload size and compression type. */
76:     payload_size = headerGetNumber(h, RPMTAG_LONGARCHIVESIZE);

the above command searches for the word size in all files that matches the pattern cpio.c

Reference:
man page of ag version 0.28.0

Note 1:

If you are looking for a string in certain file types, say all C sources code, there is an undocumented feature in ag to help you quickly restrict searches to certain file types.

The commands below both look for foo in all php files:

find . -name \*.php -exec grep foo {}
ag --php foo

While find + grep looks for all .php files, the --php switch in the ag command actually looks for the following file extensions:

.php  .phpt  .php3  .php4  .php5  .phtml

You can use --cpp for C++ source files, --hh for .h files, --js for JavaScript etc etc. A full list can be found here