0

Sometimes when using locate, my search string will (either incidentally or intentionally) match a portion of a directory. This causes everything below that point in the directory to be printed. For example:

$ locate lib
/home/myname/libImWorkingOn/libImWorkingOn.so
/lib/
/lib/modules/
/lib/firmware/
.... etc

This quickly gets out of hand and makes it difficult to search.

Is there a way to prevent this? For example, have it print:

$locate lib
/home/myname/libImWorkingOn/libImWorkingOn.so
/lib/

And nothing more?

Additionally, is it possible to look for a directory and have locate pick up just the directories?

For example (looking for qemu base folder)

Actual:

$locate qemu
home/myname/qemu
home/myname/qemu/.svn
home/myname/qemu/.svn/.....
home/myname/qemu/Makefile
.....
usr/bin/qemu
.....

Desired:

$locate (option) qemu
/home/myname/qemu
/usr/bin/qemu

3 Answers3

2

On systems with the mlocate version of locate, you could limit the matches using the -b or --basename option:

locate -b lib

... which would limit the results to files whose names contain the string. On my system, this results in many fewer matches:

$ locate lib | wc -l
28901
$ locate -b lib | wc -l
3430
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • This definitely improves the results, but it doesn't cover the use case of looking for a directory. Is there a way to do that as well? – Brydon Gibson Aug 14 '18 at 19:11
2

locate prints a list of absolute pathnames. You can always pipe the result through grep to obtain just filenames

locate lib |grep -E '/lib$'

or just directory names

locate lib |grep '/lib/' | sed -e 's,/lib/.*$,/lib,' | sort -u

If you did this frequently enough, you could write a small script that did each of those (parameterizing the "lib", of course).

Thomas Dickey
  • 76,765
0

we can limit the number of entries by using -l option as below.

 locate -w lib -l 1
  • -w match the exact word

  • -l Exit successfully after finding number occurrence which specified

Or you can use -b option

locate -b '\lib' -l 1
  • -b Match only the base name against the specified patterns
Siva
  • 9,077