40 Best Examples of Find Command in Linux: The Complete Guide for File Search and Automation

As Linux infrastructures scale to petabytes of data across thousands of servers, effectively managing all those files gets increasingly difficult. 92% of IT managers surveyed said file storage growth is making storage management more complex.

How do Linux administrators intelligently locate files to clean up wasted space, audit permissions, find sensitive data, and automate management with so much scale?

The humble but mighty Find command is their Swiss army knife for slicing through file system complexity. Mastering Find helps admins overcome many management challenges.

In this complete guide, I‘ll provide 40 practical examples of the Linux Find command for both new and experienced sysadmins. We‘ll cover how to:

  • Find Files By Name: Match file and directory names, extensions, case-insensitive searches
  • Search By File Size: Locate files over, under or between certain sizes
  • Find By Ownership and Permissions: List files by user, group, permssions like 777 files
  • Search Content with grep: Combine Find with grep to match text
  • List Files Details with ls: Output file details like long listing
  • Copy, Move and Delete Files: Combine Find with cp, mv and rm
  • Optimize Performance: Make Find faster by avoiding unneeded directories
  • Take Actions Using -exec: Pass results to other programs like chmod and tar
  • Audit File Systems: Find stale files, directories using space, permission issues
  • Automate Management: Examples combining Find into scripts to handle located files

I‘ll provide real-world examples of Find so you can directly apply them for common system administration tasks on Linux, whether you manage a few servers or thousands.

So let‘s start mastering the Find command!

1. Find Files By Exact Name

The most basic Find use case is locating files by their full name or extension…

find . -name install.log

That will recursively match and print filenames containing "install.log" from the current directory ..

Some examples of matching by name:

Locate Log Files

To find install.log:

find / -name install.log

Match a Specific Extension

Print all .log files:

find /var/log -name *.log

Case-Insensitive Search Names

To make the name search case-insensitive:

find / -iname INSTALL.LOG 

This will match regardless of upper or lowercase name.

Handling files that have moved locations or determining if a filename exists on a system makes Find invaluable.

Now let‘s look at locating files by other attributes like size…

2. Search Files By Size

Often you need to find files above or below a certain size threshold. Common examples include:

  • Rotating log files out of overflowing directories
  • Finding large video and image assets to archive cold storage
  • Locating files consuming excess space to remove

Find enables searching file sizes using these units:

Unit Meaning
b 512 byte blocks
c bytes
k kilobytes
M megabytes
G gigabytes

You append the size unit to a numeric value. Some examples:

Locate Files Over 10 Megabytes

Finds files larger than 10MB:

find / -size +10M

The + indicates over that size.

Print Files Under 2 Kilobytes

To match tiny files under 2KB in size:

find /tmp -size -2k 

The – means less than the size. Helpful for finding log files not rotated properly.

Find Between Size Range

Fetch files between a size range like 100KB to 200KB:

find /opt -size +100k -size -200k

This only matches files in that size bracket.

Monitoring size thresholds prevent wasted storage on unused file build up.

Now let‘s look at finding files by creation and access times…

3. Locate Files By Time Attribute

To analyze storage usage over time, determine cleanup candidates or audit access, use these options to search file timestamps:

  • Access time (-atime) – Last read of file contents
  • Modification time (-mtime) – Last content update
  • Change time (-ctime) – Last metadata change like permissions or ownership

They take a numeric value plus specific units:

Unit Meaning
m Minutes
h Hours
d Days

Common examples include:

Recently Accessed Files

Find files read in last 5 minutes:

find ~ -atime -5m  

Helps determine active working set.

Week Old Unmodified Logs

Matches files not modified for over 7 days:

find /var/log -mtime +7d

Candidates for log rotation.

List New Files

Prints files changed in last day:

find . -ctime -1d

Useful to determine what‘s recently updated.

So combined with filters like file size, time attributes narrow down file search check points.

4. Find By File Permissions and Ownership

Permissions and ownership offer critical context on files. Common scenarios include:

  • Audit user file access – Ensure users only access allowed files
  • Find insecure permissions – Like world writeable, misconfigurations
  • Review before access changes – Examine effective permissions before support sessions

