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

在给定路径中搜索符合给定模式的文件并进行归档

阅读更多

这个例子构建在第一个例子(http://www.iteye.com/topic/524316)的基础上,但是需要将搜索到的文件打包到zip文件中。

 

内建的zlib模块可帮助处理gzip文件,对于大多数情况它都够好。在这里我将使用另一个很好的Ruby库,即“rubyzip”,来创建和处理zip归档文件。

 

安装rubyzip

 

gem install rubyzip

 

require 'find'
require 'zip/zip'

puts ""
puts "------------------File Search and Zip-----------------------------"
puts ""
print "Enter the search path    : "
searchpath = gets
searchpath = searchpath.chomp
puts ""
print "Enter the search pattern : "
pattern = gets
pattern = pattern.chomp
puts"----------------------------------------------------------------------"
puts "Searching in " + searchpath + " for files matching pattern " + pattern
puts"----------------------------------------------------------------------"
puts ""
puts"----------------------------------------------------------------------"
puts "Zipping up the found files..."
puts"----------------------------------------------------------------------"
Zip::ZipFile.open("test.zip", Zip::ZipFile::CREATE) {|zipfile|
Find.find(searchpath) do |path|
  if FileTest.directory?(path)
     if File.basename(path)[0] == ?.
       Find.prune
     else
       next
     end
   else
       if File.fnmatch(pattern, File.basename(path))
          puts File.basename(path)
          zipfile.add(File.basename(path), path)  #将符合的文件添加到zip归档中
       end
   end
end
}

 

在命令行输入ruby zip.rb运行该文件,然后输入搜索路径D:\ruby和匹配模式*.rb,下面是一个示例输出:

 

-----------------------File Search and Zip-----------------------------------

Enter the search path    : D:\ruby

Enter the search pattern : *.rb
----------------------------------------------------------------------
Searching in D:\ruby for files matching pattern *.rb
----------------------------------------------------------------------

----------------------------------------------------------------------
Zipping up the found files...
----------------------------------------------------------------------
points_controller.rb
packages_controller.rb
orders_controller.rb

 

这样,在当前目录下便产生了一个test.zip文件。

 

现在输入unzip -l test.zip进行解压,下面是一个示例输出:

 

Archive:  test.zip
Length        Date      Time        Name
--------    --------   ------  -------------------
 2341       11-25-09   17:05   orders_controller.rb
 21000      11-25-09   17:05   packages_controller.rb
 12889      11-25-09   17:05   points_controller.rb
--------                       -------------------
 36230                         3 files

 

分享到:
评论
1 楼 rubynroll 2009-12-04  
find . -name *.rb | xargs tar -zcvf test.tgz

相关推荐

Global site tag (gtag.js) - Google Analytics