大头@ 阅读(319) 评论(0) 编辑 收藏
前两天在工作上碰到要把某个文件夹(里面包含有多层的子文件夹)里的XML文件中的一些字符改成其它值的情况,想了想就自己用RUBY写了个脚本
今天没事干,就发上来
#it will copy a new file to another disk like the base dir
#dir path store the file which we want to deal
#要处理的文件夹的结构,注意,并不包括盘符
BASE_DIR = ":/Workspace/IngeniumV512/TS.ROOT/UI/tpl"
#the disk old file store
#IE. here the path is BASE_DIR + BASE_DISK
#要处理的文件夹放在C盘
BASE_DISK = "C"
#the disk new file store
#IE.here the new file will store in NEW_DISK + BASE_DIR
#修改后的文件放在E盘
NEW_DISK = "E"
#define the old value need to replace
#要替换的字符串
SEARCH_REG = 'FldType="15"'
#define the new value to replace the old value
#新的字符串
REPLACE_REG = 'FldType="8"'
#要处理的文件类型
FILE_TYPE = "xml"
def all_over_dir(dir)
Dir.foreach "#{BASE_DISK}#{dir}" do |item|
#判断是否文件
if File.file?("#{BASE_DISK}#{dir}/#{item}")
#判断是否需要处理的文件类型
if /"*.#{FILE_TYPE}/ =~ item
str = ''
need_to_replace = false
begin
f = File.open("#{BASE_DISK}#{dir}/#{item}")
f.each do |line|
if line.include? SEARCH_REG
line.sub! SEARCH_REG , REPLACE_REG
need_to_replace = true
end
str << line
end
#如果查找到要替换的字符,则处理该文件
if need_to_replace
make_dir "#{NEW_DISK}#{dir}"
file = File.new "#{NEW_DISK}#{dir}/#{item}","w"
file.write str
end
rescue => err
puts err
end
end
elsif (item != '..' and item != '.')
#如果是文件夹,则递归处理
all_over_dir "#{dir}/#{item}"
end
end
end
#该方法作用是创建目录,因为我把替换了的文件是拷到别一个盘,同样结构的文件夹中的
def make_dir(path)
p = ''
array = path.split '/'
p = "#{array[0]}"
i = 1
while i < array.size
p << "/#{array[i]}"
begin
Dir.new p
rescue
Dir.mkdir p
end
i += 1
end
end
all_over_dir BASE_DIR