Commands.page Logo

How to Remove Files by Extension in Ubuntu

This article provides a quick guide on deleting files with a specific extension in the current directory on Ubuntu. It covers basic command-line techniques using wildcards and the find command to ensure you clean up your workspace safely and effectively.

Using the RM Command with Wildcards

The fastest way to remove files is using the rm command combined with a wildcard. Open your terminal and navigate to the target directory. To delete all files ending in .tmp, for example, run:

rm *.tmp

This command matches every file in the current folder with that extension and deletes them immediately. Be careful, as this action cannot be undone.

Previewing Files Before Deletion

Before running a delete command, it is best to verify which files will be affected. Use the ls command with the same wildcard pattern:

ls *.tmp

Review the list to ensure no important files are selected. Once confirmed, you can proceed with the rm command.

Using the Find Command for Safety

For more control, especially if you want to ensure only files (not directories) are deleted, use the find command. To remove all .tmp files in the current directory only, use:

find . -maxdepth 1 -type f -name "*.tmp" -delete

The -maxdepth 1 flag ensures subdirectories are not scanned, and -type f confirms only regular files are targeted.

Handling Permission Issues

If you encounter permission denied errors, you may need to use sudo. Exercise extreme caution when using elevated privileges:

sudo rm *.tmp

Always double-check the path and extension when using sudo to prevent accidental system file deletion.