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 Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

deleting file from script . . .

Status
Not open for further replies.

youthman

Programmer
Apr 28, 2004
49
US
is there a way to make a script look at a dirctory, compare that to a list of file name in a text file and delete the actual files that do NOT appear in the text file of file names?

The Youthman
 
as long as the file has 1 file name per line.

use strict;

my ($dirname,@files,$file,$keep,$item,);

$dirname = '/path/to/file';

open(FILE, "path/to/file") or die $!;
@files = <FILE>;
close(FILE);

opendir(DIR, "$dirname") or die "can't opendir $dirname: $!";

while (defined($file = readdir(DIR))) {
$keep = 0;
foreach $item (@files){
chomp $item;

if ($item eq $file){
$keep = 1;
}
}
if ($keep == 0){
unlink("$dirname/$file");
}
}

closedir(DIR);
 
nowaday, people use perl because
a) they will not learn 'c'
b) perl is very good+performant, simply because it's 'c'.

but, they still dont think performant...

- suppose this directory grows to Xthousend entries
the chomp statemen will be executed Xthousend times.
it does not matter how big the @files is, chomp it ONCE.
- immediately break the loop if FOUND
- read the output of 'readdir' in an array, like you did
with 'path/to/file' AND SORT both, its more code... and
performance.
- if you don't want to sort, let the system do it for you
'system("ls");' gives sorted output.
- using sorted lists (and little more code) you don't need
each time, to restart the list on the top.
- good code needs time, once writted, gives time.

FINALLY, why re-invent the wheel ?????
let the system do the job.
assumed your list is called must_list, create an is_list
entering: ls >is_list
then use: comm -13 must_list is_list
look at the output, see man pages comm, diff, cmp ...

:) guggach
 
i agree with guggach.

cd /path_to_directory
for f in $((ls -1;cat path_to_textfile path_to_textfile )|sort|uniq -u);do rm $f;done

this will attempt (and fail) to remove any directoriess in /path_to_directory

The perl script will do the same.
 
arn0ld's solution is incredible. It's also a little daunting. I would definitely have a go with that first.

BUT you could always:-

1. create a temporary named KEEP
2. move all the files that exist in your text file to that directory
3. delete any that are left
4. move the files in the KEEP directory back to the original directory

job done!


Kind Regards
Duncan
 
Thanks guys . . . I am trying these suggestions now! thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top