How to delete all the text file in a folder

How to delete all the text file in a folder
LVL 7
tankergoblinAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
vikaskhoriaConnect With a Mentor Commented:
Check the script below, it will remove any .txt files from the given directory.
Do let me know, if you have any doubts.

Vikas.

#!/usr/bin/perl
 
$dirname = <STDIN>;
chomp($dirname);
opendir(DIR,$dirname);
while ( $file = readdir(DIR))
 {
  if ( $file =~ /\.txt$/)
  { 
    unlink $dirname."/".$file;
  }
} 
closedir(DIR);

Open in new window

0
 
mharfouchCommented:
#!/usr/bin/perl

print "content-type: text/html \n\n";      #The header
@files = ("newtext.txt","moretext.txt","yetmoretext.txt");
foreach $file (@files) {
    unlink($file);
}
0
 
lwadwellCommented:
Hi tankergoblin,

try

unlink <*.txt> or die "Cannot unlink files $!";

or, more safely

if () {
    my $c = unlink  or die "Cannot do it $!";
    print "deleted ", $c, " files","\n";
} else {
    print "nothing to delete","\n";
}

lwadwell
0
 
Adam314Commented:

#This will work, but will only die if it doesn't remove any
#If any files are removed (even if some could not be), you will not be notified
unlink </path/to/*.txt> or die "Cannot unlink files $!";
 
 
#### With this, you will be notified for each unsuccessful delete
foreach (</path/to/*.txt>) {
    unlink or warn "Could not remove $_:$!\n";
}

Open in new window

0
 
ozoCommented:
#depending on how you define  text file
-T and unlink || warn "$_ $!" for <folder/*>;
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.