Learn GNU/Linux Commands (14): Search Files - locate, find
We introduce 2 widely-used programs for searching files, "locate" and "find".
"locate" searches in the database(s) (caches) updated by "updatedb", which is usually run daily by "cron" to update the default database. "find" searches real-time. So "locate" is faster, but sometimes the results may be outdated.
locate
locate [OPTION]... PATTERN...
Search for PATTERNS in a database about the pathnames of all regular files and directories stored in the system.
"locate" options:
- -A, --all: each result must match all patterns at the same time. (Not the default)
- -w, --wholename: match whole path name (the default)
- -b, --basename: match only the file names (base names) instead of the whole pathnames. Opposite to "-w".
- -c, --count: print number of found entries instead of the pathnames.
Update the Database Manually
updatedb
This command needs to be run with administration privileges (as root or sudoers).
find
find [PATH...] [TEST]
"find" is a powerful program. It can search by files' name or attributes. If PATH is not specified, the default is the current directory. To search files under a directory, the user needs the read permission of that directory. We introduce some of the functions of "find" below.
In this section, N is an integer.
- There can be a "+" before N as "+N" for greater than N.
- There can be a "-" before N as "-N" for less than N.
Search by File Name
find [PATH...] -name PATTERN
"-name": case sensitive. PATTEN is a shell pattern, it should not include slashes (/).
find [PATH...] -iname PATTERN
"-iname": case insensitive.
Search by Pathname
find [PATH...] -path PATTERN
"-name": case sensitive. PATTERN is a shell pattern, the metacharacters do not treat `/' or `.' specially.
find [PATH...] -ipath PATTERN
"-iname": case insensitive.
Search by Size
find [PATH...] -size N
There needs to be a unit after N.
- "c" for bytes.
- "k" for Kilobytes (units of 1024 bytes).
- "M" for Megabytes (units of 1048576 bytes).
- "G" for Gigabytes (units of 1073741824 bytes).
- "b" for 512-bytes blocks (the default).
Note that when matching, each files' size is rounded up to the unit of N. So a 1-byte file is not matched by "-size -1M" as it is rounded up as "0M"
Search by Accessed Time
find [PATH...] -amin N
Search for files that were last accessed N minutes ago.
find [PATH...] -atime N
Search for files that were last accessed N*24 hours ago. Any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago.
Search by Changed (Modified) Time
find [PATH...] -cmin N
Search for files that were last changed N minutes ago.
find [PATH...] -ctime N
Search for files that were last changed N*24 hours ago. Any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago.
Search by User
find [PATH...] -user name_or_id
Search by Group
find [PATH...] -group name_or_id
Comments
Post a Comment