使用Ruby替换文件中的特定行

使用Ruby替换文件中的特定行,ruby,line,overwrite,Ruby,Line,Overwrite,我有一个文本文件(a.txt),如下所示 open close open open close open 我需要找到一种方法,用“关闭”替换第三行。我做了一些搜索,大多数方法都是搜索行而不是替换行。因为我不想把所有的“打开”都变成“关闭”,所以我不能在这里这么做 基本上(在本例中),我正在寻找IO.readlines(“./a.txt”)[2]的写版本。类似这样的东西怎么样: lines = File.readlines('file') lines[2] = 'close' <<

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

open
close
open
open
close
open
我需要找到一种方法,用“关闭”替换第三行。我做了一些搜索,大多数方法都是搜索行而不是替换行。因为我不想把所有的“打开”都变成“关闭”,所以我不能在这里这么做


基本上(在本例中),我正在寻找IO.readlines(“./a.txt”)[2]的写版本。

类似这样的东西怎么样:

lines = File.readlines('file')
lines[2] = 'close' << $/
File.open('file', 'w') { |f| f.write(lines.join) }
lines=File.readlines('File'))
行[2]=“关闭”
在将
FNameIn
的内容写入
FNameOut
时,有几种方法可以将
FNameIn
的第三行替换为“had”

#1读一行,写一行

如果文件很大,您应该从输入文件中读取,然后一次一行写入输出文件,而不是将大字符串或字符串数组保留在内存中

fout = File.open(FNameOut, "w")
File.foreach(FNameIn).with_index { |s,i| fout.puts(i==2 ? "had" : s) }
fout.close
让我们检查
FNameOut
是否正确写入:

puts File.read(FNameOut)
my
dog
had
fleas
请注意,如果字符串尚未以记录分隔符结尾,则写入记录分隔符。1。此外,如果省略了
fout.close
FNameOut
fout
超出范围时关闭

#2使用正则表达式

r = /
    (?:[^\n]*\n) # Match a line in a non-capture group
    {2}          # Perform the above operation twice
    \K           # Discard all matches so far
    [^\n]+       # Match next line up to the newline
    /x           # Free-spacing regex definition mode

File.write(FNameOut, File.read(FNameIn).sub(r,"had"))

puts File.read(FNameOut)
my
dog
had
fleas
1
File.superclass#=>IO
,因此
IO
的方法由
File
继承

puts File.read(FNameOut)
my
dog
had
fleas
r = /
    (?:[^\n]*\n) # Match a line in a non-capture group
    {2}          # Perform the above operation twice
    \K           # Discard all matches so far
    [^\n]+       # Match next line up to the newline
    /x           # Free-spacing regex definition mode

File.write(FNameOut, File.read(FNameIn).sub(r,"had"))

puts File.read(FNameOut)
my
dog
had
fleas