If you’re looking for a file but don’t know where it is, the find command can help. Here’s how to use this powerful and versatile tool.
Have you ever been unable to locate a file because you couldn’t recall where you stored it, much alone the filename? The Bash find command on Linux can help you search your system for that file.
In Linux, the find command in Bash provides a variety of options for searching for files and directories. In this video, you’ll learn how to use the Bash search command to discover files and directories based on their last-time access, permissions, and more. Let’s get this party started!
If you want to follow along with the examples in this lesson, you’ll need the following:
- A Linux computer – Ubuntu 20.04 is used in this tutorial, but any Linux distribution should work.
- The find utility – All Linux distributions should already have the Bash find utility installed. v4.7.0 is used in this lesson.
Command 101 is found by the Bash.
Finding a file requires the use of certain criteria, such as a portion of the file name, the file type, and the file’s rights. The locate command lets you provide those criteria to find the specific file(s) you’re looking for. Symbolic connections are also found or searched for using the find command (symlink). A symbolic link is a Linux shortcut file that directs your computer to another file or location. Let’s start with the most basic application of the search command in Bash.
Perhaps you’re searching for a directory called snap and all files and subdirectories beneath it in your home directory. In such instance, just type locate followed by the name of the directory (“snap”), and you’re done!
You can see the list of files and directories discovered recursively within the snap directory since there are no additional command line parameters below.
Finding and listing the contents of a directory (snap)
If the name option isn’t specified, find will presume that the first argument is for the name parameter, thus find “snap” is the same as find -name “snap.”
Obtaining Tests-Included Files (aka Filters)
You’ve seen how the find command works in its most basic form. However, you may choose to limit your search to set more particular criteria. If that’s the case, you’ll need to conduct testing. The criteria you supply to the find command are known as tests.
Tests instruct the find command to filter the results using a variety of criteria.
Using the File or Directory Name to Locate Files
Perhaps you simply recall how the file’s name begins, perhaps without regard for case. In this scenario, a wildcard may be used to assist limit down the results.
# find -name “snap*” -name “snap*” -name “snap*” -name “snap*” -name “snap*” -name “snap*” # in case insensitive way (for example:’Snap’,’snap’, ‘SNaP’, etc.) # find files and folders with names beginning with’snap’ “snap*” locate -iname
Using the -name Test to locate files and directories
Using File Types to Locate Files and Directories
The -type test, like the -name test, is a quick method to discover files and folders. The -type test allows you to filter the find command’s output by either files or directories.
# find “snap” -type f find “snap” -type f find “snap” -type f find “snap” -type f find “snap” # find “snap” -type d find “snap” -type d find “snap” -type d find “snap” -type d find “snap”
The -type Test may be used to find either files or directories.
Run the command below to combine the -name and -type tests to limit down the file search even further.
The find command below searches exclusively for directories (-type d) with names (-name) that begin with the letter “snap.”
locate -type d -name “snap*”
locating a directory with a name that begins with the letter’snap’
Using Tests and Operators to Locate Files and Directories
It’s time to step up your file-searching game now that you’ve mastered the fundamentals of the find command and completed the exams. You may need to look for files or folders that fit many criteria, such as name and file type. You’ll need to mix conditions in such scenario.
You may combine conditions with operators to identify files when you need to add more than one condition. Operators are components that let you combine conditions to create more complicated tests and filters.
Using the -and Operator to Combine Two Conditions
Perhaps you need to locate certain files or folders that have the same name and type as something else. You may achieve this by using the -and operator. The -and operator joins two or more expressions and only displays the result if the find command returns a true value. Expressions express specific criteria, for as when filtering files by name (-name “snap”).
Run each of the instructions below to see how the -and operator combines two criteria.
# Only look for files (-type f) in the current directory and subdirectories, and make sure the names (-name) start with snap #. type f and locate -name “snap*” # Only look for directories (-type d) and (-and) make sure the names (-name) in the current directory and subdirectories start with snap #. type d and locate -name “snap*” # Only look for files that begin with snap (-type f) and (-and) make sure the names (-name) start with snap. type f and locate -name “snap” # Only look for directories (-type d) and make sure the names (-name) begin with snap. -type d -find -name “snap”
Using the -and Operator to Locate Files and Directories
Using the -or Operator to Combine Two Conditions
The -or operator (-o), like the -and operator, combines two distinct statements. The find command differs in that it will return results even if just one expression is true.
The following is a simple syntax for using the -or operator to combine two criteria. Even if just one, either expr1 or expr2, returns a true value, the search command prints the result.
You could want to use the -name option to search a file name of a specified kind using the -type parameter. If that’s the case, use the search command to discover files (-type f) with names (-name) that begin with snap -or chart.
find -name “snap*” -type f -or “chart*” find -name “snap*” -type f -or “chart*” find -name “snap*” –
locating files with names that begin with either snap or chart
Using the -not Operator to Remove Files
The -not operator (!) is the polar opposite of the preceding two operators, which filter the items you’re searching for. The -not operator eliminates files and directories from the search results that you don’t wish to view.
Maybe you just want to look for files with names that don’t begin with a certain letter. In such situation, use the command below. The find command below searches exclusively for files (-type f) with names (-name) that do not begin with snap.
-type f find -not -name “snap*”
Using the -not Operator to exclude files and directories from a search result
Grouping Expressions to Find Files
You’ve now learnt how to use tests and operators to filter the results of the search command. But what if your desired outcome is a little more complicated? If this is the case, you should investigate grouping expressions. The search command in Bash enables you to group expressions, which means you may create two or more “sets” of criteria.
Using Parentheses to Group Expressions
Assume you need to locate files or folders with various names. Using the principles of the search command, as discussed before, you’ll quickly discover the assignment difficult. You’ll need to utilize parentheses to combine the expressions into a single complicated expression as a solution.
In the example below, the find command will seek for files with the.html extension (-type f) or folders with names that begin with chart (-type d).
To enable the terminal to interpret the parentheses literally, both open and closing parentheses are escaped by a backslash (). The escape character instructs the find command to consider the character as if it were a literal character.
(-name “*.html” -type f) or (-name “chart*” -type d) to find (-name “*.html” -type f) or (-name “chart*” -type d)
Grouping Expressions to Find Files with Parenthesis
Rather than using parentheses, you can also use commas to group expressions like locate -type d -name “snap*” -delete, -name “chart*” -print. Grouping expressions by commas is basically a running series of tasks in a single command.
Searching the Parent Directory for Files
The Bash find command only discovered files in the current working directory and all subdirectories in the previous examples. However, it’s possible that you should begin your search in the parent directory. If that’s the case, use the -depth option. As demonstrated below, the -depth argument lists files and directories in depth-first order.
The contents of the parent directory are listed first, followed by the contents of the working directory in the find command below (snap).
Finding Files in the Working Directory from the Parent Directory
Using Permissions to Locate Files and Directories
Instead than searching for files based on their name or type, the find command may instead search for files and directories based on their permissions. Every file and folder in Linux has rights assigned to it by the owner, group owner, and other users. With the -perm option, the find command allows you use those permissions to narrow the search results for files and directories.
Users and File Permissions: A Windows Guy in a Linux World
You should learn about reading permissions before attempting to search files and directories using the -perm option. Permissions specify who has access to and may alter which files and folders.
Using Symbolic Mode to Locate Files
Try searching for files in symbolic mode now that you’ve grasped the notion of file permissions. The symbolic mode represents file permissions using a mix of characters and symbols.
Run each of the commands below to see how to discover files using symbolic mode.
# in the current find, locate only files (-type f) in the working directory (.) # with read, write, and execute rights for user, group, and others -type f -perm u=rwx,g=rwx,o=rwx # Location files (-type f) in the current find in the working directory (.) # with any of the read, write, and execute permissions (not the exact) for user, group, and others. -perm -u=rwx,g=rwx,o=rwx -type f -perm -u=rwx,g=rwx,o=rwx # Find files in the working directory (.) where either the user, group, or others # have read, write, or execute access (including hidden files). -type f /u=rwx,g=rwx,o=rwx -perm /u=rwx,g=rwx,o=rwx
how to use symbolic mode to search files
Using Absolute Mode is a mode that allows you to do everything to Locate Files and Directories
If you don’t like using symbolic mode to discover files, Absolute Mode is a mode that allows you to do everything could be for you. Absolute Mode is a mode that allows you to do everything uses octal numeric representation to specify permissions rather than letters.
The symbolic mode -rwxrwxrwx is identical to the Absolute Mode is a mode that allows you to do everything 777, as seen below.
Absolute Mode is a mode that allows you to do everything
Let’s say you only want to find files and directories with read-only permission for user, group and, others. If so, run each of the commands below to see the results you’ll get when Using Absolute Mode is a mode that allows you to do everything to Locate Files and Directories.
# In the working directory (.) discover files and directories only with read-only permissions for user, group, and others. -permanent 444 # In the working directory (.) identify files and directories that have at least the read-only permission # for user, group, and others. -444 -perm # In the working directory (.) identify files and directories that have at least the read-only permission # for user, group, and others (including hidden files and directories). -permanent /444
Using Absolute Mode to Locate Files is a mode that allows you to do everything
With the -print parameter, you may change the output of the search results.
Instead than only seeing file paths in the search results, you may want to look at their characteristics. You may change the output of the search command by using the -print action.
When you use the find command, the -print argument causes it to display out the search results of files, each on a separate line. You’ll get the same result if you use any of the commands below to look for files and folders called snap.
find -name “snap” -print find -name “snap” -print find -name “snap”
The -print action is used to print the output of the find command.
Finding and printing file names that don’t include any white spaces
The -print0 option, unlike the normal -print parameter, allows you to remove white spaces or newline characters from a search result produced by the find command. Especially if you’re using another tool to look for patterns, such as grep.
You can use the command below to find and output a directory that is free of white spaces and newline characters.
# Remove white spaces and newline characters from the file or directory name “snap” and output the result locate -name “snap” -print0
Single-Line Printing of the Result
Using Print Formatting to locate and print a file with properties
The -printf argument of the search command may be used to customize the output format. This option enables you to write directives or “formatters” that determine the appearance of the search result.
You may need to locate files as well as their attributes, such as the last time they were accessed. If that’s the case, perform the instructions below.
# Find files with names that begin with’snap,’ then output each file’s last-time access attributes, complete path, and filename on a new line. find -name “snap*” -printf “percent a percent p n” # Find files with the.html or.json extension, then display the username, group name, complete path, and filename of each file owner on a separate line find (-name “*.html” -type f) -or -name “*.json” -printf “percent u percent g percent p n”
Using Directives to Find and Print File Properties
The following is a list of directives that may be used in conjunction with the -printf action:
- percent a – Returns the most recent access to a file.
- percent b – Returns the size of a file’s disk space in 512-byte blocks.
- percent d – Gets the depth of a file in the directory tree.
- percent g – Returns the name of a file’s group, or a numeric group ID if the group doesn’t have one.
- percent k – Returns the number of 1K blocks of disk space occupied by a file.
- percent m – Returns a file’s permission bits (in octal).
- percent p – Returns the precise filename of a file.
- % s – Returns the size of a file in bytes.
- percent t – Returns the last modification time of a file in the format of the -ctime option.
- percent u – Returns the user name of a file owner, or a numeric user ID if the user doesn’t have one.
Limiting the Number of Files You Can Find
If you want to narrow down your search even further and restrict it to directories, use the -maxdepth option with the find command, as shown below.
The -maxdepth argument instructs the find command to restrict the scope of the search to a certain number of subdirectories down the directory tree.
# Locate files and directories one level below the current working directory. -name “chart*” -maxdepth 1 # Go two levels down from the /chart directory search to discover files and folders. /chart -maxdepth 2 -name “chart” /chart -maxdepth 2 -name “chart”
Searching for Files in the Current and Subdirectories
With the -prune option, you can only find files in your working directory.
Check out the -prune argument if you want to restrict a search to just the current working directory and not recurse into any subdirectories.
You’ll locate files and folders whose names (-name) do not begin with snap and are confined (-prune) to the working directory using the command below (.).
Remove the -or operator and replace it with the -print action to retrieve search results for files and folders with names beginning with snap. -name “snap*” -name “snap*” -name “sna -prune
-prune -or -print find. -name “snap*”
Pruning File Names Beginning with’snap’ Search Result
Using Last Time Access to locate files and directories
Pruning certain files will undoubtedly restrict the search results. But what if the only memory you have of the file you’re searching for is the last time you used it? The good news is that you can use the find command to look for files and folders based on their last-time access. Let’s get started!
Finding files based on the file’s last access date
If you recall the last time you viewed a file or directory, the -atime option paired with the search command, as shown below, is all you need. The search command gives a false result and skips a file whose last time access does not fall within the value you set.
# Use find -atime to locate files and folders that you last visited between 2 and 3 days ago. 2 # find -atime -2 discover files and folders you last visited within the previous two days # find -atime 0 find -atime 0 find -atime 0 find -atime 0 find -atime 0 find -atime 0 find -atime
Locating Files accessed during the last two or three days
Getting a List of Files You’ve accessed in the Last Two Days
Getting a List of Files You’ve accessed in the Last Day
If you want to know the last time a file or directory was accessed, use the -printf action with directives. You may use the command line below to locate files that were accessed during the last day (-atime 0). The -printf action then prints the last time access (percent a) and filenames (percent p) of files or directories, each on a new line (n), as seen below.
find -atime 2 -printf “percent a percent p n” find -atime 2 -printf “percent a percent p n”
Using Last Time Access with Output to Locate Files
Using Last-Minute Access to Files to Locate Files
Assume you need to locate files depending on the current minute. The -amin option works in the same way as the -atime option. Instead, as seen below, you’ll obtain search results for files sorted by their most recent access time depending on the value you entered.
# Find files and directories accessed within the past 40 minutes # Not ideal most of the time as you will get result of tons of files and directories find -amin 40 # Find directories accessed within the past 40 minutes locate -type d -name “snap*” -amin -40 # Find files accessed within the past 40 minutes find -name “snap*” -type f -amin -40
Finding Files That Have Been accessed in the Last 40 Minutes
Using the Last Time Change method to locate files and directories
When searching for files or directories using last time access, you may get a large number of results, which might be misleading if the filenames are identical. Instead, use the -ctime option to limit down the search results even further. The -ctime option narrows the search results by the last time you changed a file or directory, depending on a value you provide (within the past days).
Perhaps you’re looking for files that you changed in the previous two days. If that’s the case, try the instructions below.
# find -ctime -2 find -ctime -2 find -ctime -2 find -ctime -2 find -ctime -2 find -ctime -2 find -ctime -2 find – # Find files and folders with names that start with’snap’ # that you’ve changed in the last two days find -name “snap*” -ctime -2
Locating Files and Folders Filtered by the most recent time change
After locating a file or directory, run a command.
The find command can do more than simply discover files and directories; with the -exec argument, it may also run commands straight after presenting search results. This capability is useful when you need to open a file in a text editor or delete a file or directory that has been discovered.
To avoid being misinterpreted, be careful to escape the semicolons (;) with a backslash ().
# Locate a file named’snap.doc’ and open it in vi editor find -name “snap.doc” -exec vi ; # Locate a file named’snap.doc’ and delete it find -name “snap.doc” -exec rm ;
Using the -delete Action to Remove Files and Directories
The find command does more than merely locate files, as you’ve seen. You may also use the locate command to remove a file automatically after it’s been discovered. You may need to remove empty files or folders with a specified name or that follow a pattern. Then the search command, together with the -delete action, will be really useful.
Your Step-by-Step Guide to Managing Directories and Files in Linux
Create a directory and a file first to illustrate how to remove files and directories using the -delete action. The command lines below will create a directory called (thanos) and a file named snap within that directory (mkdir).
touch thanos/snap mkdir thanos
Only empty folders are deleted using the -delete action. If you use the command line below to remove the thanos directory, you’ll receive a warning stating find: cannot delete ‘thanos’: There is no empty directory.
To remove a single file (snap), use the search command with the -type test option, as follows: -type f -delete find “snap”
# Find and remove the directory ‘thanos’ # This command fails because the ‘thanos’ directory is not empty find “thanos” -type d -delete # Locate and remove the file ‘thanos.snap’ locate “thanos.snap” -type f -delete
Because the /thanos directory isn’t empty, it can’t be erased.
Use the -depth option to erase the /thanos directory, as illustrated below. The locate command will look for the thanos directory and remove the contents of the /thanos directory recursively (-delete) as well as the directory itself.
find -depth -delete “thanos”
This post intends to show you how to use the Bash search command to identify files, acquire file attributes, and even change the format of an output. Previously, locating a misplaced file was fraught with difficulties. Is it considered cheating now that you may leap over the hurdles and go directly to the finish line?
Regardless matter the approach you used to locate your file, the experience was undoubtedly rewarding! So, whatever test, activity, or choice piqued your curiosity the most?
The “bash find file containing string” command is a powerful way to search for files that match a specific criteria. This article offers a step-by-step guide on how to use the bash find command with dozens of different parameters.
- bash find files in directory
- bash find example
- bash find file by name
- bash find file with extension
- bash find file and store in variable