summaryrefslogtreecommitdiff
path: root/keep-num
diff options
context:
space:
mode:
Diffstat (limited to 'keep-num')
-rwxr-xr-xkeep-num48
1 files changed, 48 insertions, 0 deletions
diff --git a/keep-num b/keep-num
new file mode 100755
index 0000000..bf89f2f
--- /dev/null
+++ b/keep-num
@@ -0,0 +1,48 @@
+#! /usr/bin/ruby
+
+# Given a directory, print the filenames of all but the last (alphabetically) n files
+# printed filenames are separated by a \0 character, suitable for use with xargs -0
+#
+# Copyright (c) 2005 Florian Reitmeir
+#
+# MIT license
+#
+
+require 'optparse'
+
+$NULL = nil
+$dir = nil
+$num_to_keep = 0
+$prefix = nil
+
+def show_help(parser, code=0, io=STDOUT)
+ io.puts parser
+ exit(code)
+end
+ARGV.options do |opts|
+ opts.on_tail("-h", "--help", "Display this help screen") { show_help(opts) }
+ opts.on("-p", "--path=PATH", String, "path to cleanup") { |$dir| }
+ opts.on("-n", "--number=NUMBER", Integer, "number of entries to keep") { |$num_to_keep| }
+ opts.on("-x", "--prefix=PREFIX", String, "prefix of files") { |$prefix| }
+ opts.on("-0", "--null", String, "terminate strings with zero") { $NULL = 1 }
+ opts.parse!
+end
+
+show_help(ARGV.options,1,STDERR) unless $num_to_keep
+show_help(ARGV.options,1,STDERR) if $num_to_keep < 1
+show_help(ARGV.options,1,STDERR) unless $dir
+show_help(ARGV.options,1,STDERR) unless $prefix
+
+entries = Dir.glob($dir + '/' + $prefix+"*").sort.reverse
+
+if entries.length < $num_to_keep
+ exit
+end
+
+while entries.length > $num_to_keep
+ unless $NULL then
+ puts entries.pop
+ else
+ $> << entries.pop << "\0"
+ end
+end