
这是代码:
#!/usr/bin/env rubyDOC = "test.txt"FIND = /,^M/SEP = "\n"#make substitutionfile.read(DOC).gsub(FIND,SEP)#Check if the line already existunique_lines = file.readlines(DOC).uniq#Save the result in a new filefile.open('test2.txt','w') { |f| f.puts(unique_lines) } 谢谢大家 !
解决方法 我跳过你做的检查,看看这条线是否已经存在,并且通常是这样的(这里我想用’bar’替换’FOO’):full_path_to_read = file.expand_path('~/test1.txt')full_path_to_write = file.expand_path('~/test2.txt')file.open(full_path_to_read) do |source_file| contents = source_file.read contents.gsub!(/FOO/,'bar') file.open(full_path_to_write,"w+") { |f| f.write(contents) }end expand_path的使用在这里也可能有点迂腐,但我喜欢它,所以我不会意外地破坏一些我不是故意的文件.
总结以上是内存溢出为你收集整理的在Ruby中查找并替换文件全部内容,希望文章能够帮你解决在Ruby中查找并替换文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)