I use locate all the time to find files that I know the name of, locate is very fast and I love that. For recently created files find is great, normally with recently created files I know where basically they were created so I don't have to search my entire file system.

When I've forgotten the location of a directory however neither find nor locate seem ideal.

Locate always spits out far too much information because every file within a directory is also a match for locate. For instance if I was searching for a directory named log somewhere on my file system locate log would return tons and tons of results. If I do the same thing with find, find / -name log -type d find takes minutes to run and spits out all sorts of permissions errors every time it encounters a folder it can't read.

Is there a better way?

Answer: So I'm sticking with grep until I find something else:

locatedir () {
    for last; do true; done
    if [[ $last == *\/* ]]
        locate $@ | grep "${last}\$"
        locate $@ | grep "/${last}\$"

A way (I suspect there may be a better way) is to use grep to return only the those paths which end in your folder name :

locate foldername | grep /foldername$
| improve this answer | |

You can use the option --regex (-r) of locate:

locate -r '/log$'
| improve this answer | |
  • Yes (+1). locate has its own built-in regex capablility: -r or --regex ... for full range of options see: info locate – Peter.O Nov 28 '10 at 4:25
  • 1
    I knew there must be a better way! – misterben Nov 28 '10 at 12:32
  • So short and it works smoothly. Great contribution! Another reason to learn/master regular expressions – loved.by.Jesus Nov 8 '16 at 12:23
  • You don't need the two ' in this case: locate -r /log$ is enough. – simlev Sep 26 '17 at 8:56

Have you tried:

locate /home/insertusernamehere/*/filename?


locate file | grep -i '^/home/.*/examplesubdirectory'?

or any variation of such?

| improve this answer | |
  • This answer shows that grep isn't necessary, and as seen in the first suggested option, neither are regexps. – Tom Apr 9 '15 at 12:43

Here it is

locatedir () {
    locate "$*" | while read line
    if [ -d "$line" ] ; then echo $line ; fi

locatedir $*
| improve this answer | |
  • 1
    If you can explain what changes you have made it will be helpful for other too. – Ron Jun 12 '15 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.