#!/usr/bin/perl # nextFilename # This script is for use in a situation when you are saving data in several # files in one directory and you want the filenames to follow a simple sequence # where the filenames have a number in them. # (e.g. "data_001.txt", "data_002.txt", "data_003.txt", ...) # The first command-line argument specifies the filename that is first # in the sequence - i.e. it specifies the pattern for the sequence. # The second command-line argument specifies the directory # where these files are - if there is no second command-line argument, # the current directory will be used. # The script looks at what files exist in the specified directory # and then outputs (to STDOUT) the name of the next file in the sequence # - i.e. the first filename in the sequence that has not yet been used. # Example of use: nextFilename "data_001.txt" # If the specified directory had existing files: "data_001.txt", "data_002.txt" # then the above command would output "data_003.txt". # Note that if there are any "holes" (missing files) in the sequence, # the script will output the name of the first "hole". # E.g. if there were files "data_001.txt and "data_003.txt" # but no "data_002.txt", the above command would output "data_002.txt". # # Cameron Hayne (macdev@hayne.net) February 2009 use strict; use warnings; use Cwd; my $scriptName = "nextFilename"; if (scalar(@ARGV) < 1) { die "Usage: $scriptName firstFilename [dirName]\n"; } sub fatalError($) { my ($msg) = @_; print "$scriptName: $msg\n"; exit 1; } my $firstFilename = shift; # 1st command-line arg # if no dir supplied (as 2nd command-line arg), use the current directory my $dirName = @ARGV ? $ARGV[0] : getcwd(); fatalError("$dirName is not a directory") unless -d $dirName; fatalError("The name '$firstFilename' does not contain a number") unless ($firstFilename =~ /^(.*\D)(\d+)(\D*)$/); my $startname = $1; my $number = $2; my $endname = $3; # cd to the specified directory to make things easier chdir($dirName) or fatalError("Can't chdir to $dirName: $!"); while (-e "$startname$number$endname") { ++$number; } print "$startname$number$endname\n";