#!/usr/bin/perl

# Strip away all text from a file name if it has one
# or more digits.
#
# Usage:  num_only *.wav
#
#   Renames 04.wav 06--Tune.wav to 04.wav 06.wav
#

$numdigits = 3;		# Set default # of digits here

if ($#ARGV < 0) {
 print << "ENDPRINT";

Version 1.0, David Edwards <davidbtdt@gmail.com>

num_only - For files with format "*nn*", where nn is a sequence
of digits, strip away all other text.  The extension is not effected.
		 
             *nn*.ext -->  nn.ext

  Usage:  num_only [num_digits] file_name...
 
  num_digits:     Number of digits in each number (defaults to $numdigits)

  Example:  num_only 3 6test.fred.wav 08--Tune.wav
  
  Renames: 06test_9.fred.wav --> 006.wav
           08--Tune.wav    --> 008.wav

NOTE: Renaming is based on the first occurance of a
string of digits. Subsequent digit strings are ignored.

ENDPRINT
 exit 1;
}

# If first arg is all digits, override the default
# and skip to the next command line arg
if ($ARGV[0] =~ /^\d+$/) {
	$numdigits = $ARGV[0];
	shift;
}

$fmt="%0${numdigits}d";

foreach $fname (@ARGV) {

	# If there is a "." break it into name and ext
	if ($fname =~ /\./) {
		$ext = $fname;
		$ext =~ s/.*(\..*$)/$1/;

		$base = $fname;
		$base =~ s/(.*)\..*$/$1/;
		
	} else {
		$base = $fname;
		$ext = '';
	}
	
	# If there is a digit string, use it,
	# otherwise skip the file.
	if ($base =~ /(\d+)/) {
		$num = $1;
	} else {
		next;
	}
	
	$num = sprintf($fmt,$num);
	
	$newname = "$num$ext";

	# This is careful to not overwrite any files!
	if ("$newname" ne "$fname") {
		if (-e $newname) {
			print "Destination exists: $fname SKIP -> $newname\n";
		} else {
			if (rename("$fname","$newname")) {
				print "$fname -> $newname\n";
			} else {
	   			print "Cannot rename $fname to $newname\n";
			}
		}
	}
}
