Practical Guide to Linux find Command: Finding, Moving, and Archiving Files by Time
In Linux system administration, it's common to filter, move, and archive files based on their modification time. This guide demonstrates how to use the find command for these tasks.
1. Moving All Files (Excluding Directories) in the Current Directory
To move all regular files (excluding directories themselves) from the current directory to /opt/shell:
find . -type f -exec mv {} /opt/shell ;
Alternatively, using xargs:
find . -type f | xargs -I '{}' mv {} /opt/shell
Note: For a large number of files, xargs is generally more efficient. However, the -exec method is safer as it avoids issues with filenames containing special characters (like spaces or newlines).
2. Finding Files by Time Range
First, you can count the total number of files in a directory:
find . -type f | wc -l
To find and count files modified more than 120 days ago:
find . -mtime +120 | wc -l
Time Parameter Explanation:
-mtime +n: Find files modified more than n * 24 hours ago.-mtime -n: Find files modified less than n * 24 hours ago.-mtime n: Find files modified exactly n * 24 hours ago.
3. Moving Files by Time to a Specified Directory
To move files modified more than 90 days ago to the /var/tmp/date_90 directory:
find . -mtime +90 -exec mv {} /var/tmp/date_90 ;
Best Practices:
- Always verify the file count before moving to prevent mistakes.
- For a very large number of files (e.g., over 200,000 small files), consider processing in batches to avoid high system load.
4. Checking Directory Size and Creating an Archive
After moving files, check the size of the target directory:
du -sh /var/tmp/date_90
It's generally recommended to keep individual archive sizes around 10-15 GB for easier transfer and storage.
Finally, create a compressed archive using tar:
tar -zcvf date_90.tar.gz /var/tmp/date_90/
Command Flag Explanation:
-z: Use gzip compression.-c: Create an archive.-v: Verbose output (optional).-f: Specify the archive filename.
By following these steps, you can successfully filter files by time, move them, and create a compressed archive for backup or management.