- find command in Linux with examples
- How to Find Files in Linux Using the Command Line
- Find a File in Linux by Name or Extension
- Using Common find Commands and Syntax to Find a File in Linux
- Basic Examples
- Options and Optimization for find
- Find a File in Linux by Modification Time
- Use grep to Find a File in Linux Based on Content
- How to Find and Process a File in Linux
- How to Find and Delete a File in Linux
- More Information
- How to Use Find and Locate Commands In Linux: A Beginner’s Guide
- Why Use Find and Locate Commands in Linux?
- Using the Find Command in Linux
- The Basic Syntax
- Ways to Utilize find Command
- Searching by Name
- Searching by Type
- Searching by Time
- Searching by Size
- Searching by Ownership
- Searching by Permissions
- Other Useful Options
- Using Locate Command in Linux
- How to Install locate Package
- The Basic Syntax
- How to Use Linux Locate Command
- Search Exact File Name
- Count the Number of Files
- Ignore Case Sensitive
- Show Existing Files
- Disables Errors While Searching
- Limit the Number of Search Results
- Conclusion
find command in Linux with examples
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. By using the ‘-exec’ other UNIX commands can be executed on files or folders found.
Syntax :
Options :
- -exec CMD: The file being searched which meets the above criteria and returns 0 for as its exit status for successful command execution.
- -ok CMD : It works same as -exec except the user is prompted first.
- -inum N : Search for files with inode number ‘N’.
- -links N : Search for files with ‘N’ links.
- -name demo : Search for files that are specified by ‘demo’.
- -newer file : Search for files that were modified/created after ‘file’.
- -perm octal : Search for the file if permission is ‘octal’.
- -print : Display the path name of the files found by using the rest of the criteria.
- -empty : Search for empty files and directories.
- -size +N/-N : Search for files of ‘N’ blocks; ‘N’ followed by ‘c’can be used to measure size in characters; ‘+N’ means size > ‘N’ blocks and ‘-N’ means size My Personal Notes arrow_drop_up
Источник
How to Find Files in Linux Using the Command Line
When you have to find a file in Linux, it’s sometimes not as easy as finding a file in another operating system. This is especially true if you are running Linux without a graphical user interface and need to rely on the command line. This article covers the basics of how to find a file in Linux using the CLI. The find command in Linux is used to find a file (or files) by recursively filtering objects in the file system based on a simple conditional mechanism. You can use the find command to search for a file or directory on your file system. By using the -exec flag ( find -exec ), files can be found and immediately processed within the same command.
Find a File in Linux by Name or Extension
Use find from the command line to locate a specific file by name or extension. The following example searches for *.err files in the /home/username/ directory and all sub-directories:
Using Common find Commands and Syntax to Find a File in Linux
find expressions take the following form:
- The options attribute will control the find process’s behavior and optimization method.
- The starting/path attribute will define the top-level directory where find begins filtering.
- The expression attribute controls the tests that search the directory hierarchy to produce output.
Consider the following example command:
This command enables the maximum optimization level (-O3) and allows find to follow symbolic links ( -L ). find searches the entire directory tree beneath /var/www/ for files that end with .html .
Basic Examples
Command | Description |
---|---|
find . -name testfile.txt | Find a file called testfile.txt in current and sub-directories. |
find /home -name *.jpg | Find all .jpg files in the /home and sub-directories. |
find . -type f -empty | Find an empty file within the current directory. |
find /home -user exampleuser -mtime -7 -iname «.db» | Find all .db files (ignoring text case) modified in the last 7 days by a user named exampleuser. |
Options and Optimization for find
The default configuration for find will ignore symbolic links (shortcut files). If you want find to follow and return symbolic links, you can add the -L option to the command, as shown in the example above.
find optimizes its filtering strategy to increase performance. Three user-selectable optimization levels are specified as -O1 , -O2 , and -O3 . The -O1 optimization is the default and forces find to filter based on filename before running all other tests.
Optimization at the -O2 level prioritizes file name filters, as in -O1 , and then runs all file-type filtering before proceeding with other more resource-intensive conditions. Level -O3 optimization allows find to perform the most severe optimization and reorders all tests based on their relative expense and the likelihood of their success.
Command | Description |
---|---|
-O1 | (Default) filter based on file name first. |
-O2 | File name first, then file type. |
-O3 | Allow find to automatically re-order the search based on efficient use of resources and likelihood of success. |
-maxdepth X | Search current directory as well as all sub-directories X levels deep. |
-iname | Search without regard for text case. |
-not | Return only results that do not match the test case. |
-type f | Search for files. |
-type d | Search for directories. |
Find a File in Linux by Modification Time
The find command contains the ability to filter a directory hierarchy based on when the file was last modified:
The first command returns a list of all files in the entire file system that end with the characters conf and modified in the last seven days. The second command filters exampleuser user’s home directory for files with names that end with the characters conf and modified in the previous three days.
Use grep to Find a File in Linux Based on Content
The find command can only filter the directory hierarchy based on a file’s name and metadata. If you need to search based on the file’s content, use a tool like grep . Consider the following example:
This searches every object in the current directory hierarchy ( . ) that is a file ( -type f ) and then runs the command grep «example» for every file that satisfies the conditions. The files that match are printed on the screen ( -print ). The curly braces ( <> ) are a placeholder for the find match results. The <> are enclosed in single quotes ( ‘ ) to avoid handing grep a malformed file name. The -exec command is terminated with a semicolon ( ; ), which should be escaped ( \; ) to avoid interpretation by the shell.
How to Find and Process a File in Linux
The -exec option runs commands against every object that matches the find expression. Consider the following example:
This filters every object in the current hierarchy ( . ) for files named rc.conf and runs the chmod o+r command to modify the find results’ file permissions.
The commands run with the -exec are executed in the find process’s root directory. Use -execdir to perform the specified command in the directory where the match resides. This may alleviate security concerns and produce a more desirable performance for some operations.
The -exec or -execdir options run without further prompts. If you prefer to be prompted before action is taken, replace -exec with -ok or -execdir with -okdir .
How to Find and Delete a File in Linux
To delete the files that end up matching your search, you can add -delete at the end of the expression. Do this only when you are positive the results will only match the files you wish to delete.
In the following example, find locates all files in the hierarchy starting at the current directory and fully recursing into the directory tree. In this example, find will delete all files that end with the characters .err :
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Monday, October 25, 2010.
Источник
How to Use Find and Locate Commands In Linux: A Beginner’s Guide
Do you want to know how to perform searches on a Linux computer or server? Then you’ve come to the right place!
In this article, we’ll talk about the Linux find and locate commands, which will help you to look for any file on your machine.
Why Use Find and Locate Commands in Linux?
New Linux users often claim that they get confused about the location of their files on a server. This might be because most people are used to operating Windows or macOS, which have more clear-cut and user-friendly directory layouts.
While there is some truth to this, Linux gives users more options on how to search for files using certain commands. Besides searching based on common filters, you are also able to find files by user permissions, size, timestamps, and so on.
What’s great, once you understand the commands, searching for files on your Linux platform is strikingly easy.
To do that, we’ll utilize the find and locate commands in Linux.
An important thing to note is that we will be using Ubuntu VPS in this guide. That being said, the steps should also work for Debian, CentOS, or any other distribution of Linux. If you don’t know how to connect to VPS, you can follow this guide before proceeding further.
Using the Find Command in Linux
First, let us explain the find command and how to use it.
The Basic Syntax
The most popular command to find and filter files on Linux is find. The basic syntax is as follows:
It starts with the keyword find, which alerts Linux that whatever follows after will be used to find your file. The argument is the origin point of where you want to start the search. It can be replaced with several arguments, including:
- / (slash) — search the whole system.
- . (dot) — search from the folder you’re currently working on (current directory).
(tilde) — to search from your home folder.
In order to find the current directory you are in, use the pwd command.
The second argument is dedicated to your file. This could be the file’s name, type, date of creation, etc. The third argument is where you will specify the relevant search term.
Ways to Utilize find Command
Let’s take a look at various options Linux provides its users:
Searching by Name
Of course, the most common method to look for a file is using its name. To run a simple search query using the name of the file, use the find command like this:
We used the -name option, and searched for a file called my-file. Note that we started the search in our current directory by using the . (dot) argument.
Keep in mind that the -name argument looks for case-sensitive terms in Linux. If you know the name of the file, but are not sure about its case-sensitivity, use the following find command:
You can also search for all files without a certain keyword in their name. There are two ways to do this. The first method involves using the –not keyword in the following manner:
Second, we can use the exclamation symbol (!). However, it has to be preceded by the escape identifier (\) to let Linux know that this is the part of the find command.
You can look for multiple files with a common format like .txt as well:
This will list down all the text files starting with the current folder.
Lastly, if you want to find a certain file by name and remove it, use the -delete argument after the file name:
Searching by Type
Linux allows users to list all information based on their types. There are several filters that you can use:
- d – directory or folder
- f – normal file
- l – symbolic link
- c – character devices
- b – block devices
A simple example of using a file type can be seen below:
This will list all of the current directories in your system since we searched from our root directory with the / (slash) symbol.
You can also combine the –type and -name options to narrow down your searches further:
This will look for files named my-file, excluding directories or links.
Searching by Time
If you want to search for files based on when they were accessed and modification time footprints. Linux keeps track of the files using these three timestamps.
- Access Time (-atime) – when the file was either read or written into.
- Modification Time (-mtime) – when the file was modified.
- Change Time (-ctime) – when the file’s meta-data was updated.
This option has to be used with a number that specifies how many days passed since the file was accessed, modified or changed:
This command will show all files that were accessed a day ago starting from your current time.
We can narrow down our queries even more by adding plus (+) and minus (–) signs preceding the number of days. For instance:
It lists down all the files that have a modification time of more than two days ago.
To find all files whose meta-data was updated less than a day ago, run the following:
While not often used, there are some additional arguments that are also related to timed-searches. The -mmin argument looks for modified files on a minute basis. It can be used like this:
Also, we have the -newer argument, which can be used to compare the age of two or more files and display the newer one.
What you’ll get are all of the files that are more recently modified than your file.
Searching by Size
Linux lets you search for files based on their sizes. The syntax for searching files by size is:
You can specify the following size units:
- c – bytes
- k – kilobytes
- M – megabytes
- G – gigabytes
- b – 512-byte chunks
A simple example of how to use the find command for file sizes is as follows:
Here we search for all of the files in your system that are exactly 10 megabytes. Just like when searching based on time, you can filter your searches further using the plus and minus signs:
It will display all the files that are more than five gigabytes in size.
Searching by Ownership
Linux gives you the ability to narrow down your searches based on file ownership. To find files of a certain owner, the following command should be executed:
The script will return a list of all files that the user named john owns. Similar to usernames, we can also find files through group names:
Searching by Permissions
Users can search for files based on file permissions using -perm option. For example:
In Linux, 644 corresponds to read and write permission. That means this command will look for all the files that have only read and write permissions. You can play around with this option further:
With an addition of a dash symbol, it will return with all the files that have at least 644 permission.
Feel free to read more on permissions and various codes corresponding to other Linux permissions.
Other Useful Options
There are other useful options that you should remember.
For example, to look for empty files and folders on your system, use the following:
Similarly, to look for all the executables saved on your drive, utilize the -exec option:
To look for readable files, you can run the following command:
As you can see, there is a ton of options at hand for users to tailor their queries as they wish. Let us look at the other command which can be used to locate files in Linux.
Using Locate Command in Linux
The locate command is a useful alternative, as it is faster than the find command when performing searches. That’s because the former only scans your Linux database instead of the whole system. Furthermore, the syntax is relatively easier to write.
How to Install locate Package
By default, Linux does not come with the locate command pre-installed. To get the package, run the following commands one after another:
The Basic Syntax
You can now use the command to search for files using this syntax:
The vanilla locate command can sometimes return files that have been deleted, if the database wasn’t updated. The best solution is to manually update the database by running the following:
How to Use Linux Locate Command
We’ll share with you the most common applications of Linux locate command.
Search Exact File Name
The basic syntax only allows you to search for files that contain the search term. If you want to get the file with the exact name, you can use the -r option and add dollar symbol ($) at the end of your search term, for example:
Count the Number of Files
In order to tell how many files appear on your search result, insert -c after the locate command.
Instead of listing all the files, it will give you the total number of them.
Ignore Case Sensitive
Use -i on your linux locate command to ignore case sensitive files. For instance:
All of the files with this name will be shown, regardless of any uppercase or lowercase symbols found.
Show Existing Files
Just like we’ve mentioned, Linux locate command can even show you a deleted file if you haven’t updated the database. Thankfully, you can get around this problem by using -e option, like this:
By doing this, you will only get files that exist at the time you perform the locate command.
Disables Errors While Searching
-q option will prevent any errors from showing up when the search is being processed. To do this, simply enter:
Limit the Number of Search Results
If you want to limit the number of search results, -n will do the trick. However, remember that you need to put the option at the end of the command line. Take a look at this example:
The script will only display the first 10 files it discovers even when there are more.
Conclusion
You can search for files on your server using the find and locate commands in Linux. These two powerful tools have their own advantages. Therefore, we encourage you to give both of them a go and see which one is more suitable for you. Here’s a short summary of what we talked about:
- Use find to search for files based on name, type, time, size, ownership and permissions, in addition to some other useful options
- Install and use Linux locate command to perform faster system-wide searches for files. It also allows you to filter out by name, case-sensitive, folder, and so on.
If you have any questions, feel free to ask in the comments!
Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places.
Источник