Ruby 目录中的行替换是否清除整个文件?
我试图递归地将Ruby 目录中的行替换是否清除整个文件?,ruby,replace,Ruby,Replace,我试图递归地将index.html文件中的一整行内容替换为具有子目录的目录 上面的代码列出了我正在使用var“pattern”搜索的正确行,但当我运行它时,它会删除index.html文件中的所有内容 pattern = "Keyword" replacement = "<td width=\"30\"><img src=\"styles/img/trans.gif\" width=\"30\"></td>" Dir.glob('/Users/root/D
index.html
文件中的一整行内容替换为具有子目录的目录
上面的代码列出了我正在使用var“pattern”搜索的正确行,但当我运行它时,它会删除index.html文件中的所有内容
pattern = "Keyword"
replacement = "<td width=\"30\"><img src=\"styles/img/trans.gif\" width=\"30\"></td>"
Dir.glob('/Users/root/Desktop/directory/test/**/index.html') do |item|
next unless File.file?(item)
File.open(item, "w+:ASCII-8BIT") do |f|
f.each_line do |line|
if line.match(pattern)
my_line = line
line.sub(my_line, replacement)
end
end
end
end
pattern=“关键字”
替换=“”
Dir.glob('/Users/root/Desktop/directory/test/**/index.html')do | item|
下一个文件。文件?(项目)
打开(项目“w+:ASCII-8BIT”)do | f|
f、 每条线都要做|
if line.match(模式)
我的线
line.sub(车型年款,更换)
结束
结束
结束
结束
我做错了什么?您使用的是
文件。使用打开模式w+
打开,根据Ruby文档,该模式是:
“w+”读写,将现有文件截断为零长度或创建新文件进行读写
要读取文件并放置一些行,请使用r
:
File.open(item, "r:ASCII-8BIT")
您需要先读取文件,生成预期输出,然后再写入:
你确定你的index.html
不止一行吗?在你的代码中做一个简单的计数,而不是sub
。而不是使用w+
使用a
进行追加。事实上,我忽略了读和写之间的分离。当我“puts output.join”时,您的代码可以工作。它用remplacement行打印整个文件,但它生成了一个空文件。哎呀,我的错,我错过了f.write方法。谢谢你的帮助!
Dir.glob('/Users/root/Desktop/directory/test/**/index.html') do |item|
next unless File.file?(item)
output = IO.readlines(item).map do |line|
if line.match(pattern)
replacement
else
line
end
end
File.open(item, "w+:ASCII-8BIT") do |f|
f.write output.join
end
end
end