- 论坛徽章:
- 1
|
论坛里有网友问在一个有非常多很大文件的目录中搜索的问题,显然这时我们最关心的是性能的。你可能会说最好用C来做,不过在好的算法下shell的性能也许能够满足要求。这里我们假定我们要查找的东西只会出现一次。那么:
1.我们的程序应该在找到匹配后放弃搜索其它文件;
2.由于文件的行数也很大,所以程序在找到匹配后退出当前文件的搜索。
如果直接用shell来做,可能会碰到命令行长度或参数数目的限制问题,如果用xargs重新装配命令行,也有些很难处理的麻烦。所以索性用perl写了一个,请大家指正:
- #!/usr/bin/perl
- die "usage: $0 path pattern\n" unless @ARGV == 2;
- ($path, $pattern)=@ARGV;
- $, = " ";
- print $path;
- opendir(DH, $path) or die "cannot open dir!";
- while($file = readdir(DH)) {
- next if (!open(FH, "./".$file));
- while(<FH>) {
- print $file, $1 if (m/($pattern)/);
- if ($1) {
- printf STDERR "found in %s line %d!\nexiting...\n", $file, $.;
- exit 0; # change this to "next;" (no ") if you want to find in other files
- }
- }
- close(FH);
- }
- closedir(DH);
- print STDERR "not found.";
- exit 1
复制代码
讨论:
1.如果要查找的东西不止会出现一次,但在每个文件中不会出现多次,那我们就得在其它文件中继续搜索。可以将上面脚本中带注释的一行改为:
2.如果在每个文件中也可能重复出现,那就没办法取巧了,只好将带注释的一行删掉。你最好去用C写个程序,或者找到其它特征在算法上提高查找的速度。
[ 本帖最后由 woodie 于 2006-2-10 21:20 编辑 ] |
|