I'd probably do this with a Perl script:
#!/usr/bin/env perl
use strict;
use warnings;
for my $arg (@ARGV)
{
my($prefix, $number, $suffix) = ($arg =~ m/^ (\D+) (\d+) (\D.*) $/x);
foreach my $i (1..$number-4)
{
my $file = "$prefix$i$suffix";
unlink $file;
print "$file\n";
}
}
For each of the arguments specified on the command line, the name is split into 3 bits: a non-empty prefix of non-digits, a non-empty number of digits, and a suffix consisting of a non-digit followed by any sequence of characters (so file1.bz2
is split into file
, 1
and .bz2
). Then, for each number from 1 to 4 less than the given number, generate a file name from the prefix, the current number, and the suffix. With that file name, unlink the file and print the name. You can tweak it to remove only files that exist, or not report the names, or whatever. There's no fixed limit on the maximum number of files.
You could omit the unlink
and simply print the file names and send those to xargs rm -f
or an equivalent. You could ensure that the names were terminated with a null byte so that names with newlines could be handled correctly by GNU xargs
and the -0
option. Etc.
You could code this in pure Bash if you wished to, though the splitting into prefix, number, suffix will be messier than in Perl. I wouldn't use awk
for this, though it could probably be forced to do the job if you chose to make it do so.