加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Ruby中查找并替换文件

发布时间:2020-12-17 02:52:52 所属栏目:百科 来源:网络整理
导读:我有这个用 ruby编写的小程序.我在SO上找到了一段很好的代码来查找和替换文件中的某些内容,但它似乎不起作用. 这是代码: #!/usr/bin/env rubyDOC = "test.txt"FIND = /,^M/SEP = "n"#make substitutionFile.read(DOC).gsub(FIND,SEP)#Check if the line al
我有这个用 ruby编写的小程序.我在SO上找到了一段很好的代码来查找和替换文件中的某些内容,但它似乎不起作用.
这是代码:

#!/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) }

谢谢大家 !

解决方法

我跳过你做的检查,看看这条线是否已经存在,并且通常是这样的(这里我想用’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的使用在这里也可能有点迂腐,但我喜欢它,所以我不会意外地破坏一些我不是故意的文件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读