Understanding the `find -exec` Command | Generated by AI

Home PDF

The -exec option in the find command is a powerful feature in Unix-like systems that allows you to execute a command on each file or directory matched by the find criteria. Your example, find . -name "*eclipse*" -exec rm {} \;, searches for files or directories with “eclipse” in their name and deletes them using rm. Let’s explore how -exec works, common patterns, and more examples.

How -exec Works

Common Patterns and Examples

1. Deleting Files (rm)

Your example:

find . -name "*eclipse*" -exec rm {} \;

2. Moving Files (mv)

Move all .txt files to a specific directory:

find . -name "*.txt" -exec mv {} /destination/folder \;

3. Copying Files (cp)

Copy all .jpg files to a backup folder:

find . -type f -name "*.jpg" -exec cp {} /backup/images \;

4. Changing Permissions (chmod)

Make all shell scripts executable:

find . -name "*.sh" -exec chmod +x {} \;

5. Listing Details (ls -l)

Display detailed info about all .log files:

find . -name "*.log" -exec ls -l {} \;

6. Grepping Content (grep)

Search for a string (e.g., “error”) in all .log files:

find . -name "*.log" -exec grep "error" {} \;

7. Compressing Files (tar or gzip)

Compress all .txt files individually:

find . -name "*.txt" -exec gzip {} \;

8. Running a Custom Script

Execute a script on each matched file:

find . -name "*.data" -exec ./process.sh {} \;

9. Combining Commands with Shell

Use a shell to combine multiple commands:

find . -name "*.bak" -exec sh -c 'mv {} /tmp && echo "Moved {}"' \;

10. Batch Processing with xargs Alternative

For efficiency with many files, -exec can be replaced with xargs:

find . -name "*.tmp" | xargs rm

Advanced Tips

Common Commands Used with -exec

Notes

These examples and patterns should give you a solid foundation for using -exec effectively! Let me know if you want more specific use cases.


Back 2025.03.17 Donate