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 ./ -name "*.php" -exec grep -e {} +;
This command will search for the phrase within all .php files in the current directory and its subdirectories.
4. Find, Zip, and Unzip Files
Find can also be combined with other commands like zip and bunzip2 to compress or decompress files. For example, to decompress all .bz2 files excluding already uncompressed files:
find . -type f \( -iname "*" ! -iname "*.bz2" \) -print0 | while IFS= read -r -d $'\0' line; do
echo "Bunzipping: $line"
bunzip2 -z "$line"
done
5. Find and Replace Text in Files
The find command can be used in conjunction with sed to find and replace text in files. Suppose we have some legacy PHP4 code that uses shortcuts to echo, and we want to replace them.
find ./ -name "*.php" -exec sed -i 's/\<\?=/\<\?php\ echo\ /g' {} \;
This command replaces all instances of <?= with <?php echo in all .php files.
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 -exec chmod 755 {} \;
In this command, -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