在 Ruby 中的文件中查找并替换
我有一个用 ruby 编写的小程序。我在这里找到了一段很好的代码,用于查找和替换文件中的某些内容,但它似乎不起作用。 代码如下:
#!/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) }
谢谢大家!
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 !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会跳过检查该行是否已存在的操作,并且通常会使用类似的内容(这里我想用“BAR”替换“FOO”):
expand_path
的使用也可能是这里有点迂腐,但我喜欢它,这样我就不会意外地破坏一些我无意的文件。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'):
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.