THE find
The command is used to search and locate files and directories based on specified conditions such as file name, size, date modified, and other attributes. You can use it to search the entire file system or within a specific directory.
It is commonly used by system administrators and regular users to quickly locate files, especially in systems with large numbers of files. If you are looking for a lost document or need to perform mass operations on a set of files that meet certain criteria, the file find
The command can be an essential tool for managing and organizing your file system.
General syntax for find
command:
$ find [OPTIONS] [PATH...] [EXPRESSION]
1. Search for a specific file in a directory
find ./ExampleDir -name example.txt
With the -name
parameter, this command will attempt to search for a file example.txt
inside the ExampleDir
list; and if found, it will return the path to the file.
./ExampleDir/subdir1/example.txt ./ExampleDir/subdir2/subsubdir/example.txt
2. Find and list files with the same extension
find ./dirname -name *.txt
This command will search, within ExampleDir
directory, all files ending with the extension .txt
. If found, each result will be returned in a new line.
./dirname/file1.txt ./dirname/file2.txt ./dirname/subdir/file3.txt ./dirname/subdir/another_subdir/file4.txt
3. Find and list empty files and empty subdirectories
find ./ExampleDir -empty
This command, with the -empty
parameter, it will find and list all empty files AND empty subfolders inside the ExampleDir
folder.
Definition of empty file being a file size of 0 bytes and empty folder not being files or files with 0 bytes.
4. Find and list files that contain specific text
find ./ExampleDir -type f -name "*.txt" -exec grep 'Example' {} \;
This command searches for the word/string “Example” in files with extension .txt
inside ExampleDir
directories.
./ExampleDir/file1.txt:This is an Example line in file1. ./ExampleDir/subdir/file2.txt:Another Example in a different file. ./ExampleDir/file3.txt:Example usage of the find command.
5. Find and list files and subdirectories owned by a specific user
find ./ExampleDir -user ubuntu
This command, with the -user
parameter, it will find files and subdirectories owned by Ubuntu
user in ExampleDir
directories. If found, the filenames will be returned.
In the following example ls -l
result:
-rw-rw-r-- 1 newone ubuntu 20 Jan 27 06:24 example.txt
newone
represents group name is ubuntu
and the user.
6. Find and list files and subdirectories belonging to a specific group
find ./ExampleDir -group ubuntu
This command, with the -group
parameter, it will find all files and subdirectories owned by Ubuntu
group inside ExampleDir
directories. If found, the filenames will be returned.