Ruby可以打开一个文件,查找关键字或单词然后在该行之后写文本吗?

Joe*_*ato 1 ruby

我大约一个星期左右进入Ruby开发,我想知道是否有办法在文件中读取,找到一个特定的句子,然后在该句子之后写另一行文本.

例如,如果我让程序找到这条线"你好,今天怎么样?".我需要做什么来输出"我很棒,你好吗"在同一个文件中,但在下一行.

IE中的*.txt

#Hello, how are you?
Run Code Online (Sandbox Code Playgroud)

在*.txt中变成这个

#Hello, how are you?
#I am great, how are you?
Run Code Online (Sandbox Code Playgroud)

我所做的研究让我找到了;

File.readlines("FILE_NAME").each{ |line| print line if line =~ /check_String/ }
Run Code Online (Sandbox Code Playgroud)

返回特定关键字,以及将其更改为其他关键字的关键字.

def ChangeOnFile(file, regex_to_find, text_to_put_in_place)
  text= File.read file
  File.open(file, 'w+'){|f| f << text.gsub(regex_to_find, text_to_put_in_place)}
end

ChangeOnFile('*.txt', /hello/ , "goodbye")
Run Code Online (Sandbox Code Playgroud)

如果有人有一个教程链接可以帮助我或任何可以帮助我理解需要做什么,那么我将是一个非常愉快的露营者.

非常感谢你

Mat*_*att 5

由于您可能要添加到文件的中间,因此您将不得不构建一个新文件.使用Tempfile非常有用,因为您可以临时构建它,然后使用FileUtils替换原始文件.您有几个选项而不使用正则表达式,如下所示.我还包括一个正则表达式示例.我已经验证此代码适用于Ruby 1.9.2.

代码:

require 'tempfile'
require 'fileutils'

file_path = 'C:\Users\matt\RubymineProjects\test\sample.txt'
line_to_find = 'Hello, how are you?'
line_to_add = 'I am great, how are you?'

temp_file = Tempfile.new(file_path)

begin
  File.readlines(file_path).each do |line|
    temp_file.puts(line)
    temp_file.puts(line_to_add) if line.chomp == line_to_find

    #or... if you just want to see if a given line contains the
    #sentence you are looking for you can:
    #temp_file.puts(line_to_add) if line.include?(line_to_find)

    #or... using regular expressions:
    #temp_file.puts(line_to_add) if line =~ /Hello, how are you/
  end
  temp_file.close
  FileUtils.mv(temp_file.path,file_path)
ensure
  temp_file.delete
end
Run Code Online (Sandbox Code Playgroud)

原始sample.txt(减去#符号):

#This line should not be found.
#Hello, how are you?
#Inserted Line should go before this one.
Run Code Online (Sandbox Code Playgroud)

运行脚本后(减去#符号):

#This line should not be found.
#Hello, how are you?
#I am great, how are you?
#Inserted Line should go before this one.
Run Code Online (Sandbox Code Playgroud)