You may have downloaded or the move the file from one place to another and totally forget where you moved or downloaded that file. That’s what happens to me a lot! There’s a find command which helps to locate the files and directories in the Linux system. Find command is very useful to find the missing files and directories. You can specify five things while using find command: pathname(where to search), file types(directories, links, data files), with the permissions, name of the file and perform logical operations on selections (-o and -a). Here’s a simple syntax of find command which is easy to understand.
find where-to-look criteria what-to-do
Remember, all the arguments are optional. Try simply using “find” which will list each and everything that is in your system.
Search file with name in the whole system:
find / -name file_name
This command search for “file_name” in the whole system. The “/” tell the console to search in the whole system. You should run this command as root. If you want to search in your current directory use:
find . -name file_name
I searched for a file named “hello” in the current directory and here’s my output.
Thus the use of “/” searches in the whole system starting from the root directory and must be run as a root. The use of “.” search in the current working directory.
Search file with the specific extension:
find . -name "*.txt"
This command search for the files with the extension .txt.
Search based on modification time:
“-mtime” is used to search the files based on modification time. Let’s take a example for a day.
find . -mtime 1(find all the files modified exact 1 day)
find . -mtime -1(find all the files modified less than a day)
find . -mtime +1(find all the files modified more than a day)
Search files with strings(Using grep):
Find command can be used with grep command to find the files with the specific words. Grep command is used to search the strings in the files. This is extremely useful. See the grep command tutorial. The “xargs” is used to modify the find command. Here’s an example of find and grep command:
find . -name ".*txt" -print | xargs grep "hello"
This command searches all the text files with the word “hello” on them and display the results. The use of “-print” is encouraged to avoid problems with white space in the path when piping xargs. You can also find more information about “find command” in the manual page. Type man find in the terminal in order to access the manual page of find. The find command is extremely powerful and useful. Find command can be used with various other commands as well. If you have any problems, feel free to ask questions as comments.