There is always a time when working with the CLI that you will want to find a set of files by name, such as all JPEG images. The `find` command lets you do this and more. Let's jump into the basic structure of a find command:
find starting-folder find-files action
The first word, find, is obviously the command itself. Starting-folder is the directory that you want to start looking in, such as /home. Find-files tells find what you are looking for. This could be composed of a pattern of names, file modification dates, permissions, you name it. Action is what will happen when the files are found. "-print" is the most common action.
To start, here is an example of a simple find command:
find /home -name '*.jpg' -print
Let's split the command into pieces:
- The find command itself.
- /home, where we want to search in (recursive).
- -name '*.jpg' tells find to look for all files that end in .jpg.
- -print tells find to simply output what it finds in the terminal.
Before we get into any actions on what find can do, let's start with some available options for finding files. You can find these and a lot more in the command man find.
- -name pattern - Like above, pattern is a shell pattern detailing what you want to find in the name.
- -iname pattern - Case-insensitive version of -name.
- -regex pattern - Like -name, but supports regular expressions.
- -size n - The file size is exactly n. n can be something like "20M" for 20 megabytes, or "12k" for 12 kilobytes. See the manual page for more info.
- -type c - The file is of type c, which can be:
- d - directory
- f - regular file
- l - symbolic link
- -user name - the file is owned by user name.
- -group name - file is owned by group name.
Now, what if you want to act upon a certain file when it is found? You can do it with these actions (again, more are in man find).
- -print - output the files found
- -delete - delete the files when found
- -exec command \; - executes command each time a file is found. Note the \; is required.
- -exec command '{}' \; - executes command using '{}' as parameters. '{}' is never actually ran as a parameter in command, it is replaced by the file found. Explained in the example below.
find /home -name '*.sh' -exec chmod +x '{}' \;
- find /home -name '*.sh' finds all files ending in .sh in /home recursively.
- -exec starts the action.
- chmod +x is the command we want to run, in this case, add execute permission.
- '{}' is where the filename will go when find finds a file.
- \; is the required ending sequence of -exec.
When ran, every time a .sh file is found, chmod +x will be run on the file. For example, if /home/jacob/script.sh is found, the following command will be automatically run:
chmod +x '/home/jacob/script.sh'
The -exec command can be invaluable when dealing with large amounts of files.
find is incapable of searching inside files however. We'll cover that in the next part of this tutorial using a command called grep.