Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

delete file with similar names

Status
Not open for further replies.
Apr 30, 2003
56
US
Hi,
I guess this might come down to more of a unix command then perl question. I want to write a script that will delete any file with similar name for the particular month.
The files under the directory are name such as below:
-rw-r----- 1 oracle dba 20353024 Jul 3 23:00 exprmanFri_0703152300.dmp
-rw-r--r-- 1 oracle dba 6066 Jul 3 23:00 exprmanFri_0703152300.log
-rw-r----- 1 oracle dba 20418560 Jul 10 23:00 exprmanFri_0710152300.dmp
-rw-r--r-- 1 oracle dba 6067 Jul 10 23:00 exprmanFri_0710152300.log
-rw-r----- 1 oracle dba 19423232 Jul 17 23:00 exprmanFri_0717152300.dmp
-rw-r--r-- 1 oracle dba 6067 Jul 17 23:00 exprmanFri_0717152300.log

My script is below:
#!/usr/bin/perl
$dir = '/apps/oracle/admin/gcprod/dpdump';
print "Enter the two digit month number for the file to be deleted: ";
$mon = <STDIN>;
chomp($mon);
opendir DIR, $dir;
foreach my $file (readdir(DIR)) {
$len = length $file;
$str1 = substr($file, $len-14, 2);
next if $file =~ /^\./; #skip ., .., etc
next unless -f "$dir/$file"; # skip non-files
if ($str1 = $mon)
{
system ("rm");
}
# print "The month of the file is $str1 \n"; for debug purpose
}
closedir DIR;

I am not sure how I should write the rm command the remove the files I wanted. Please advise. Will rm exprman*_$mon* work? I don't have a test system to test this. So, do not want to issue this and delete any files that I actually needed.
 
I might do something like this:
Code:
use warnings;
use strict;
use File::Find;

my $dir = './txt/';	# Change this to your directory
my $month = '07'; 	# Get this from STDIN, command line, etc.
find( {wanted => \&remove_files_by_month, follow => 0}, $dir);

sub remove_files_by_month() {
	if (-f $_) {
		if (substr($_, length($_)-14, 2) eq $month) {
			print "unlink $_\n";	# Use this for testing
			#unlink $_;	# Uncomment this line to delete files
		}
	}
}
And you can nearly always test to some degree; in this case the script prints the commands that would have run (see the comments.) Alternately, you could copy a representative set of log files to a temporary location in your home directory or somewhere else and operate on the copies instead of the originals.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top