Using find and rm to Delete Files by Extension
In Linux or macOS, you can use the find command with rm to batch delete files with a specific extension in the current directory (or a specified path). This is an efficient and flexible file management technique.
Basic Command Syntax
To delete all .html files in the current directory (.), use:
find . -name "*.html" -exec rm -f {} ;
Alternatively, using a pipe (|) with xargs:
find . -name "*.html" | xargs rm -f
Command Breakdown
find .: Start searching from the current directory.-name "*.html": Match all filenames ending with.html.-exec rm -f {} ;: Executerm -f(force delete) for each found file.{}is a placeholder for the file path.| xargs rm -f: Pipe the output offindtoxargs, which passes the file paths as arguments torm -f.
Extended Usage and Best Practices
1. Delete files in a specific directory: Replace . with the target path. For example, to delete all .log files in /tmp/docs:
find /tmp/docs -name "*.log" -exec rm -f {} ;
2. Safety first: preview before deleting. Run find alone to list files that would be affected:
find . -name "*.html"
3. Handle filenames with spaces or special characters. The -exec method is generally safer. For xargs, use null-character separation to avoid issues:
find . -name "*.html" -print0 | xargs -0 rm -f
The -print0 and -0 options use null characters as delimiters, safely handling all filenames.
4. Target different file types: Modify the pattern in -name. For example, -name "*.tmp" for temporary files.
Warning:
rm -fforces deletion without confirmation. Use with extreme caution, especially in directories with important data. Always verify the command's behavior in a test environment or ensure you have backups.