summaryrefslogtreecommitdiff
path: root/keep-num
blob: bf89f2f0add1212824b07f304731f31f539768cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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