There are times when you need to find some files on your Linux server or desktop. This could mean looking for a specific file to make a change, or it could simply be because you want to organize your files into subdirectories. In this tutorial, we’ll show you how to use three different methods for finding files in Linux: the find command, grep, and locate.
search files with find command in Linux
Find command is a command line utility that searches for files in your file system. Find command uses regular expressions to match files. Find command can search for files by name or by size.
The syntax of find command is as follows:
- find [path] -name “regex” -print0 | xargs -0 ls -lR > filelist
This will print all the names of files, directories and subdirectories in the current working directory which match the pattern “regex”. It also prints their permissions and sizes, but not their ownerships (you can change this behaviour with other flags). The long format output is redirected to a file called filelist so that it doesn’t go into standard output where we might lose it (i.e., when running multiple instances).
search files with grep command in Linux
The grep command is a handy utility that allows you to search for patterns in files, directories and even entire file systems.
The most basic way to use grep is to find a single line containing the specified pattern. For example:
- To search for “linux” in “myfile”: grep linux myfile
- To search for multiple lines containing the specified pattern: grep -r linux mydirectory
search files with locate command in Linux
The use of locate is very simple. It has a syntax similar to that of find and can be used in shell scripts.
But unlike find, locate uses its own database of files instead of the directory’s contents. This means locating a file on your system will be much quicker than using find, but it also means you’re limited to searching through only those files listed in the database (which generally includes everything).
In this article, we saw three ways to search for a file in Linux.
First, you can use the find command, which allows you to search through the filesystem tree by specifying conditions like name and size. Second, you can use grep to find lines that contain a string anywhere in the file (not necessarily at the beginning). Thirdly, locate makes finding files easier by indexing an entire system so that searches take seconds instead of minutes or hours depending on how many files there are on your computer or network.”