As a Linux system administrator, knowing how to efficiently find and delete files is an essential skill. Whether you need to free up disk space, remove old log files, or delete sensitive information, Linux offers powerful commands to search for files and purge them with surgical precision.
In this comprehensive guide, you‘ll learn simple yet effective techniques to harness the full power of the Linux find and delete file commands.
An Overview of Finding and Deleting Files
Finding and deleting files in Linux requires just two main commands:
- find – Search for files and directories based on a variety of criteria
- rm – Delete files and directories
By combining find and rm, you can locate files and delete them in one swift command. This saves the extra step of having to first find files and then run a separate delete command.
Here is the basic syntax for finding and deleting files in one step:
find <path> <criteria> -delete
This will search for files matching the specified criteria under the given path and remove them automatically.
Let‘s break this down step-by-step.
The Linux Find Command for Locating Files
The find command in Linux enables you to search for files based on filename, size, date, permissions, owner, type, and many other properties.
Here is the basic syntax for using find:
find <path> <criteria> <action>
Let‘s understand each component:
- Path – Where to search. This can be a directory path, storage device, or entire filesystem. Some examples:
/home– Search user home directories/var/log– Scan log directory/dev/sda1– Search this disk partition
- Criteria – Which files to search for. For example:
-name "*.pdf"– Filename matches this pattern-size +1G– Size greater than 1GB-mtime -7– Modified in last 7 days
- Action – What to do with the matching files. Common actions include:
-print– Print names of matching files-delete– Delete matching files-exec– Run command on matching files
As you can see, the find command is immensely versatile. You can zero in on specific files based on almost any attribute.
Now let‘s see some examples of using find.
Find Files by Name
To search for files by full or partial name, use the -name parameter along with globbing patterns:
find /home -name "*.pdf"
This will find all PDF files under user home directories.
find /var/log -name "*auth*"
The above will match log files with ‘auth‘ anywhere in their names, like auth.log or sudoauth.log.
You can also exclude files using the ! symbol:
find /home -name "!*.txt"
This will match all non-text files in user homes.
Find Files by Size
To search for files above or below a certain size threshold, use the -size parameter along with comparison operators:
find /home -size +500M
The above will find files larger than 500 MB in user directories.
find /var/log -size -10k
This will match log files smaller than 10 KB.
Other size formats like K, M, G work too.
Find Files by Date
To search for recently modified files, use the -mtime parameter along with a value in days:
find /home -mtime -7
The above will match files changed in the last 7 days inside user directories.
You can also specify date ranges. For example:
find /logs -mtime +30 -and -mtime -365
This will find log files modified between 30 and 365 days ago.
There are many other date filters besides mtime like atime, ctime.
Matching Multiple Criteria
You can chain together multiple search criteria using Boolean logic:
find /var/log -name "*.log" -and -size +1M -and -mtime -7
The above will list logs ending in .log, over 1 MB, and modified in the last week.
More Boolean operators like -or and ! (not) can combine complex searches.
Acting on Matched Files
By itself, the Linux find command will only print out names of matched files. More often, you‘ll want to act on them in some way.
Some actions you can apply to matching files:
-delete– Delete matched files-exec– Execute a command on files-print– Print names to standard output
Let‘s look at some examples.
Deleting Found Files
One of the most common scenarios is to search for files like temporary files or old logs and purge them in one go.
This is where the -delete action comes in handy with find.
For example, to match all *.tmp files over 10 MB and remove them:
find /home -name "*.tmp" -size +10M -delete
Or delete all logs under /var/log older than 2 years:
find /var/log -mtime +730 -delete
This allows you to precisely target large subsets of files and delete them safely in one sweep.
Running Commands on Found Files
The -exec action lets you execute arbitrary commands or shell scripts on files matching your find criteria. Commands are appended after {} for each matching file.
Some examples:
Strip executable permissions from *.sh files:
find /home -name "*.sh" -exec chmod -x {} \;
Archive old logs over 10 MB:
find /var/log -size +10M -exec tar -cvzf archive_{}.tar.gz {} \;
The \; signals the end of the command.
This technique opens up many possibilities to batch process particular sets of files.
Finding Files Faster with Locate
The locate command can instantly search a database of filenames and paths. This makes it much faster than find since there is no extensive filesystem traversal.
The downside is that locate only scans filenames indexed in its database, which is updated once per day. So it will not match recently created files.
Some examples of using locate:
locate --regex ".*[log|bkp]$"
The above finds files ending in .log or .bkp via regex.
locate -i passw*
This ignores case sensitivity while matching passw* patterns.
In summary, locate is blazing fast while find examines the actual filesystem. Use locate for quick searches and find for reliable accuracy.
Finding and Deleting Files in One Step
Now that you know how to search for files with find and delete with rm, let‘s put it together to locate files and purge them automatically.
Here are some examples patterns:
Delete JPEG files over 5 MB inside user directories:
find /home -name "*.jpg" -size +5M -delete
Remove empty subdirectories anywhere under /var:
find /var -type d -empty -delete
Match GZIP compressed logs in /var/log and delete:
find /var/log -name "*.gz" -delete
As you can see, Linux makes it simple to pinpoint files via flexible criteria and eliminate them in one swift command.
Tips for Safer File Deletion
When deleting files programatically, extra care should be taken to avoid disastrous mishaps. Here are some tips:
- Test runs – First do dry runs without -delete to preview matches
- Undo capability – Send deletes files to Trash or archive them
- Sudo usage – Prefix find with sudo when accessing system directories
- Narrow criteria – Be as precise as possible in search terms
- Exclude crucial directories – Explicitly omit critical filesystem paths
Building in checks and overrides will prevent accidental data loss.
Some Linux distributions also offer advanced file searching capabilities:
- mlocate – An enhanced locate supporting regular expressions
- Beagle – Desktop search engine for fast file indexing
- recoll – Full text indexing and compressed content search
Conclusion
In closing, Linux offers immense power through the find command to search for files coupled with deletion capabilities. Mastering the techniques covered here will enable you to swiftly clean up old files, recover wasted disk space, remove sensitive items, and overall enforce better organization.
Be sure to start with non-destructive test runs before executing permanent deletes. And incorporate additional checks like archives or trash storage as a precaution.
With Linux, simplify routine file administration by easily finding what you need and dismissing what you don‘t.


