`
singleant
  • 浏览: 375271 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

【ruby】ruby实践之实现文件检索小工具

    博客分类:
  • ruby
阅读更多

 

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

 

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

 

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

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

 

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


 

git分支:

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
  • 大小: 77.4 KB
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics