---
title: "【ruby】ruby实践之实现文件检索小工具"
author: "singleant"
date: "2012-12-19T14:14:59Z"
tags: []
categories: ["编程语言"]
slug: "ruby-ruby"
draft: false
lastmod: "2012-12-19T14:23:42Z"
id: 1750350
url: "https://singleant.iteye.com/blog/1750350"
---

ruby学习进入实践阶段。花了点时间用ruby实现了一个文件检索功能。小工具没什么好去说的，主要是本人通过这个熟悉ruby的一些api。

 

**需求**：根据输入的关键字在指定的目录下，搜索指定格式的文件。返回文件名或文件内容包含该关键子的文件列表。

 

**输入**：关键字 keyword，指定目录 path,文件格式 filepattern

**输出**：文件名或文件内容包含keyword的文件列表

 

效果如下，在"/home/yblin/rubyspace"下，\*.rb的文件中，检索包含length关键字的文件：

![](http://dl.iteye.com/upload/attachment/0078/1393/e081210b-a333-39f1-a1d9-5a7e5ccbca68.png)

 

git分支：

[https://github.com/abingsky37/filesearcher](https://github.com/abingsky37/filesearcher)

 

（注工具用到了ptools，需要通过sudo gem install ptools安装）

源码：

 

```
require "ptools"


class Filesearch
  
 def self.search(path,keyword,filepattern)
     if !File.exist?(path)
        return
     end 

     if File.directory?(path)
        searchInDir(path,keyword,"|",filepattern) 
     else
        grepFile(path,keyword,"|") 
     end
 end 

 def self.searchInDir(dir,keyword,prefix,filepattern)
    puts "#{prefix}___search in dir #{dir}:"
    Dir.chdir(dir)
    files=Dir.glob("*"+keyword+"*")
    if !files.empty?
      puts "   #{prefix}___ Files that filename contains \"#{keyword}:#{files}\""
    end
    Dir.foreach(dir){|x|
    next if x == "."
    next if x == ".."
    Dir.chdir(dir)
    if File.directory?(x)
          searchInDir(Dir.getwd+"/"+x,keyword,"   "+prefix,filepattern)
    elsif
       if File.fnmatch(filepattern,x)
        Dir.chdir(dir) 
        grepFile(Dir.getwd+"/"+x,keyword,prefix)
       end
    end
    }

 end

 def self.grepFile(fpath,keyword,prefix)
   if !File.exist?(fpath) || File.directory?(fpath)
   return
   end
   if !File.binary?(fpath)
    IO.foreach(fpath){|x| 
     if x.index(keyword) != nil
      puts "   #{prefix}#{fpath} contains keyword \"#{keyword}\""
      puts "                 #{x}"
      puts "                 ..."
      break
     end
    } 
   end
 end 

end

if ARGV.empty? || ARGV.length< 3
   puts "right format: ruby -w Filesearch.rb  path keyword filepattern"
else
   Filesearch.search(ARGV[0],ARGV[1],ARGV[2])
end
```