1831339 Members
3386 Online
110024 Solutions
New Discussion

find script

 
Edgar_8
Regular Advisor

find script

Hi,

We would like to script a find file search, currentlyhave a file containing a list of files & want to do a
"find" for the file and to out put that the file was found and is in x directory. The script must also
cater for files not found. Any ideas would be most appreciated.

Thanks in advance!
6 REPLIES 6
RAC_1
Honored Contributor

Re: find script

Say you have a list of files to be found in file input file.

for i in `cat input_file`
do
find /dir_where_to_find -name $i
if [$? -eq 0]
then
echo $i >> /tmp/found_files.txt
else
echo $i >> /tmp/file_not_found.txt
fi
There is no substitute to HARDWORK
Edgar_8
Regular Advisor

Re: find script

Hi RAC,

Thanks for the info, we have used that but what if we dont no the search directory? How would do a global search, if the file is found then the output to be redirected to log file saying ie. "$file found in directory_name"?
RAC_1
Honored Contributor

Re: find script

Say you have a list of files to be found in file input file.

for i in `cat input_file`
do
find / -depth -name $i -print -exec echo {} >> /tmp/files.txt
if [$? -eq 0]
then
echo $i >> /tmp/found_files.txt
else
echo $i >> /tmp/file_not_found.txt
fi
There is no substitute to HARDWORK
Thierry Poels_1
Honored Contributor

Re: find script

modified:

for i in `cat input_file`
do
find / -name $i >> /tmp/found_files.txt
if [$? -ne 0]
echo $i >> /tmp/file_not_found.txt
fi

found_files will contain full pathname & filename.

regards,
Thierry.
All unix flavours are exactly the same . . . . . . . . . . for end users anyway.
Alan Turner
Regular Advisor

Re: find script

Based on RAC's submission, to search globally and log where found do:

for i in `cat input_file`
do
find / -name "$i" > /tmp/found_files.tmp
if [$? -eq 0]
then
echo "FOUND:$i"
cat /tmp/found_files.tmp
else
echo "FAILED TO FIND:$i"
fi
done >> /tmp/results.txt

Strictly, if run with privilege, e.g. as root, you should avoid predictable names in shared directories in case some malicious person creatred /tmp/results.txt as a symbolic link to something important, e.g. /etc/fstab
Rodney Hills
Honored Contributor

Re: find script

How about in perl. This uses "ls -1R" to generate list of all filenames. It goes through the file system once and generates a list of all directories the filename is located.

#!/usr/bin/perl
$startdir="/";
open(INP,"while() { chomp; $names{$_}=[]; }
close(INP);
$lastdir=$startdir;
open(LS,"ls -1R $startdir|");
while() {
chomp;
next unless $_;
if (substr($_,0,1) eq "/") { $lastdir=$_; }
else {
push(@{$names{$_}},$lastdir) if $names{$_};
}
}
close(LS);
foreach $name (sort keys %names) {
$dirs=$names{$name};
if (scalar @$dirs) {
print $name," ",join(",",@$dirs),"\n";
} else {
print $name," NOT FOUND...\n";
}
}

HTH

-- Rod Hills
There be dragons...