find
find
command allows a quick and easy scan through the file system and perform tasks on the returned results.
find .
find dir_name/
find .
but only lists the files and folders from the directory named dir_name
find . -type d
find .
but only returns the directories and not the files (works recursively)find . -type f
find .
but only returns the files and not the directories (works recursively)find . -type f -name "file_name"
file_name
file_*
is used instead of file_name
, all files with the prefix file_
will be returned (handy in case the exact file name is not known)-name
option is case sensitive*.py
will return all the files with the extension .py
find . -type f -iname "file_name"
find . -type f -mmin -10
mmin
refers to modified in minutes-10
refers to less than 10 minutes+10
refers to greater than 10 minutesfind . -type f -mmin +5 -min -10
find . -type f -mtime -1
-mtime
refers to the units in days-mmin
, +1
will return files modified more than a day backamin
and atime
refer to the last access time in minutes and days respectivelycmin
and ctime
refer to the last changed time in minutes and days respectively; changed refers to changes in both metadata and contentfind . -size +5M
-size
is the flag to search by file size+
refers to more than while -
is for less than+5M
is greater than 5 Megabytesk
can be used for kilobytesG
can be used for Gigabytesand
operatorand
and or
operators are available as the -a
and -o
switch()
can also be used to group certain flags, but they must be enclosed in ''
or ""
since they are special characters in linuxfind . -type f "(" -mmin -5 -o -mtime +1 ")"
and
only those that were modified (
either less than 5 minutes ago or
more than a day ago )
find . -type f -a "(" -mmin -5 -o -mtime +1 ")"
is an equivalent formulation since the -a
is redundantfind . -empty
find . -perm 777
777
format-maxdepth
flag is useful when we wish to find the files till a certain level of depthfind . -type f -maxdepth 1
find . -type f -maxdepth 2
on the other hand searches both the current directory and only the subdirectories (not the directories inside them)-mindepth
will start the search at the specified minimum depth-exec
flagfind . -type f -name "*.md" -exec head {} ';'
head
command on all the files that are found{}
refer to the placeholder that will contain the entire file path on which to execute the command';'
terminates the command; '
are used since ;
is also a special character in linux;
, we also have the +
option when we wish to pass in the list of files to a commandfind . -type f -name "*.md" -exec tar -czf md_files.tar.gz {} '+'
.md
to the tar
command-exec
, there is -execdir
to execute commands on directories with the ;
and +
options available