Ubuntu – Locate command is returning too many results

bashcommand lineduplicateduplicate filesscripts

I made the mistake of copying the same files to different partitions with good intentions of pruning (deleting) them from the source or target(s) later. Now when I try to locate them I get too many results from locate command:

rick@alien:~$ locate "display-auto-brightness"
/etc/cron.d/display-auto-brightness
/home/rick/Pictures/display-auto-brightness conky.png
/home/rick/Pictures/display-auto-brightness systray.png
/home/rick/Pictures/display-auto-brightness-config 1.png
/home/rick/Pictures/ps display-auto-brightness.png
/lib/systemd/system-sleep/display-auto-brightness
/mnt/e/etc/cron.d/display-auto-brightness
/mnt/e/lib/systemd/system-sleep/display-auto-brightness
/mnt/e/usr/local/bin/display-auto-brightness
/usr/local/bin/display-auto-brightness

The locate command is automatically placing the * wild card after the search string and returning extra undesired results. The .png files should not be returned.

Why is locate returning too many results?

Best Answer

The locate command is automatically placing the * wild card after the search string and returning extra undesired results.

That is the default behaviour of locate. See man locate:

If any PATTERN contains no globbing characters, locate  behaves  as  if
the pattern were *PATTERN*.

To match only against the filename, explicitly set a glob in the path component:

locate '*/display-auto-brightness'

Or use a regex and the --basename option for matching an exact filename:

locate --basename --regex '^display-auto-brightness$'

Or, given the results you have shown, you could get away with just asking for paths that contain display-auto-brightness at the end:

locate --regex 'display-auto-brightness$'

I'll leave it you to use this in a script looping over each filename in a directory.

Related Question