使用Ruby替换文件中的特定行 [英] Replace a specific line in a file using Ruby

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

问题描述

我有一个文本文件(a.txt),如下所示.

I have a text file (a.txt) that looks like the following.

open
close
open
open
close
open

我需要找到一种方法将第三行替换为"close".我做了一些搜索,大多数方法都涉及搜索行而不是替换行.因为我不想将所有的打开"都变成关闭",所以在这里真的不能做到.

I need to find a way to replace the 3rd line with "close". I did some search and most method involve searching for the line than replace it. Can't really do it here since I don't want to turn all the "open" to "close".

基本上(对于这种情况)我正在寻找IO.readlines("./a.txt")[2]的写入版本.

Essentially (for this case) I'm looking for a write version of IO.readlines("./a.txt") [2].

推荐答案

诸如此类的事情

lines = File.readlines('file')
lines[2] = 'close' << $/
File.open('file', 'w') { |f| f.write(lines.join) }

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

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