在Ruby中查找并替换文件 [英] Find and replace in a file in Ruby

查看:314
本文介绍了在Ruby中查找并替换文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我用红宝石写的这个小程序。我在这里发现了一个很好的代码,用来查找和替换文件中的某些东西,但似乎不起作用。
以下是代码:

$ $ $ $ $ $ $ $ $ $ =test.txt
FIND = / ,, ^ M /
SEP =\\\


#make substitution
File.read(DOC) .gsub(FIND,SEP)

#检查该行是否已经存在
unique_lines = File.readlines(DOC).uniq

#将结果保存在新文件
File.open('test2.txt','w'){| f | f.puts(unique_lines)}

谢谢大家!

解决方案

我跳过检查你看看这行是否已经存在,通常是像这样(这里我想用'BAR'替换'FOO'): / p>

  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 在这里也可能有点儿迂腐,但是我喜欢它,所以我不会不小心打开一些我并不想要的文件。


I have this little program I write in ruby. I found a nice piece of code here, on SO, to find and replace something in a file, but it doesn't seems to work. Here's the code:

#!/usr/bin/env ruby

DOC = "test.txt"
FIND = /,,^M/
SEP = "\n"

#make substitution
File.read(DOC).gsub(FIND, SEP)

#Check if the line already exist
unique_lines = File.readlines(DOC).uniq

#Save the result in a new file
File.open('test2.txt', 'w') { |f| f.puts(unique_lines) }

Thanks everybody !

解决方案

I skip the check you make to see if the line already exists and usually go with something like this (here I want to replace 'FOO' with 'BAR'):

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

The use of expand_path is also probably a bit pedantic here, but I like it just so that I don't accidentally clobber some file I didn't mean to.

这篇关于在Ruby中查找并替换文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