Find makes auditing permissions easy using options like:

  • -user – Match owned by specific user
  • -group – Owned by primary group
  • -perm – Filter by permission like 755, also with operators like /, – and +

Some handy permission auditing examples:

World Writable Files

Detects files writable by anyone:

find / -perm 777

Dangerous misconfiguration giving global access.

List Files of User

Shows files owned by "john":

find /home -user john

Quick audit before support session.

Locate SGID/SUID Binaries

Finds setuid/setgid root files:

find / -perm -4000 -o -perm -2000  

Privileged programs that can be dangerous if compromised.

Understanding standard permissions by user and intended access makes auditing easier.

5. Grep File Contents with Find

Grep filters patterns from file contents. Combining it with Find enables powerfully scoping searches to specific locations.

For example, to search JS code for API keys:

find . -name *.js -exec grep -i API_KEY {} \;

This finds .js files then searches their contents, printing filenames with matches to screen.

Some other examples:

Find Configs With Password

To print .conf files containing DB_PASSWORD:

find /etc -name *.conf -exec grep DB_PASSWORD {} \;

Match Text Across Code

Finds Python and JS files containing "Todo: Refactor":

find . \( -name *.py -o -name *.js \) -exec grep -l "Todo: Refactor" {} +

Grep combos are perfect for scouring code and assets for keywords.

Now let‘s look at piping results to other programs…

6. Output File Details with ls

The ls command prints helpful file details. Combine it with Find using -exec to summarize results:

find . -name *.log -exec ls -lh {} +  

This will long list all logfile details so you can review sizes, dates and permissions.

Some other examples:

List Large Log Files

To print large Apache logs:

find /var/log/apache2 -name access.log -exec ls -lh {} \;  

Trims results to only large access logs.

See Folder Sizes

Summary of all directories over 10 GB:

find / -type d -size +10G -exec du -sh {} \;

Helpful before cleaning up space of tmp or logs.

Piping find to ls lets you vet matches visually before taking action.

7. Find and Copy Files

A common need is to archive sets of files, like better organizing projects.

The -exec option runs commands on results, enabling integrate find with bash tools like copy, move and delete.

Some examples:

Archive Old Logs

To snapshot logs not accessed in over 180 days:

find /var/log -atime +180 -exec cp {} /mnt/backups \;

This increments backups of stale logs.

Concatenate CSV Reports

To combine last month‘s daily reports:

find . -name ‘daily_report_*.csv‘ -mtime -30 -exec cat {} + > combined_reports.csv

Super useful for processing file outputs.

Copy Photos to User Folders

To copy .jpg family photos to respective user accounts:

find /media/familypics -name "*.jpg" -exec cp {} /home/{}/pics \;  

The {} inserts the filename into the command.

Find and copy avoids tedious manual sorting and dragging of files between folders.

8. Move Large Groups of Files

Similar to copying, a common need is consolidating files scattered across the system to a central location.

For example, gathering last year‘s project files together:

Consolidate Old Code

Move code not touched in over a year to cold storage:

find /opt /usr /var -name ‘*.py‘ -atime +365 -exec mv {} /mnt/coldstorage \;

This sweeps up .py files and moves them to archives.

Migrate Media Files

To relocate media assets like images and videos:

