22

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 == *\/* ]]
    then
        locate $@ | grep "${last}\$"
    else
        locate $@ | grep "/${last}\$"
    fi
}
Michael
  • 323
  • 1
  • 2
  • 7

4 Answers4

28

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

locate -r '/log$'
Volker Siegel
  • 12,820
  • 5
  • 48
  • 65
Florian Diesch
  • 86,013
  • 17
  • 224
  • 214
12

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$
misterben
  • 7,247
  • 3
  • 22
  • 27
5

Have you tried:

locate /home/insertusernamehere/*/filename?

or

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

or any variation of such?

Gilles 'SO- stop being evil'
  • 59,745
  • 16
  • 131
  • 158
RolandiXor
  • 51,091
  • 31
  • 161
  • 256
  • This answer shows that `grep` isn't necessary, and as seen in the first suggested option, neither are regexps. – Tom Apr 09 '15 at 12:43
2

Here it is

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

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