我从事 Ruby 开发大约一周左右,我想知道是否有一种方法可以读取文件,找到特定的句子,然后在该句子之后写下另一行文本。
例如,如果我要求程序定位这一行“你好,今天怎么样?”。我需要做什么才能在同一个文件中但在下一行输出“我很棒,你好吗”。
即在 *.txt
#Hello, how are you?
在*.txt中变成这个
#Hello, how are you?
#I am great, how are you?
我所做的研究让我找到了;
File.readlines("FILE_NAME").each{ |line| print line if line =~ /check_String/ }
它返回特定的关键字,而这个将单词更改为其他内容。
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")
如果有人有指向可以帮助我的教程的链接或任何可以帮助我理解需要做什么的东西,那么我将是一个非常快乐的露营者。
谢谢你
最佳答案
由于您可能要在文件的中间添加内容,因此您将不得不构建一个新文件。使用 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
原始 sample.txt(减去 # 符号):
#This line should not be found.
#Hello, how are you?
#Inserted Line should go before this one.
运行脚本后(减去 # 符号):
#This line should not be found.
#Hello, how are you?
#I am great, how are you?
#Inserted Line should go before this one.
关于ruby - Ruby 可以打开一个文件,找到一个关键字或单词,然后在该行之后写文本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5251922/