search for files in a directory hierarchy (2023)

SYNOPSIS

find[-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression]

DESCRIPTION

This manual pagedocuments the GNU version offind.GNUfindsearches the directory tree rooted at each given starting-point byevaluating the given expression from left to right, according to therules of precedence (see section OPERATORS), until the outcome isknown (the left hand side is false for and operations, true foror), at which pointfindmoves on to the next file name. If no starting-point is specified,`.' is assumed.

If you are usingfindin an environment where security is important (for example if you areusing it to search directories that are writable by other users), youshould read the "Security Considerations" chapter of the findutilsdocumentation, which is called Finding Files and comes withfindutils. That document also includes a lot more detailand discussion than this manual page, so you may find it a more usefulsource of information.

OPTIONS

The-H,-Land-Poptions control the treatment of symboliclinks. Command-line arguments following these are taken to be namesof files or directories to be examined, up to the first argument thatbegins with `-', or the argument `(' or `!'. That argument and anyfollowing arguments are taken to be the expression describing what isto be searched for. If no paths are given, the current directory isused. If no expression is given, the expression-printis used(but you should probably consider using-print0instead, anyway).

This manual page talks about `options' within the expression list.These options control the behaviour offindbut are specified immediately after the last path name. The five`real' options-H,-L,-P,-Dand-Omust appear beforethe first path name, if at all. A double dash--can also be usedto signal that any remaining arguments are not options (thoughensuring that all start points begin with either `./' or `/' isgenerally safer if you use wildcards in the list of start points).

-P
Never follow symbolic links. This is the default behaviour. Whenfindexamines or prints information a file, and the file is a symboliclink, the information used shall be taken from the properties of thesymbolic link itself.
-L
Follow symbolic links. Whenfindexamines or prints information about files, the information used shallbe taken from the properties of the file to which the link points, notfrom the link itself (unless it is a broken symbolic link orfindis unable to examine the file to which the link points). Use of thisoption implies-noleaf.If you later use the-Poption,-noleafwill still be in effect. If-Lis in effect andfinddiscovers a symbolic link to a subdirectory during its search,the subdirectory pointed to by the symbolic link will be searched.
When the-Loption is in effect, the-typepredicate will alwaysmatch against the type of the file that a symbolic link points torather than the link itself (unless the symbolic link is broken).Actions that can cause symbolic links to become broken whilefindis executing (for example-delete)can give rise to confusing behaviour.Using-Lcauses the-lnameand-ilnamepredicates always to returnfalse.
-H
Do not follow symbolic links, except while processing the commandline arguments. Whenfindexamines or prints information about files, the information usedshall be taken from the properties of the symbolic link itself. Theonly exception to this behaviour is when a file specified on thecommand line is a symbolic link, and the link can be resolved. Forthat situation, the information used is taken from whatever the linkpoints to (that is, the link is followed). The information about thelink itself is used as a fallback if the file pointed to by thesymbolic link cannot be examined. If-His in effect and one of thepaths specified on the command line is a symbolic link to a directory,the contents of that directory will be examined (though of course-maxdepth 0 would prevent this).

If more than one of-H,-Land-Pis specified, each overrides theothers; the last one appearing on the command line takes effect.Since it is the default, the-Poption should be considered to be ineffect unless either-Hor-Lis specified.

GNUfindfrequently stats files during the processing of the command lineitself, before any searching has begun. These options also affect howthose arguments are processed. Specifically, there are a number oftests that compare files listed on the command line against a file weare currently considering. In each case, the file specified on thecommand line will have been examined and some of its properties willhave been saved. If the named file is in fact a symbolic link, andthe-Poption is in effect (or if neither-Hnor-Lwere specified), the information used for the comparison will be taken fromthe properties of the symbolic link. Otherwise, it will be taken fromthe properties of the file the link points to. Iffindcannot follow the link (for example because it has insufficientprivileges or the link points to a nonexistent file) the properties ofthe link itself will be used.

When the-Hor-L options are in effect, any symbolic links listedas the argument of-newerwill be dereferenced, and the timestampwill be taken from the file to which the symbolic link points. Thesame consideration applies to-newerXY,-anewerand-cnewer.

The-followoption has a similar effect to-L,though it takeseffect at the point where it appears (that is, if-Lis not used but-followis, any symbolic links appearing after-followon thecommand line will be dereferenced, and those before it will not).

-D debugopts
Print diagnostic information; this can be helpful to diagnose problemswith whyfindis not doing what you want. The list of debug options should be commaseparated. Compatibility of the debug options is not guaranteedbetween releases of findutils. For a complete list of valid debugoptions, see the output offind -Dhelp.Valid debug options include
exec
Show diagnostic information relating to -exec, -execdir, -ok and -okdir
help
Explain the debugging options.
opt
Prints diagnostic information relating to the optimisation of theexpression tree; see the -O option.
rates
Prints a summary indicating how often each predicate succeeded orfailed.
search
Navigate the directory tree verbosely.
stat
Print messages as files are examined with thestatandlstatsystem calls. Thefindprogram tries to minimise such calls.
tree
Show the expression tree in its original and optimised form.
-Olevel
Enables query optimisation. Thefindprogram reorders tests to speed up execution while preserving theoverall effect; that is, predicates with side effects are notreordered relative to each other. The optimisations performed at eachoptimisation level are as follows.
0
Equivalent to optimisation level 1.
1
This is the default optimisation level and corresponds to thetraditional behaviour. Expressions are reordered so that tests basedonly on the names of files (for example-nameand-regex)are performed first.
2
Any-typeor-xtypetests are performed after any tests based only on the names of files,but before any tests that require information from the inode. On manymodern versions of Unix, file types are returned byreaddir()and so these predicates are faster to evaluate than predicates whichneed to stat the file first.If you use the-fstypeFOOpredicate and specify a filesystem typeFOOwhich is not known (that is, present in `/etc/mtab') at the timefindstarts, that predicate is equivalent to-false.
3
At this optimisation level, the full cost-based query optimiser isenabled. The order of tests is modified so that cheap (i.e. fast)tests are performed first and more expensive ones are performed later,if necessary. Within each cost band, predicates are evaluated earlieror later according to whether they are likely to succeed or not. For-o,predicates which are likely to succeed are evaluated earlier, and for-a,predicates which are likely to fail are evaluated earlier.
The cost-based optimiser has a fixed idea of how likely any given testis to succeed. In some cases the probability takes account of thespecific nature of the test (for example,-type fis assumed to be more likely to succeed than-type c).The cost-based optimiser is currently being evaluated. If it doesnot actually improve the performance offind,it will be removed again. Conversely, optimisations that prove to bereliable, robust and effective may be enabled at lower optimisationlevels over time. However, the default behaviour (i.e. optimisationlevel 1) will not be changed in the 4.3.x release series. Thefindutils test suite runs all the tests onfindat each optimisation level and ensures that the result is the same.

EXPRESSION

The part of the command line after the list of starting points is theexpression.This is a kind of query specification describing how we match filesand what we do with the files that were matched.An expression is composed of a sequence of things:

Tests
Tests return a true or false value, usually on the basis of someproperty of a file we are considering. The-emptytest for example is true only when the current file is empty.
Actions
Actions have side effects (such as printing something on the standardoutput) and return either true or false, usually based on whether ornot they are successful. The-printaction for example prints the name of the current file on the standardoutput.
Global options
Global options affect the operation of tests and actions specified onany part of the command line. Global options always return true. The-depthoption for example makesfindtraverse the file system in a depth-first order.
Positional options
Positional optiona affect only tests or actions which follow them.Positional options always return true. The-regextypeoption for example is positional, specifying the regular expressiondialect for regulat expressions occurring later on the command line.
Operators
Operators join together the other items within the expression. Theyinclude for example-o(meaning logical OR) and-a(meaning logical AND). Where an operator is missing,-ais assumed.

If the whole expression contains no actions other than-pruneor-print,-printis performed on all files for which the whole expression is true.

The-deleteaction also acts like an option (since it implies-depth).

POSITIONAL OPTIONS

Positional options always return true. They affect only tests occurringlater on the command line.

(Video) Search for files in a directory hierarchy 🤯 // Master Linux #85 #shorts #linux

-daystart
Measure times (for-amin,-atime,-cmin,-ctime,-mmin,and-mtime)from the beginning of today rather than from 24 hours ago. Thisoption only affects tests which appear later on the command line.
-follow
Deprecated; use the-Loption instead. Dereference symbolic links.Implies-noleaf.The-followoption affects only those tests whichappear after it on the command line. Unless the-Hor-Loption hasbeen specified, the position of the-followoption changes the behaviour of the-newerpredicate; any files listed as the argumentof-newerwill be dereferenced if they are symbolic links. The sameconsideration applies to-newerXY,-anewerand-cnewer.Similarly, the-typepredicate will always match against the type of the filethat a symbolic link points to rather than the link itself. Using-followcauses the-lname and-ilnamepredicates always to return false.
-regextype type
Changes the regular expression syntax understood by-regexand-iregextests which occur later on the command line. To see which regularexpression types are known, use-regextypehelp.The Texinfo documentation (seeSEEALSO)explains the meaning of anddifferences between the various types of regular expression.
-warn, -nowarn
Turn warning messages on or off. These warnings apply only to thecommand line usage, not to any conditions thatfindmight encounter when it searches directories. The default behaviourcorresponds to-warnif standard input is a tty, and to-nowarnotherwise. If a warning message relating to command-line usage isproduced, the exit status offindis not affected. If the POSIXLY_CORRECT environment variable is set,and-warn is also used, it is not specified which, if any, warnings will be active.

GLOBAL OPTIONS

Global options always return true.Global options take effect even for tests which occur earlier on thecommand line. To prevent confusion, global options should specifiedon the command-line after the list of start points, just before thefirst test, positional option or action. If you specify a globaloption in some other place,findwill issue a warning message explaining that this can be confusing.

The global options occur after the list of start points, and so arenot the same kind of option as-L,for example.

-d
A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD.
-depth
Process each directory's contents before the directory itself. The-delete action also implies-depth.
-help, --help
Print a summary of the command-line usage offindand exit.
-ignore_readdir_race
Normally, find will emit an error message when it fails to stat a file.If you give this option and a file is deleted between the time findreads the name of the file from the directory and the time it tries to statthe file, no error message will be issued. This also applies to filesor directories whose names are given on the command line. This option takeseffect at the time the command line is read, which means that you cannot searchone part of the filesystem with this option on and part of it with this optionoff (if you need to do that, you will need to issue two find commandsinstead, one with the option and one without it).
-maxdepth levels
Descend at most levels (a non-negative integer) levels ofdirectories below the starting-points.-maxdepth 0
meansonlyapplythetestsandactionstothestarting-pointsthemselves.
-mindepth levels
Do not apply any tests or actions at levels less than levels (anon-negative integer).-mindepth 1means process all files except the starting-points.
-mount
Don't descend directories on other filesystems. An alternate name for-xdev,for compatibility with some other versions offind.
-noignore_readdir_race
Turns off the effect of-ignore_readdir_race.
-noleaf
Do not optimize by assuming that directories contain 2 fewersubdirectories than their hard link count. This option is needed whensearching filesystems that do not follow the Unix directory-linkconvention, such as CD-ROM or MS-DOS filesystems or AFS volume mountpoints. Each directory on a normal Unix filesystem has at least 2hard links: its name and its `.' entry. Additionally, itssubdirectories (if any) each have a `..' entry linked to thatdirectory. Whenfindis examining a directory, after it has statted 2 fewer subdirectoriesthan the directory's link count, it knows that the rest of the entriesin the directory are non-directories (`leaf' files in the directorytree). If only the files' names need to be examined, there is no needto stat them; this gives a significant increase in search speed.
-version, --version
Print the find version number and exit.
-xdev
Don't descend directories on other filesystems.

TESTS

Some tests, for example-newerXYand-samefile,allow comparison between the file currently being examined and somereference file specified on the command line. When these tests areused, the interpretation of the reference file is determined by theoptions-H,-Land-Pand any previous-follow,but the reference file is only examined once, at the time the commandline is parsed. If the reference file cannot be examined (forexample, thestat(2)system call fails for it), an error message is issued, andfindexits with a nonzero status.

Numeric arguments can be specified as

+n
for greater thann,
-n
for less thann,
n
for exactlyn.
-amin n
File was last accessed n minutes ago.
-anewer file
File was last accessed more recently than file was modified. Iffile is a symbolic link and the-Hoption or the-Loption is in effect, the access time of the file it points to isalways used.
-atime n
File was last accessed n*24 hours ago.When find figures out how many 24-hour periods ago the filewas last accessed, any fractional part is ignored, so to match-atime+1,a file has to have been accessed at leasttwodays ago.
-cmin n
File's status was last changed n minutes ago.
-cnewer file
File's status was last changed more recently than file wasmodified. If file is a symbolic link and the-Hoption or the-Loption is in effect, the status-change time of the file it pointsto is always used.
-ctime n
File's status was last changed n*24 hours ago.See the comments for-atimeto understand how rounding affects the interpretation of file statuschange times.
-empty
File is empty and is either a regular file or a directory.
-executable
Matches files which are executable and directories which aresearchable (in a file name resolution sense). This takes into accountaccess control lists and other permissions artefacts which the-permtest ignores. This test makes use of theaccess(2)system call, and so can be fooled by NFS servers which do UIDmapping (or root-squashing), since many systems implementaccess(2)in the client's kernel and so cannot make use of the UID mappinginformation held on the server. Because this test is based only onthe result of theaccess(2)system call, there is no guarantee that a file for which this testsucceeds can actually be executed.
-false
Always false.
-fstype type
File is on a filesystem of type type. The valid filesystemtypes vary among different versions of Unix; an incomplete list offilesystem types that are accepted on some version of Unix or anotheris: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use-printfwith the %F directive to see the types of your filesystems.
-gid n
File's numeric group ID is n.
-group gname
File belongs to group gname (numeric group ID allowed).
-ilname pattern
Like-lname,but the match is case insensitive.If the-Loption or the-followoption is in effect, this test returns false unless the symbolic linkis broken.
-iname pattern
Like-name,but the match is case insensitive. For example, thepatterns `fo*' and `F??' match the file names `Foo', `FOO', `foo',`fOo', etc. The pattern `*foo*` will also match a filecalled '.foobar'.
-inum n
File has inode number n. It is normally easier to use the-samefiletest instead.
-ipath pattern
Like-path.but the match is case insensitive.
-iregex pattern
Like-regex,but the match is case insensitive.
-iwholename pattern
See -ipath. This alternative is less portable than-ipath.
-links n
File has n links.
-lname pattern
File is a symbolic link whose contents match shell patternpattern. The metacharacters do not treat `/' or `.' specially.If the-Loption or the-followoption is in effect, this test returns false unless the symbolic linkis broken.
-mmin n
File's data was last modified n minutes ago.
-mtime n
File's data was last modified n*24 hours ago.See the comments for-atimeto understand how rounding affects the interpretation of filemodification times.
-name pattern
Base of file name (the path with the leading directories removed)matches shell pattern pattern. Because the leading directoriesare removed, the file names considered for a match with-namewill never include a slash, so `-name a/b' will never match anything(you probably need to use-pathinstead). A warning is issued if you try to do this, unless the environment variablePOSIXLY_CORRECT is set.The metacharacters (`*', `?',and `[]') match a `.' at the start of the base name (this is a changein findutils-4.2.2; see section STANDARDS CONFORMANCE below). To ignore adirectory and the files under it, use-prune;see an example in thedescription of-path.Braces are not recognised as beingspecial, despite the fact that some shells including Bash imbue braceswith a special meaning in shell patterns. The filename matching isperformed with the use of thefnmatch(3)library function. Don't forget to enclose the pattern in quotesin order to protect it from expansion by the shell.
-newer file
File was modified more recently than file. If file is asymbolic link and the-Hoption or the-Loption is in effect, themodification time of the file it points to is always used.
-newerXY reference
Succeeds if timestamp X of the file being considered is newerthan timestamp Y of the file reference. The lettersX and Y can be any of the following letters:
aThe access time of the file reference
BThe birth time of the file reference
cThe inode status change time of reference
mThe modification time of the file reference
treference is interpreted directly as a time

Some combinations are invalid; for example, it is invalid forXto bet.Some combinations are not implemented on all systems; for exampleBis not supported on all systems. If an invalid or unsupportedcombination ofXYis specified, a fatal error results. Time specifications areinterpreted as for the argument to the-doption of GNUdate.If you try to use the birth time of a reference file, and the birthtime cannot be determined, a fatal error message results. If youspecify a test which refers to the birth time of files being examined,this test will fail for any files where the birth time is unknown.

-nogroup
No group corresponds to file's numeric group ID.
-nouser
No user corresponds to file's numeric user ID.
-path pattern
File name matches shell pattern pattern. The metacharacters donot treat `/' or `.' specially; so, for example,
find . -path "./sr*sc"
will print an entry for a directory called `./src/misc' (if oneexists). To ignore a whole directory tree, use-prunerather thanchecking every file in the tree. For example, to skip thedirectory `src/emacs' and all files and directories under it, andprint the names of the other files found, do something like this:
find . -path ./src/emacs -prune -o -print
Note that the pattern match test applies to the whole file name,starting from one of the start points named on the command line. Itwould only make sense to use an absolute path name here if therelevant start point is also an absolute path. This means that thiscommand will never match anything:
find bar -path /foo/bar/myfile -print
Find compares the-pathargument with the concatenation of a directory name and the base nameof the file it's examining. Since the concatenation will never endwith a slash,-patharguments ending in a slash will match nothing (except perhaps a startpoint specified on the command line).The predicate-pathis also supported by HP-UXfindand will be in a forthcoming version of the POSIX standard.
-perm mode
File's permission bits are exactly mode (octal or symbolic).Since an exact match is required, if you want to use this form forsymbolic modes, you may have to specify a rather complex mode string.For example `-perm g=w' will only match files which have mode 0020(that is, ones for which group write permission is the only permissionset). It is more likely that you will want to use the `/' or `-'forms, for example `-perm -g=w', which matches any file with groupwrite permission. See theEXAMPLESsection for some illustrative examples.
-perm -mode
All of the permission bits mode are set for the file.Symbolic modes are accepted in this form, and this is usually the wayin which you would want to use them. You must specify `u', `g' or `o' ifyou use a symbolic mode. See theEXAMPLESsection for some illustrative examples.
-perm /mode
Any of the permission bits mode are set for the file. Symbolicmodes are accepted in this form. You must specify `u', `g' or `o' ifyou use a symbolic mode. See theEXAMPLESsection for some illustrative examples. If no permission bits inmodeare set, this test matches any file (the idea here is to be consistentwith the behaviour of-perm-000).
-perm +mode
This is no longer supported (and has been deprecated since 2005). Use-perm /modeinstead.
-readable
Matches files which are readable. This takes into account accesscontrol lists and other permissions artefacts which the-permtest ignores. This test makes use of theaccess(2)system call, and so can be fooled by NFS servers which do UIDmapping (or root-squashing), since many systems implementaccess(2)in the client's kernel and so cannot make use of the UID mappinginformation held on the server.
-regex pattern
File name matches regular expression pattern. This is a matchon the whole path, not a search. For example, to match a file named`./fubar3', you can use the regular expression `.*bar.' or `.*b.*3',but not `f.*r3'. The regular expressions understood byfindare by default Emacs Regular Expressions, but this can bechanged with the-regextypeoption.
-samefile name
File refers to the same inode as name. When-Lis in effect, this can include symbolic links.
-size n[cwbkMG]
File uses n units of space, rounding up. The following suffixescan be used:
`b'
for 512-byte blocks (this is the default if no suffix is used)
`c'
for bytes
`w'
for two-byte words
`k'
for Kilobytes (units of 1024 bytes)
`M'
for Megabytes (units of 1048576 bytes)
`G'
for Gigabytes (units of 1073741824 bytes)
The size does not count indirect blocks, but it does count blocks insparse files that are not actually allocated. Bear in mind that the`%k' and `%b' format specifiers of-printfhandle sparse filesdifferently. The `b' suffix always denotes 512-byte blocks and never1 Kilobyte blocks, which is different to the behaviour of-ls.
The + and - prefixes signify greater than and less than, as usual.Bear in mind that the size is rounded up to the next unit. Therefore-size -1Mis not equivalent to-size -1048576c.The former only matches empty files, the latter matches files from 1 to1,048,575 bytes.
-true
Always true.
-type c
File is of type c:
b
block (buffered) special
c
character (unbuffered) special
d
directory
p
named pipe (FIFO)
f
regular file
l
symbolic link; this is never true if the-Loption or the-followoption is in effect, unless the symbolic link is broken. If you wantto search for symbolic links when-Lis in effect, use-xtype.
s
socket
D
door (Solaris)
To search for more than one type at once, you can supply the combined list oftype letters separated by a comma `,' (GNU extension).
-uid n
File's numeric user ID is n.
-used n
File was last accessed n days after its status was last changed.
-user uname
File is owned by user uname (numeric user ID allowed).
-wholename pattern
See -path. This alternative is less portable than-path.
-writable
Matches files which are writable. This takes into account accesscontrol lists and other permissions artefacts which the-permtest ignores. This test makes use of theaccess(2)system call, and so can be fooled by NFS servers which do UIDmapping (or root-squashing), since many systems implementaccess(2)in the client's kernel and so cannot make use of the UID mappinginformation held on the server.
-xtype c
The same as-typeunless the file is a symbolic link. For symboliclinks: if the-Hor-Poption was specified, true if the file is alink to a file of type c; if the-Loption has been given, trueif c is `l'. In other words, for symbolic links,-xtypechecks the type of the file that-typedoes not check.
-context pattern
(SELinux only) Security context of the file matches glob pattern.

ACTIONS

-delete
Delete files; true if removal succeeded. If the removal failed, anerror message is issued.If-deletefails,find'sexit status will be nonzero(when it eventually exits).Use of-deleteautomatically turns on the`-depth'option.

Warnings:Don't forget that the find command line isevaluated as an expression, so putting-deletefirst will makefindtry to delete everything below the starting points you specified.When testing afindcommand line that you later intend to use with-delete,you should explicitly specify-depthin order to avoid later surprises. Because-deleteimplies-depth,you cannot usefully use-pruneand-deletetogether.

-exec command ;
Execute command; true if 0 status is returned. All followingarguments tofindare taken to be arguments to the command until an argument consistingof `;' is encountered. The string `{}' is replaced by the currentfile name being processed everywhere it occurs in the arguments to thecommand, not just in arguments where it is alone, as in some versionsoffind.Both of these constructions might need to be escaped (with a `\') orquoted to protect them from expansion by the shell. See theEXAMPLESsection for examples of the use of the-execoption. The specifiedcommand is run once for each matched file.The command is executed in the starting directory. There areunavoidable security problems surrounding use of the-execaction;you should use the-execdiroption instead.
-exec command {} +
This variant of the-execaction runs the specified command on theselected files, but the command line is built by appending eachselected file name at the end; the total number of invocations of thecommand will be much less than the number of matched files. Thecommand line is built in much the same way thatxargsbuilds its command lines. Only one instance of `{}' is allowed withinthe command. The command is executed in the starting directory. Ifany invocation returns a non-zero value as exit status, thenfindreturns a non-zero exit status. Iffindencounters an error, this can sometimes cause animmediate exit, so some pending commands may not be runat all. This variant of-execalways returns true.
-execdir command ;
-execdir command {} +
Like-exec,but the specified command is run from the subdirectorycontaining the matched file, which is not normally the directory inwhich you startedfind.This a much more secure method for invoking commands, as it avoidsrace conditions during resolution of the paths to the matched files.As with the-execaction, the `+' form of-execdirwill build acommand line to process more than one matched file, but any giveninvocation ofcommandwill only list files that exist in the same subdirectory. If you usethis option, you must ensure that your$PATHenvironment variable does not reference `.';otherwise, an attacker can run any commands they like by leaving anappropriately-named file in a directory in which you will run-execdir.The same applies to having entries in$PATHwhich are empty or which are not absolute directory names. Ifany invocation returns a non-zero value as exit status, thenfindreturns a non-zero exit status. Iffindencounters an error, this can sometimes cause animmediate exit, so some pending commands may not be runat all. The result of the action depends on whether the+or the;variant is being used;-execdircommand{} +always returns true, while-execdircommand{} ;returns true only ifcommandreturns 0.
-fls file
True; like-lsbut write to file like-fprint.The output file is always created, even if the predicate is nevermatched.See theUNUSUAL FILENAMESsection for information about how unusual characters in filenames are handled.
-fprint file
True; print the full file name into file file. If filedoes not exist when find is run, it is created; if it doesexist, it is truncated. The file names `/dev/stdout' and`/dev/stderr' are handled specially; they refer to the standardoutput and standard error output, respectively.The output file is always created, even if the predicate is never matched.See theUNUSUAL FILENAMESsection for information about how unusual characters in filenames are handled.
-fprint0 file
True; like-print0but write to file like-fprint.The output file is always created, even if the predicate is never matched.See theUNUSUAL FILENAMESsection for information about how unusual characters in filenames are handled.
-fprintf file format
True; like-printfbut write to file like-fprint.The output file is always created, even if the predicate is never matched.See theUNUSUAL FILENAMESsection for information about how unusual characters in filenames are handled.
-ls
True; list current file inls -dilsformat on standard output.The block counts are of 1K blocks, unless the environment variablePOSIXLY_CORRECT is set, in which case 512-byte blocks are used.See theUNUSUAL FILENAMESsection for information about how unusual characters in filenames are handled.
-ok command ;
Like-execbut ask the user first. If the user agrees, run the command. Otherwisejust return false. If the command is run, its standard input is redirectedfrom/dev/null.
The response to the prompt is matched against a pair of regularexpressions to determine if it is an affirmative or negativeresponse. This regular expression is obtained from the system if the`POSIXLY_CORRECT' environment variable is set, or otherwise fromfind'smessage translations. If the system has no suitabledefinition,find'sown definition will be used. In either case, the interpretation ofthe regular expression itself will be affected by the environmentvariables 'LC_CTYPE' (character classes) and 'LC_COLLATE' (characterranges and equivalence classes).
-okdir command ;
Like-execdirbut ask the user first in the same way as for-ok.If the user does not agree, just return false.If the command is run, its standard input is redirected from/dev/null.
-print
True; print the full file name on the standard output, followed by anewline. If you are piping the output offindinto another program and there is the faintest possibility that the fileswhich you are searching for might contain a newline, then you shouldseriously consider using the-print0option instead of-print.See theUNUSUAL FILENAMESsection for information about how unusual characters in filenames are handled.
-print0
True; print the full file name on the standard output, followed by anull character (instead of the newline character that-printuses).This allows file names that contain newlines or other types of whitespace to be correctly interpreted by programs that process thefind output. This option corresponds to the-0option ofxargs.
-printf format
True; print format on the standard output, interpreting `\'escapes and `%' directives. Field widths and precisions can bespecified as with the `printf' C function. Please note that many ofthe fields are printed as %s rather than %d, and this may mean thatflags don't work as you might expect. This also means that the `-'flag does work (it forces fields to be left-aligned). Unlike-print,-printfdoes not add a newline at the end of the string. The escapesand directives are:
\a
Alarm bell.
\b
Backspace.
\c
Stop printing from this format immediately and flush the output.
\f
Form feed.
\n
Newline.
\r
Carriage return.
\t
Horizontal tab.
\v
Vertical tab.
\0
ASCII NUL.
\\
A literal backslash (`\').
\NNN
The character whose ASCII code is NNN (octal).

A `\' character followed by any other character is treated as anordinary character, so they both are printed.

%%
A literal percent sign.
%a
File's last access time in the format returned by the C `ctime' function.
%Ak
File's last access time in the format specified by k, which iseither `@' or a directive for the C `strftime' function. The possiblevalues for k are listed below; some of them might not beavailable on all systems, due to differences in `strftime' betweensystems.
@
seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.

Time fields:

H
hour (00..23)
I
hour (01..12)
k
hour ( 0..23)
l
hour ( 1..12)
M
minute (00..59)
p
locale's AM or PM
r
time, 12-hour (hh:mm:ss [AP]M)
S
Second (00.00 .. 61.00). There is a fractional part.
T
time, 24-hour (hh:mm:ss.xxxxxxxxxx)
+
Date and time, separated by `+', for example`2004-04-28+22:22:05.0'. This is a GNU extension. The time isgiven in the current timezone (which may be affected by setting the TZenvironment variable). The seconds field includes a fractional part.
X
locale's time representation (H:M:S). The seconds field includes afractional part.
Z
time zone (e.g., EDT), or nothing if no time zone is determinable

Date fields:

a
locale's abbreviated weekday name (Sun..Sat)
A
locale's full weekday name, variable length (Sunday..Saturday)
b
locale's abbreviated month name (Jan..Dec)
B
locale's full month name, variable length (January..December)
c
locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format isthe same as forctime(3)and so to preserve compatibility with that format, there is no fractional partin the seconds field.
d
day of month (01..31)
D
date (mm/dd/yy)
h
same as b
j
day of year (001..366)
m
month (01..12)
U
week number of year with Sunday as first day of week (00..53)
w
day of week (0..6)
W
week number of year with Monday as first day of week (00..53)
x
locale's date representation (mm/dd/yy)
y
last two digits of year (00..99)
Y
year (1970...)
%b
The amount of disk space used for this file in 512-byte blocks. Since diskspace is allocated in multiples of the filesystem block size this is usuallygreater than %s/512, but it can also be smaller if the file is a sparse file.
%c
File's last status change time in the format returned by the C `ctime'function.
%Ck
File's last status change time in the format specified by k,which is the same as for %A.
%d
File's depth in the directory tree; 0 means the file is a starting-point.
%D
The device number on which the file exists (the st_dev field of structstat), in decimal.
%f
File's name with any leading directories removed (only the last element).
%F
Type of the filesystem the file is on; this value can be used for-fstype.
%g
File's group name, or numeric group ID if the group has no name.
%G
File's numeric group ID.
%h
Leading directories of file's name (all but the last element).If the file name contains no slashes (since it is in the currentdirectory) the %h specifier expands to ".".
%H
Starting-point under which file was found.
%i
File's inode number (in decimal).
%k
The amount of disk space used for this file in 1K blocks. Since disk space isallocated in multiples of the filesystem block size this is usually greaterthan %s/1024, but it can also be smaller if the file is a sparse file.
%l
Object of symbolic link (empty string if file is not a symbolic link).
%m
File's permission bits (in octal). This option uses the `traditional'numbers which most Unix implementations use, but if your particularimplementation uses an unusual ordering of octal permissions bits, youwill see a difference between the actual value of the file's mode andthe output of %m. Normally you will want to have a leadingzero on this number, and to do this, you should use the#flag (as in, for example, `%#m').
%M
File's permissions (in symbolic form, as forls).This directive is supported in findutils 4.2.5 and later.
%n
Number of hard links to file.
%p
File's name.
%P
File's name with the name of the starting-point under whichit was found removed.
%s
File's size in bytes.
%S
File's sparseness. This is calculated as (BLOCKSIZE*st_blocks /st_size). The exact value you will get for an ordinary file of acertain length is system-dependent. However, normally sparse fileswill have values less than 1.0, and files which use indirect blocksmay have a value which is greater than 1.0. The value used forBLOCKSIZE is system-dependent, but is usually 512 bytes. If the filesize is zero, the value printed is undefined. On systems which lacksupport for st_blocks, a file's sparseness is assumed to be 1.0.
%t
File's last modification time in the format returned by the C `ctime'function.
%Tk
File's last modification time in the format specified by k,which is the same as for %A.
%u
File's user name, or numeric user ID if the user has no name.
%U
File's numeric user ID.
%y
File's type (like inls -l),U=unknown type (shouldn't happen)
%Y
File's type (like %y), plus follow symlinks: L=loop, N=nonexistent
%Z
(SELinux only) file's security context.
%{ %[ %(
Reserved for future use.

A `%' character followed by any other character is discarded, but theother character is printed (don't rely on this, as further formatcharacters may be introduced). A `%' at the end of the formatargument causes undefined behaviour since there is no followingcharacter. In some locales, it may hide your door keys, while inothers it may remove the final page from the novel you are reading.

The %m and %d directives support the#,0and+flags, but the other directives do not, even if theyprint numbers. Numeric directives that do not support these flagsincludeG,U,b,D,kandn.The `-' format flag is supported and changes the alignment of a fieldfrom right-justified (which is the default) to left-justified.

See theUNUSUAL FILENAMESsection for information about how unusual characters in filenames are handled.

-prune
True; if the file is a directory, do not descend into it. If-depthis given, false; no effect. Because-deleteimplies-depth,you cannot usefully use-pruneand-deletetogether.
-quit
Exit immediately. No child processes will be left running, but no morepaths specified on the command line will be processed. For example,find /tmp/foo /tmp/bar -print -quitwill print only/tmp/foo.Any command lines which have been built up with-execdir ... {} +will be invoked beforefindexits. The exit status may or may not be zero, depending on whetheran error has already occurred.

OPERATORS

Listed in order of decreasing precedence:

(Video) Files, Folders, and Directory Structure

( expr )
Force precedence. Since parentheses are special to the shell, youwill normally need to quote them. Many of the examples in this manualpage use backslashes for this purpose: `\(...\)' instead of `(...)'.
! expr
True if expr is false. This character will also usually needprotection from interpretation by the shell.
-not expr
Same as ! expr, but not POSIX compliant.
expr1 expr2
Two expressions in a row are taken to be joined with animplied "and"; expr2 is not evaluated if expr1 is false.
expr1 -a expr2
Same as expr1 expr2.
expr1 -and expr2
Same as expr1 expr2, but not POSIX compliant.
expr1 -o expr2
Or; expr2 is not evaluated if expr1 is true.
expr1 -or expr2
Same as expr1-oexpr2, but not POSIX compliant.
expr1 , expr2
List; both expr1 and expr2 are always evaluated. Thevalue of expr1 is discarded; the value of the list is the valueof expr2. The comma operator can be useful for searching forseveral different types of thing, but traversing the filesystemhierarchy only once. The-fprintfaction can be used to list the various matched items into severaldifferent output files.

Please note that-awhen specified implicitly (for example by two tests appearing withoutan explicit operator between them) or explicitly has higher precedencethan-o.This means thatfind . -name afile -o -name bfile -printwill never printafile.

UNUSUAL FILENAMES

Many of the actions offindresult in the printing of data which is under the control of otherusers. This includes file names, sizes, modification times and soforth. File names are a potential problem since they can contain anycharacter except `\0' and `/'. Unusual characters in file names cando unexpected and often undesirable things to your terminal (forexample, changing the settings of your function keys on someterminals). Unusual characters are handled differently by variousactions, as described below.

-print0, -fprint0
Always print the exact filename, unchanged, even if the output isgoing to a terminal.
-ls, -fls
Unusual characters are always escaped. White space, backslash, anddouble quote characters are printed using C-style escaping (forexample `\f', `\"'). Other unusual characters are printed using anoctal escape. Other printable characters (for-lsand-flsthese are the characters between octal 041 and 0176) are printed as-is.
-printf, -fprintf
If the output is not going to a terminal, it is printed as-is.Otherwise, the result depends on which directive is in use. Thedirectives %D, %F, %g, %G, %H, %Y, and %y expand to values which arenot under control of files' owners, and so are printed as-is. Thedirectives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U havevalues which are under the control of files' owners but which cannotbe used to send arbitrary data to the terminal, and so these areprinted as-is. The directives %f, %h, %l, %p and %P are quoted. Thisquoting is performed in the same way as for GNUls.This is not the same quoting mechanism as the one used for-lsand-fls.If you are able to decide what format to use for the output offindthen it is normally better to use `\0' as a terminatorthan to use newline, as file names can contain white space and newlinecharacters. The setting of the `LC_CTYPE' environmentvariable is used to determine which characters need to be quoted.
-print, -fprint
Quoting is handled in the same way as for-printfand-fprintf.If you are usingfindin a script or in a situation where the matched files might havearbitrary names, you should consider using-print0instead of-print.

The-okand-okdiractions print the current filename as-is. This may change in a future release.

STANDARDS CONFORMANCE

For closest compliance to the POSIX standard, you should set thePOSIXLY_CORRECT environment variable. The following options arespecified in the POSIX standard (IEEE Std 1003.1, 2003 Edition):

-H
This option is supported.
-L
This option is supported.
-name
This option is supported, but POSIX conformance depends on thePOSIX conformance of the system'sfnmatch(3)library function. As of findutils-4.2.2, shell metacharacters(`*', `?' or `[]' for example) will match a leading `.', becauseIEEE PASC interpretation 126 requires this. This is a change fromprevious versions of findutils.
-type
Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'.GNU find also supports `D', representing a Door, where the OS provides these.Furthermore, GNU find allows multiple types to be specified at once in acomma-separated list.
-ok
Supported.Interpretation of the response is according to the "yes" and "no"patterns selected by setting the `LC_MESSAGES' environment variable.When the `POSIXLY_CORRECT' environment variable is set, these patternsare taken system's definition of a positive (yes) or negative (no)response. See the system'sdocumentation for nl_langinfo(3), in particular YESEXPR andNOEXPR. When `POSIXLY_CORRECT' is not set, the patterns are insteadtaken fromfind'sown message catalogue.
-newer
Supported. If the file specified is a symbolic link, it is alwaysdereferenced. This is a change from previous behaviour, which used totake the relevant time from the symbolic link; see the HISTORY sectionbelow.
-perm
Supported. If the POSIXLY_CORRECT environment variable is not set,some mode arguments (for example +a+x) which are not valid in POSIXare supported for backward-compatibility.
Other predicates
The predicates-atime,-ctime,-depth,-group,-links,-mtime,-nogroup,-nouser,-print,-prune,-size,-userand-xdev`-atime',`-ctime',`-depth',`-group',`-links',`-mtime',`-nogroup',`-nouser',`-perm',`-print',`-prune',`-size',`-user' and`-xdev',are all supported.

The POSIX standard specifies parentheses `(', `)', negation `!' and the`and' and `or' operators (-a,-o).

All other options, predicates, expressions and so forth are extensionsbeyond the POSIX standard. Many of these extensions are not unique toGNU find, however.

The POSIX standard requires thatfinddetects loops:

Thefindutility shall detect infinite loops; that is, entering apreviously visited directory that is an ancestor of the last fileencountered. When it detects an infinite loop, find shall write adiagnostic message to standard error and shall either recover itsposition in the hierarchy or terminate.

GNUfindcomplies with these requirements. The link count ofdirectories which contain entries which are hard links to an ancestorwill often be lower than they otherwise should be. This can mean thatGNU find will sometimes optimise away the visiting of a subdirectorywhich is actually a link to an ancestor. Sincefinddoes not actually enter such a subdirectory, it is allowed to avoidemitting a diagnostic message. Although this behaviour may besomewhat confusing, it is unlikely that anybody actually depends onthis behaviour. If the leaf optimisation has been turned off with-noleaf,the directory entry will always be examined and the diagnostic messagewill be issued where it is appropriate. Symbolic links cannot be usedto create filesystem cycles as such, but if the-Loption or the-followoption is in use, a diagnostic message is issued whenfindencounters a loop of symbolic links. As with loops containing hardlinks, the leaf optimisation will often mean thatfindknows that it doesn't need to callstat()orchdir()on the symbolic link, so this diagnostic is frequently not necessary.

The-doption is supported for compatibility with various BSD systems,but you should use the POSIX-compliant option-depthinstead.

The POSIXLY_CORRECT environment variable does not affect the behaviourof the-regexor-iregextests because those tests aren't specified in the POSIX standard.

ENVIRONMENT VARIABLES

LANG
Provides a default value for the internationalization variables thatare unset or null.
LC_ALL
If set to a non-empty string value, override the values of all theother internationalization variables.
LC_COLLATE
The POSIX standard specifies that this variable affects the patternmatching to be used for the-nameoption. GNU find uses thefnmatch(3)library function, and so support for `LC_COLLATE' depends on thesystem library. This variable also affects the interpretation ofthe response to-ok;while the `LC_MESSAGES' variable selects the actual pattern used tointerpret the response to-ok,the interpretation of any bracket expressions in the pattern will beaffected by `LC_COLLATE'.
LC_CTYPE
This variable affects the treatment of character classes used inregular expressions and also withthe-nametest, if the system'sfnmatch(3)library function supports this. This variable also affects theinterpretation of any character classes in the regular expressionsused to interpret the response to the prompt issued by-ok.The `LC_CTYPE' environment variable willalso affect which characters are considered to be unprintable whenfilenames are printed; see the section UNUSUAL FILENAMES.
LC_MESSAGES
Determines the locale to be used for internationalised messages. Ifthe `POSIXLY_CORRECT' environment variable is set, this alsodetermines the interpretation of the response to the prompt made by the-okaction.
NLSPATH
Determines the location of the internationalisation message catalogues.
PATH
Affects the directories which are searched to find the executablesinvoked by-exec,-execdir,-okand-okdir.
POSIXLY_CORRECT
Determines the block size used by-lsand-fls.IfPOSIXLY_CORRECTis set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes.
Setting this variable also turns offwarning messages (that is, implies-nowarn)by default, because POSIX requires that apart fromthe output for-ok,all messages printed on stderr are diagnostics and must result in anon-zero exit status.
When POSIXLY_CORRECT is not set,-perm+zzzis treated just like-perm/zzzif+zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, suchconstructs are treated as an error.
When POSIXLY_CORRECT is set, the response to the prompt made by the-okaction is interpreted according to the system's message catalogue, asopposed to according tofind'sown message translations.
TZ
Affects the time zone used for some of the time-related formatdirectives of-printfand-fprintf.

EXAMPLES

find /tmp -name core -type f -print | xargs /bin/rm -f

Find files namedcorein or below the directory/tmpand delete them. Note that this will work incorrectly if there areany filenames containing newlines, single or double quotes, or spaces.

find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f

Find files namedcorein or below the directory/tmpand delete them, processing filenames in such a way that file ordirectory names containing single or double quotes, spaces or newlinesare correctly handled. The-nametest comes before the-typetest in order to avoid having to callstat(2)on every file.

(Video) Find the 10 largest files in a directory tree

find . -type f -exec file '{}' \;

Runs `file' on every file in or below the current directory. Noticethat the braces are enclosed in single quote marks to protect themfrom interpretation as shell script punctuation. The semicolon issimilarly protected by the use of a backslash, though single quotescould have been used in that case also.

find / \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \\( -size +100M -fprintf /root/big.txt '%-10s %p\n' \)

Traverse the filesystem just once, listing setuid files anddirectories into/root/suid.txtand large files into/root/big.txt.

find $HOME -mtime 0

Search for files in your home directory which have been modified inthe last twenty-four hours. This command works this way because thetime since each file was last modified is divided by 24 hours and anyremainder is discarded. That means that to match-mtime0,a file will have to have a modification in the past which is less than24 hours ago.

find /sbin /usr/sbin -executable \! -readable -print

Search for files which are executable but not readable.

find . -perm 664

Search for files which have read and write permission for their owner,and group, but which other users can read but not write to. Fileswhich meet these criteria but have other permissions bits set (forexample if someone can execute the file) will not be matched.

find . -perm -664

Search for files which have read and write permission for their ownerand group, and which other users can read, without regard to thepresence of any extra permission bits (for example the executablebit). This will match a file which has mode 0777, for example.

find . -perm /222

Search for files which are writable by somebody (their owner, ortheir group, or anybody else).

find . -perm /220find . -perm /u+w,g+wfind . -perm /u=w,g=w

All three of these commands do the same thing, but the first one usesthe octal representation of the file mode, and the other two use thesymbolic form. These commands all search for files which arewritable by either their owner or their group. The files don't haveto be writable by both the owner and group to be matched; either willdo.

find . -perm -220find . -perm -g+w,u+w

Both these commands do the same thing; search for files which arewritable by both their owner and their group.

find . -perm -444 -perm /222 ! -perm /111find . -perm -a+r -perm /a+w ! -perm /a+x

These two commands both search for files that are readable foreverybody (-perm -444or-perm -a+r),have at least one write bitset (-perm /222or-perm /a+w)but are not executable for anybody (! -perm /111and! -perm /a+xrespectively).

cd /source-dirfind . -name .snapshot -prune -o \( \! -name *~ -print0 \)|cpio -pmd0 /dest-dir

This command copies the contents of/source-dirto/dest-dir,but omits files and directories named.snapshot(and anything in them). It also omits files or directories whose nameends in~,but not their contents. The construct-prune -o \( ... -print0 \)is quite common. The idea here is that the expression before-prunematches things which are to be pruned. However, the-pruneaction itself returns true, so the following-oensures that the right hand side is evaluated only for thosedirectories which didn't get pruned (the contents of the pruneddirectories are not even visited, so their contents are irrelevant).The expression on the right hand side of the-ois in parentheses only for clarity. It emphasises that the-print0action takes place only for things that didn't have-pruneapplied to them. Because the default `and' condition between testsbinds more tightly than-o,this is the default anyway, but the parentheses help to showwhat is going on.

find repo/ \( -exec test -d {}/.svn \; -or \-exec test -d {}/.git \; -or -exec test -d {}/CVS \; \) \-print -prune

Given the following directory of projects and their associated SCMadministrative directories, perform an efficient search for theprojects' roots:

repo/project1/CVSrepo/gnu/project2/.svnrepo/gnu/project3/.svnrepo/gnu/project3/src/.svnrepo/project4/.git

In this example,-pruneprevents unnecessary descent into directories that have already beendiscovered (for example we do not search project3/src because wealready found project3/.svn), but ensures sibling directories(project2 and project3) are found.

find /tmp -type f,d,l

Search for files, directories, and symbolic links in the directory/tmppassing these types as a comma-separated list (GNU extension),which is otherwise equivalent to the longer, yet more portable:

find /tmp \( -type f -o -type d -o -type l \)

EXIT STATUS

findexits with status 0 if all files are processed successfully, greaterthan 0 if errors occur. This is deliberately a very broaddescription, but if the return value is non-zero, you should not relyon the correctness of the results offind.

When some error occurs,findmay stop immediately, without completing all the actions specified.For example, some starting points may not have been examined or somepending program invocations for-exec ... {} +or-execdir ... {} +may not have been performed.

(Video) Directory Structure | tree structured directory | acyclic graph directory | operating system | files

HISTORY

As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' forexample) used in filename patterns will match a leading `.', becauseIEEE POSIX interpretation 126 requires this.

As of findutils-4.3.3,-perm /000now matches all files instead of none.

Nanosecond-resolutiontimestamps were implemented in findutils-4.3.3.

As of findutils-4.3.11, the-deleteaction setsfind'sexit status to a nonzero value when it fails.However,findwill not exit immediately. Previously,find'sexit status was unaffected by the failure of-delete.

FeatureAdded inAlso occurs in
-newerXY4.3.3BSD
-D4.3.1
-O4.3.1
-readable4.3.0
-writable4.3.0
-executable4.3.0
-regextype4.2.24
-exec ... +4.2.12POSIX
-execdir4.2.12BSD
-okdir4.2.12
-samefile4.2.11
-H4.2.5POSIX
-L4.2.5POSIX
-P4.2.5BSD
-delete4.2.3
-quit4.2.3
-d4.2.3BSD
-wholename4.2.0
-iwholename4.2.0
-ignore_readdir_race4.2.0
-fls4.0
-ilname3.8
-iname3.8
-ipath3.8
-iregex3.8

The syntax.B -perm +MODEwas removed in findutils-4.5.12, in favour of.B -perm/MODE.The+MODEsyntax had been deprecated since findutils-4.2.21which was released in 2005.

NON-BUGS

Operator precedence surprises

The commandfind . -name afile -o -name bfile -printwill never printafilebecause this is actually equivalent tofind . -name afile -o \( -name bfile -a -print \).Remember that the precedence of-ais higher than that of-oand when there is no operator specified between tests,-ais assumed.

"paths must precede expression" error message

$ find . -name *.c -printfind: paths must precede expressionUsage: find [-H] [-L] [-P] [-Olevel] [-D ... [path...] [expression]

This happens because*.chas been expanded by the shellresulting infindactually receiving a command line like this:

find . -name frcode.c locate.c word_io.c -print

That command is of course not going to work. Instead of doing thingsthis way, you should enclose the pattern in quotes or escape the wildcard:

$ find . -name '*.c' -print$ find . -name \*.c -print

BUGS

There are security problems inherent in the behaviour that the POSIXstandard specifies forfind,which therefore cannot be fixed. For example, the-execaction isinherently insecure, and-execdirshould be used instead.Please see Finding Files for more information.

The environment variableLC_COLLATEhas no effect on the-okaction.

The best way to report a bug is to use the form athttp://savannah.gnu.org/bugs/?group=findutils.The reason for this is that you will then be able to track progress infixing the problem. Other comments about find(1) and aboutthe findutils package in general can be sent to thebug-findutilsmailing list. To join the list, send email to[emailprotected].

FAQs

Which command searches for files in a directory hierarchy? ›

The find command is one of the most powerful tools in the Linux system administrators arsenal. It searches for files and directories in a directory hierarchy based on a user given expression and can perform user-specified action on each matched file.

How do I get a list of files in a specific directory? ›

-
  1. To list all files in the current directory, type the following: ls -a This lists all files, including. dot (.) ...
  2. To display detailed information, type the following: ls -l chap1 .profile. ...
  3. To display detailed information about a directory, type the following: ls -d -l .

How do I get a list of files in a directory and subfolders? ›

Steps
  1. Open File Explorer in Windows. ...
  2. Click in the address bar and replace the file path by typing cmd then press Enter.
  3. This should open a black and white command prompt displaying the above file path.
  4. Type dir /A:D. ...
  5. There should now be a new text file called FolderList in the above directory.

What is directory hierarchy? ›

Files are grouped into directories, and directories are organized in a hierarchy. At the top of the hierarchy is the “root” directory, symbolized by “ / ”. In the following example, Figure 3–1, each directory in the file system contains many subdirectories. The / character distinguishes directory levels.

How do I search for a file in all directories in Linux? ›

Basic Examples
  1. find . - name thisfile.txt. ...
  2. find /home -name *.jpg. Look for all .jpg files in the /home and directories below it.
  3. find . - type f -empty. ...
  4. find /home -user randomperson-mtime 6 -iname ".db"
Apr 5, 2021

What is the hierarchical collection of directories and files? ›

A hierarchical file system is how drives, folders, files, and other storage devices are organized and displayed on an operating system. In a hierarchical file system, the drives, folders, and files are displayed in groups, which allows the user to see only the files they're interested in seeing.

How can I get a list of all the subfolders and files present in a directory using PHP? ›

PHP using scandir() to find folders in a directory

The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.

How do you get a list of all files in a directory and its subdirectories in Java? ›

Algorithm :
  1. Create a File object for the main directory.
  2. Get an array of files for the main directory.
  3. If array[i] is a file: Print out the file name.
  4. If array[i] is a directory : Print out directory name. Get array of files for current sub-directory. ...
  5. Repeat the step 3 and 4 with next array[i].
Jan 26, 2022

What does files list () method do? ›

list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.

How to get a list of all files in a folder and subfolders without path? ›

The command DIR /b will return just a list of filenames, when displaying subfolders with DIR /b /s the command will return a full pathname. To list the full path without including subfolders, use the WHERE command.

How do you get a list of the names of all files present in a directory in node JS? ›

Method 1: Using fs.

readdirSync() is a method that is available in the file system module of Node. js. It is used for reading the contents of a directory. It returns an array of file paths, buffers, or fs.

How to list all files in a directory recursively in Linux? ›

ls -R : Use the ls command to get recursive directory listing on Linux. find /dir/ -print : Run the find command to see recursive directory listing in Linux. du -a . : Execute the du command to view recursive directory listing on Unix.

How do I create a directory hierarchy? ›

Follow these five steps to set up the folder hierarchy.
  1. Define the Structure. The first step in setting up the folder hierarchy is deciding the hierarchy for the folder or directory tree. ...
  2. Name and Describe the Folders. ...
  3. Define Folder Security. ...
  4. Create the Hierarchy. ...
  5. Set the Mount Points.

Which command is used to show the directories in hierarchical form? ›

The directories on the computer are arranged into a hierarchy. The full path tells you where a directory is in that hierarchy. Navigate to the home directory, then enter the pwd command.

What is file directory structure? ›

What is directory structure? The directory structure is the organization of files into a hierarchy of folders. It should be stable and scalable; it should not fundamentally change, only be added to. Computers have used the folder metaphor for decades as a way to help users keep track of where something can be found.

How do I search for multiple files in a directory in Linux? ›

So you want to search multiple directories with the find command under Linux or Unix? The syntax to search multiple folder is: find /dir1 /dir2 -type f -name "pattern" . This is useful when you need to search many folders or directories but not all folders.

How to search specific text in multiple files in a directory Linux? ›

How to use the grep tool
  1. Make the search case-insensitive with the "-i" option: ...
  2. Search recursively in all files in a given directory with the "-r" option: ...
  3. Search whole words only with the "-w" option: ...
  4. Print the line numbers in which the searched word was found with the "-n" option: ...
  5. Search for multiple words syntax:
Nov 17, 2021

How to find a file in Linux in all directories using grep? ›

You can make grep search in all the files and all the subdirectories of the current directory using the -r recursive search option: grep -r search_term .

What is an example of a hierarchy of data? ›

Examples of the hierarchical data that is commonly stored in databases include the following: An organizational structure. A file system. A set of tasks in a project.

What are the 2 types of hierarchical structure? ›

How many types of organizational structures are there? In your research, you may at first read that there are two types of organizational structures: centralized and decentralized. However, using just these two classifications for every possible team structure may paint with too broad a brush.

What is the name of hierarchical file system? ›

Hierarchical File System
Developer(s)Apple Computer
Full nameHierarchical File System
IntroducedSeptember 17, 1985 with System 2.1
Partition identifierApple_HFS (Apple Partition Map) 0xAF (MBR) HFS and HFS+
Structures
20 more rows

How do you display the count of all files and folders in current directory? ›

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1.

Which of the following command is used to list the content of all subdirectories? ›

ls -R gives a recursive listing, including the contents of all subdirectories and their subdirectories and so on.

Which command is used to list files in a directory and all subdirectory in your current directory? ›

The ls (list) command is used to display the names of the files and subdirectories in the current directory.

Which command is used to search all directory and subdirectories? ›

The find command will begin looking in the starting directory you specify and proceed to search through all accessible subdirectories.

How to search all files inside a directory in Java? ›

Searching files in Java can be performed using the File class and FilenameFilter interface. The FilenameFilter interface is used to filter files from the list of files. This interface has a method boolean accept(File dir, String name) that is implemented to find the desired files from the list returned by the java. io.

Which of the following commands displays all entries in all subdirectories of path? ›

-lsr <path>

Behaves like -ls, but recursively displays entries in all subdirectories of path.

What are the 6 basic file operations? ›

Six basic file operations. The OS can provide system calls to create, write, read, reposition, delete, and truncate files.
...
File Operations
  • Creating a file. ...
  • Writing a file. ...
  • Reading a file. ...
  • Repositioning within a file. ...
  • Deleting a file. ...
  • Truncating a file.

What are the three ways of searching files in Windows 10? ›

Find your documents in Windows
  1. Search from the taskbar: Type the name of a document (or a keyword from it) into the search box on the taskbar. ...
  2. Search File Explorer: Open File Explorer from the taskbar or select and hold the Start menu (or right-click), select File Explorer , then select a search location:

What are the different types of list methods? ›

Python List/Array Methods
MethodDescription
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
7 more rows

Which command is used to show hierarchy? ›

Pstree command in Linux that shows the running processes as a tree which is a more convenient way to display the processes hierarchy and makes the output more visually appealing. The root of the tree is either init or the process with the given pid. Pstree can also be installed in other Unix systems.

What is in the Linux directory hierarchy? ›

Primary hierarchy root and root directory of the entire file system hierarchy. Essential command binaries that need to be available in single user mode; for all users, e.g., cat, ls, cp. Boot loader files, e.g., kernels, initrd. Device files, e.g., /dev/null , /dev/disk0 , /dev/sda1 , /dev/tty , /dev/random.

What is the hierarchy for the Linux file system? ›

1. / (Root): Primary hierarchy root and root directory of the entire file system hierarchy. 2. /bin : Essential command binaries that need to be available in single-user mode; for all users, e.g., cat, ls, cp. Common linux commands you need to use in single-user modes are located under this directory.

Which command walks a file hierarchy in search of a keyword? ›

The find command in UNIX is a command line utility for walking a file hierarchy. It can be used to find files and directories and perform subsequent operations on them. It supports searching by file, folder, name, creation date, modification date, owner and permissions.

How do you show hierarchy data? ›

Hierarchical data is shown in tree graphs; so called because of their similarity to a tree's structure (though a tree which has been turned upside down so that the root is at the top and the branches form below it).

How do you find the hierarchy? ›

To view a type in the Type Hierarchy view: Through the "Open Type in Hierarchy" wizard: Press Ctrl+Shift+H -or- from the Menu Bar go to Navigate | Open Type in Hierarchy. The "Open Type in Hierarchy" dialog is displayed.

How do you view a hierarchy? ›

Start Hierarchy Viewer
  1. Connect your device to your computer. ...
  2. Open your project in Android Studio, build and run it on your device.
  3. Start Android Device Monitor. ...
  4. In the menu bar, select Window > Open Perspective, and then click Hierarchy View. ...
  5. Double-click your app's package name in the Windows tab on the left.
Dec 2, 2022

What are 5 main directory commands Linux? ›

Linux Directory Commands
  • pwd Command. The pwd command is used to display the location of the current working directory. ...
  • mkdir Command. The mkdir command is used to create a new directory under any directory. ...
  • rmdir Command. The rmdir command is used to delete a directory. ...
  • ls Command. ...
  • cd Command.

What is Linux file hierarchy structure explain with diagram? ›

Filesystem hierarchy standard describes directory structure and its content in Unix and Unix like operating system.
...
Linux Directories.
Directory typeTypes of files stored
Binary directoriesContains binary or compiled source code files, eg, /bin, /sbin, etc.
6 more rows

What is a folder within a folder called in a hierarchy? ›

Subfolders are folders within folders, and subfolders can contain many subfolders. In fact, you can create a hierarchy of folders within folders within folders, and so on.

What are the two types of the files found in the filesystem hierarchy standard? ›

Historical UNIX-like filesystem hierarchies contained both static and variable files under both /usr and /etc .

Which among the command can be used for searching a file? ›

You can use the find command to search for a file or directory on your file system.

Which command allows you to see the contents of a directory sorted by filesize? ›

List files and sort by file size. Type the ls -S (the S is uppercase) command to list files or directories and sort by size in descending order (biggest to smallest).

Which of the following command is used to find all text files in directory? ›

Detailed Solution. *. txt is the command used to search all the text files in any drive.

Videos

1. CompTIA A+ 220-601 (3.1), 220-602 (3.1) - Directory Structures and Files
(Professor Messer)
2. Board of Supervisors Meeting - January 24, 2023
(County of Ventura Government)
3. UNIX Programming (Part - 16) The File System (The Directory Hierarchy)
(ITUTEES)
4. How can I find the oldest file in a directory tree? (7 Solutions!!)
(Roel Van de Paar)
5. Productivity Hack: Streamline Folder Structure Creation in Finder with this Mac Shortcut!
(A Creative Opinion)
6. Understanding the File And Folder Structure Of Your Mac
(macmostvideo)
Top Articles
Latest Posts
Article information

Author: Lidia Grady

Last Updated: 11/12/2022

Views: 5821

Rating: 4.4 / 5 (45 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.