我大约一个星期左右进入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)
如果有人有一个教程链接可以帮助我或任何可以帮助我理解需要做什么,那么我将是一个非常愉快的露营者.
非常感谢你
ruby ×1