Bash function for making locate find exact matches

This is one of the coolest and most useful things to add to my UNIX/Linux profile that I have come across in a long time. I use the locate command a lot (slocate naturally) as I am sure all of us command line monkeys do. How many times have you been frustrated by the billions of lines of results flying by your screen, piping through more or less, trying to find the one nugget of goodness that you really need? Especially when you actually know the correct name of it, just not where it lives? This is where this comes in handy (this is where this? man I am eloquent)! Add this function to your bash profile (for some that’s .bash_profile and for others it might be .bashrc, depending on your nix flavor) and you can stop all of that. I haven’t tried this with other shells aside from bash, but I don’t see why it wouldn’t work.

Basically, this function uses the locate command to find whatever you are looking for just like you do, only it uses a bit of scriptology to filter it down to the exact match of what you are looking for. Yep, that’s right, the exact match! This little tidbit can really help out when you are looking for something, take a look:

## BASH locate function for exact match
## Thanks Dark_Helmet : http://solarum.com/v.php?l=1149LV99
function flocate
{
  if [ $# -gt 1 ] ; then
    display_divider=1
  else
    display_divider=0
  fi

  current_argument=0
  total_arguments=$#
  while [ ${current_argument} -lt ${total_arguments} ] ; do
    current_file=$1
    if [ "${display_divider}" = "1" ] ; then
      echo "----------------------------------------"
      echo "Matches for ${current_file}"
      echo "----------------------------------------"
    fi

    filename_re="^\(.*/\)*$( echo ${current_file} | sed s%\\.%\\\\.%g )$"
    locate -r "${filename_re}"
    shift
    (( current_argument = current_argument + 1 ))
  done
}

It’s just that easy! Copy and paste this into your profile and add a cool helper addon companion function thingy 🙂 I wish I could say I came up with this myself, but I didn’t, I found it in some forums posted by someone named Dark_Helmet (just like the attribution link in the script). I don’t know who you are Mr. Helmet, but I thank you for your sharing this with us all, and I am passing it on! Enjoy!