I want to search for a specific file type(.jpeg) in a given path very efficient manner.
I am presently having 2 options
ls- R | grep .jpeg
- use
'find'
which one is better one? is there any better approach then this?
I would use find /somewhere/on/disk -name "*.jpeg"
over ls
.
There is also the locate *.jpeg
option which makes use of a database. However, this database is only updated at regular intervals (generally from a cron
job) so some file might not have been indexed yet at the time you're invoking the locate
command hence producing a less accurate result. You can force the creation or update of this database by invoking the updatedb
command.
About find
vs ls
performance, ls
will sort the output which takes time while you don't necessarily need it. Also, ls
will output a lot of information which needs to be filtered by grep
afterwards.
Reference:
ls -f
will not sort the output making the list command much faster on big directories. I am not saying that it will be faster than find
though... I don't know.
I've always been a fan of find, there's so much you can do with it:
find /starting/path -type f -name "*.jpeg"
So if I wanted to start under my home directory:
find /home/john -type f -name "*.jpeg"
You may want to look for .jpg and .jpeg (3 letter extensions from the DOS days) as files may be named either way:
find . -type f \( -name "*.jpg" -o -name "*.jpeg" \)
Depends on what you want as a result. ls -R
won't tell you which directory it found the file in, while find
will.
Also, ls -R generates more output, which is subsequently filtered, while find
searches specifically for what you wanted. Without having done measurements, I would guess that find
is generally more efficient.
I usually use
find . -name *.jpg -print {} \;
You might also want to match the files in .JPG and .JPEG in capital letters. With find, you could add -name '*.JPG' -name '*.JPEG'
, or you could pipe find to a grep (yes, it's a bit ugly):
find . -type f | grep "\.[Jj][Pp][Ee]\?[Gg]$"
This will match:
find ./ -name *.jpg -print
*
' should be quoted? Maybe tommieb75's shell handles that ok.
Dec 15, 2009 at 11:57
Install "locate" or "slocate"
Run "updatedb" and "locate \*.jpeg"
updatedb builds a index database for the filenames in your system.
locate will find the file from the database instead of scanning directory by directory.
It is faster that find if you are do searching a lot after each database build. You might want to setup a cron job to run the updatedb command.
This is kind of like Google Desktop Search, but only for searching filename.
Find is definitely the best tool for this job.
The output of ls -R will be difficult to parse (the file names are interleaved with the directory names). Besides with ls you will have hard time dealing with names with spaces, whilst find . -name '*.jpeg' -print0 will generate a list separated by null-characters. xargs, grep and others have option to read this kind of input. This means all weird names are preserved.