java用replace替换目录_查找某目录下的所有文件并替换特定字符的脚本

大头@ 阅读(319) 评论(0)  编辑  收藏

f23548e9716deb84396629d9825a7c50.png

前两天在工作上碰到要把某个文件夹(里面包含有多层的子文件夹)里的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值