How to use locate to search for folders only
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence
--
Chapters
00:00 How To Use Locate To Search For Folders Only
00:19 Answer 1 Score 17
00:39 Answer 2 Score 4
00:54 Answer 3 Score 2
01:04 Answer 4 Score 2
02:19 Answer 5 Score 2
02:52 Thank you
--
Full question
https://superuser.com/questions/408060/h...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#unix #locate
#avk47
ANSWER 1
Score 17
Actually, locate
has what it takes if you use the --regexp
option and you don't mind it spitting out files that have the same name as the directories you seek. The "end of line" position marker gets the job done:
locate -r '/dirname$'
locate
also supports --ignore-case
if that's what you want.
ANSWER 2
Score 4
locate
itself can't do it for you. So the UNIX way to do it is to filter the output of locate
:
locate --null something | xargs -r0 sh -c 'for i do [ -d "$i" ] && printf "%s\n" "$i"; done' sh {} +
ANSWER 3
Score 2
Why not use the find command ?
find . -name YOUR_SEARCH_NAME -type d
ANSWER 4
Score 2
find
as suggested in Scott Wilson's answer is what I would have used. However, if you really need to use the locate DB, a hackish solution could be
sudo strings /var/lib/mlocate/mlocate.db | grep -E '^/.*dirname'
sudo
since the database is not directly readable by regular users.strings
to strip metadata (this makes you also find directories to which you don't have read permission, whichlocate
usually hinders)./var/lib/mlocate/mlocate.db
is the DB path on Ubuntu, apparently (as an example. Other distributions might have it in other places, e.g./var/lib/slocate/slocate.db
).grep -E
to enable regular expressions.^/.*dirname
will match all lines that start with a/
, which all directories in the DB happen to do, followed by any character a number of times, followed by your search word.
Positive sides of this solution:
- it is faster than
find
, - you can use all the bells and whistles of
grep
(or other favourite text processing tools).
Negative sides:
- the same as
locate
in general (DB must be updated), - you need root access.
ANSWER 5
Score 2
Putting Oliver Salzburg's neat line into your .bashrc
:
# locate directories:
# -------------------
locd () {
locate -0 -b -A "$@" | xargs -0 -I {} bash -c '[ -d "{}" ] && echo "{}"'
}
then you can type locd something
everytime you want to locate just directories.
Some breakdown:
-0
provides better support for filenames containing spaces or newlines.-b
or--basename
matches only the last part of the path.-A
matches all inputs, so if you provide multiple arguments, all must be present.