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

标签 ruby

我从事 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/

相关文章:

php - 使用 Ruby、PHP 或 Python 的音频水印

ruby - 如何将 nginx 设置为 Ruby 应用程序的反向代理(全部在 Docker 中运行)

ruby - 导轨/ Action 包 : warning: already initialized constant ICS

ruby-on-rails - ObjectSpace.count_objects 中每个哈希值的含义是什么?

android - 葫芦-Android : Can we simulate Home button on Android devices for Calabash-Android?

ruby-on-rails - Capistrano 3 钩子(Hook)之前和之后

ruby-on-rails - Railscasts #241 NoMethodError 未定义方法 `[]' 为 nil :NilClass

python - 使用子进程时遇到问题

ruby - 为什么一些未定义的方法(例如 Foo)没有被 `method_missing` 捕获?

ruby - 使用 jemalloc 和 rbenv 编译 Ruby 2.2 的正确方法?