Linux find Command: How to Search Files by Name

0saves

 

Linux find Command: How to Search Files by Name

When working in Linux, the find command is an incredibly powerful tool for locating files and directories. One common use case is searching for files by name, especially when you need to locate specific file types like .php, .js, and .css—regardless of case sensitivity.

In this tutorial, we’ll walk through how to use the find command to search for files by name and prepare them for archiving.

Searching for Files by Name (Case-Insensitive)

To locate all .php, .js, and .css files in a specific folder—ignoring case differences—you can use the following commands:

cd /home/taras/public_html  
find . -type f \( -iname '*.php' -o -iname '*.js' -o -iname '*.css' \) -print > /home/taras/list-to-archive.txt  

Here’s what the command does:

  1. cd /home/taras/public_html: Navigate to the target directory.
  2. find .: Search in the current directory (.) and all subdirectories.
  3. -type f: Limit the search to files only.
  4. -iname '*.php' -o -iname '*.js' -o -iname '*.css': Look for files matching the specified patterns (*.php, *.js, *.css) in a case-insensitive manner (-iname).
  5. -print > /home/taras/list-to-archive.txt: Save the search results to a file for later use.

After running this command, you’ll have a file /home/taras/list-to-archive.txt containing the list of matching files.

Archiving the Files

Once the file list is created, you can use the tar utility to create a compressed archive:

tar -cpjf /home/taras/archive.tar.bz2 -T /home/taras/list-to-archive.txt  

Here’s what this does:

  • -c: Create a new archive.
  • -p: Preserve file permissions.
  • -j: Compress using bzip2.
  • -f: Specify the output archive file.
  • -T: Use the file list generated by the find command.

Searching with Case Sensitivity

If you need to perform a case-sensitive search, simply replace -iname with -name in the find command:

find . -type f \( -name '*.php' -o -name '*.js' -o -name '*.css' \) -print > /home/taras/list-to-archive.txt  

Conclusion

The find command is a versatile tool that simplifies file management tasks in Linux. Whether you’re organizing files, preparing for archiving, or performing maintenance, mastering find can save you time and effort.

Don’t forget to bookmark this guide for quick reference and share it with others who might find it useful.

Leave a Reply

Your email address will not be published. Required fields are marked *