find / -path ‘/home/*/media‘ -exec mv {} /nas_media \;

Handy before replacing user laptops/desktops.

Centralize Log Files

To aggregate all web server access logs to one location:

find / -name ‘access.log‘ ! -path ‘*/nginx/*‘ ! -path ‘/var/log/*‘ -exec mv {} /var/log/all_access.log \;

The ! (not) paths exclude the central Nginx and Apache log directories. This catches access logs that end up scattered elsewhere.

Find and move enables efficiently corralling files distributed across random paths into defined homes.

Now let‘s look at combining Find with rm for safely deleting files…

9. Securely Deleting Groups of Files

Blindly running commands like rm -rf * can lead to catastrophic losses deleting unintended files.

Find enables precisely targeting only the set of files you need removed based on criteria:

For example:

Remove Temp Files

Clean out old temporary content over 30 days old:

find /tmp -type f -mtime +30 -delete

Safely deletes without harming active temp files.

Clear Thumbnail Caches

To wipe thumbnail caches wasting GBs of space:

find ~ /var/cache/thumbnails -path ‘*Thumbails*‘ -delete

Criterially deletes cache detritus while retaining needed files.

Remove Old Backups

To save 2 weeks of backups then expire older:

find /backups -type f -mtime +14 -delete  

This makes space while keeping a couple weeks of backups.

Find + delete saves tediously checking directories when eliminating file build up.

10. Optimize Find Speed

Find recursively descends folder structures which can strain larger systems. Some techniques to optimize include:

Skip Unneeded Directories

Exclude directories you don‘t need searched:

find / -path ‘/sys/*‘ -prune -o -type f -print

The -prune skips /sys, -o continues find across other paths.

Limit Search Depth

To only descend 5 levels:

find / -maxdepth 5 -type f

Avoid crawling Terabytes on backups mounts.

Parallelize Finds

On machines with spare cores, run parallel finds:

find /media -type f | xargs -P4 -I{} echo {}

The -P4 splits across 4 concurrent finds, speeds up IO heavy operations.

Optimized finds maintain speed on large storage deployments.

11. Execute Actions Like Chmod/Chown

So far we‘ve covered matching files. But the real power comes from acting on results using -exec.

For example, restrictive permissions on groups of files cause access issues. Or needing to recursively chown files to a common owner.

Couple that criteria matching with:

find . -name ‘*.php‘ -exec chmod 640 {} +

This bulk changes PHP files to owner read/write, group read permissions, avoiding tedious manual edits.

Other examples:

Reset Incorrect Owners

To fix accidentally changed owners:

find /home -user incorrectUser -exec chown user: {} +

Reliably restores proper ownership, even recursively across mounts.

Restrict Sensitive File Access

Revoking permissions to proprietary code:

find . -name ‘*.java‘ -exec chmod 500 {} +

Rapidly dials down access without missing files misconfigured readable.

Executing actions allows efficiently making permission and ownership changes affecting thousands of files at once.

12. Create and Extract Archives

Finding specific sets of files then archiving them is a common task when offloading old storage out of primary systems.

For example, collect media files onto tape:

find /nas_media -type f -exec tar cvzf /mnt/tape/media_archive_{1..5}.tar.gz {} +

This gathers all media files then compresses them into tapes labelled media_archive_1.tar.gz across multiple volumes prevent hitting filesystem file limits.

Conversely, extracting subsets of archives instead of entire blobs avoids untarring unnecessary files:

tar xvzf media_archive_3.tar.gz --wildcards "*.mp3"  

This extracts only mp3s out of archive 3.

Archiving enables efficiently freeing production storage of stale data.

13. Automate System Maintenance with cron

Manually running find commands provides one off benefits. But integrating criterial file finding into automated scripts provides ongoing administrative value.

For example, implementing these find commands in cron jobs:

  • Log Rotation – Move 1 week old logs to archive
  • Temp File Reaping – Nightly clean out stale /tmp content
  • Permission Auditing – Daily run checks for insecure permissions

This enables consistently applying maintenance like storage cleanup, permissions management across an entire fleet.

Some examples of cron automation scripts:



find /tmp -type f -mtime +3 -delete
find /var/log -type f -mtime +7 -exec mv {} /mnt/log_backups \;



find / -perm 777 >> /var/log/world_writeable.txt
find /home -user incorrectUser >> /var/log/bad_owners.txt 

Automating slog work consistently maintains proper file system order.


I hope these 40 in-depth examples give you a thorough tour of the versatility of the Linux find command.

Whether trying to locate specific files, execute commands, report on storage waste or automate via cron, Find is the tool enabling slicing through filesystem complexity.

Mastering criterial searching with Find will boost your productivity finding critical files across projects with ease. Combine it with execution commands to eliminate huge swathes of manual edits. Pipe results to other programs for detailed analysis before taking actions.

Integrate Find into your maintenance scripts to enable automatically handling tedious storage upkeep jobs.

The Linux Find command is essential to smooth system administration. Start harnessing its strengths today!

Let me know if you have any other creative examples of Linux find commands I can add!