- 批量替换 指定目录及其子目录中所有文件内的字符串
#!/usr/bin/env ruby
class File
class << self
def gsub!(s,t,dir=Dir.pwd)
Dir.entries(dir).each do |f|
puts f
next if(f == "." || f == "..")
if(File.file? f) then
ct = IO.readlines(f).join
if ct.index(s) then
puts "replace file <#{f}>."
ct.gsub!(s,t)
File.open(f,"w+"){|ff|ff.write ct}
end
elsif(File.directory? f) then
self.gsub!(s,t,File.join(dir,f))
end
end
end
#end of <<
end
end
使用的时候:
File.gsub!("reg","--reg--",Dir.pwd)
就可以了.
- 批量删除指定目录及子目录下含有某个扩展名的文件
#!/usr/bin/env ruby
class File
class << self
def grm(path,ext)
Dir.entries(path).each do |f|
next if (File.basename(f) == '.' || File.basename(f) == '..')
if File.directory?(File.join(path,f))
grm(File.join(path,f),ext)
elsif f != File.basename(f).chomp(ext)
puts File.join(path,f)
FileUtils.rm_f(File.join(path,f))
end
end
end
#end of <<
end
end
File.grm("C:\\scripts",'log')
可以删除scripts下面及该目录的子目录下面所有log文件.
- 获得本机IP
class Socket
class << self
def ips
Socket.getaddrinfo(Socket.gethostname, nil)
end
end
end
Socket.ips可以获得本机的IP列表数组.