Ruby implements a powerful batch file deletion script sharing and ruby deletes file scripts.
Recently, the number of apk packages on the server has increased, making manual rm operations too troublesome, it took several minutes to write a script to delete a specified directory in batches based on the last modification time and wildcard matching. After adding this script to crontab, you will no longer have to worry about the disk space occupied by redundant installation packages.
Brief code
Copy codeThe Code is as follows:
#! /Usr/bin/env ruby
# Encoding: UTF-8
# Usage: ruby removeOldFiles. rb "dest_file_pattern" days_ago
DestFilePattern = ARGV [0]
DaysAgo = ARGV [1]
EdenTime = Time. now. to_ I-daysAgo. to_ I * 86400
Dir [destFilePattern]. each {| child |
System "rm-rfv # {child}" if (File. mtime (child). to_ I <edenTime)
}
How to Use
It is easy to use. The rules are as follows:
Copy codeThe Code is as follows:
Ruby removeOldFiles. rb "dest_file_pattern" days_ago
For example, if we want to delete all the apk files in the/tmp directory that were last modified three days ago, we only need to do this.
Copy codeThe Code is as follows:
Ruby removeOldFiles. rb "/tmp/*. apk" 3
Why do the first parameter use double quotation marks?
The first parameter is the path containing the wildcard. In shell, a tool named glob will match the path containing the wildcard to a specific file, such as a piece of code.
Copy codeThe Code is as follows:
! /Usr/bin/env ruby
# Encoding: UTF-8
Puts ARGV. length
ARGV. each do | a |
Puts "Argument: # {}"
End
We pass in the path parameter containing the wildcard and the result is the name of the matched glob file (provided that the wildcard can match the file ).
Copy codeThe Code is as follows:
10: 41 $ ruby test. rb *. txt
2
Argument: abc.txt
Argument: def.txt
To avoid glob operations, double quotation marks must be used for path parameters containing wildcards.
Copy codeThe Code is as follows:
10: 41 $ ruby test. rb "*. txt"
1
Argument: *. txt
Therefore, when using the script, the first parameter must use double quotation marks.
How to traverse files in subdirectories
For example, if we want to traverse/tmp/abc/def.txt, we can use/tmp/**/. txt.