The find command is one of the most powerful and commonly used commands in Unix-based systems. It allows you to search for files in a directory hierarchy based on different criteria like file name, size, modification time, and others. While it’s often used for simple file searching operations, there’s a whole world of possibilities when it comes to utilizing find. In this post, we’re going to delve deeper into find and learn some interesting ways to leverage its power.
1. Find All Files in Current Directory
Finding all files in the current directory is straightforward. We specify . to tell find to search in the current directory, -type f to search for files (not directories), and -iname "*" to match all files.
find . -type f -iname "*"
2. Find Specific File Types Excluding Others
Sometimes we need to find files of a specific type but exclude others. For example, we may want to find all .txt files but skip .bz2 files.
find . -type f \( -iname "*.txt" ! -iname "*.bz2" \)
In this command, \( and \) are used to group conditions, ! stands for logical NOT, meaning it will exclude the following condition.
3. Finding Text within Files
We can use find in combination with grep to search within files. Suppose we want to search for a specific phrase within all .php files.
find . -type f -name '*.php' -exec grep -Hn -- 'phrase to find' {} +
The search expression belongs after grep; {} is where find supplies file names. -Hn keeps the file name and line number in the result.
4. Find, Zip, and Unzip Files
Find can also be combined with compression tools. To decompress all .bz2 files while preserving the archives:
find . -type f -name '*.bz2' -exec bunzip2 --keep -- {} +
5. Find and Replace Text in Files
The find command can be used with sed to replace text in many files. I preview the files and matching lines first:
find . -type f -name '*.php' -print
find . -type f -name '*.php' -exec grep -Hn -- 'old.example' {} +
find . -type f -name '*.php' -exec sed -i.bak 's/old\.example/new.example/g' {} +
The .bak suffix leaves a recoverable copy. I no longer convert <?=: the short echo tag has worked regardless of short_open_tag since PHP 5.4. PHP tags documentation
6. Find and Change File Permissions
We can use find to locate files or directories and change their permissions. For example, to find all directories named “specialfolder” and change their permissions to 755:
find . -name 'specialfolder' -type d -print
find . -name 'specialfolder' -type d -exec chmod 755 {} +
The first command previews the targets; the second changes them. -type d tells find to look for directories.
The find command’s versatility and power make it an essential tool for any system administrator or developer. Mastering its usage can help streamline tasks and make your work more efficient. Remember, the examples given here are just the tip of the iceberg. With a bit of creativity, you can use find in many more ways.
Buy Me a Coffee