Ruby 在文件中查找特定文本,将其从当前文件中剪切,然后将其粘贴到另一个文件中

Ruby 在文件中查找特定文本,将其从当前文件中剪切,然后将其粘贴到另一个文件中,ruby,regex,file-io,Ruby,Regex,File Io,我试图在一个.rb文件中找到一段代码,一旦找到,我想从当前文件中剪切它,然后将它粘贴到另一个现有文件中。举个例子: def move_example_block(example_description, source_file,destination_file) lines = File.readlines("#{Dir.pwd}/spec/api/#{source_file}_spec.rb") desired_block = lines.join[/it "should

我试图在一个.rb文件中找到一段代码,一旦找到,我想从当前文件中剪切它,然后将它粘贴到另一个现有文件中。举个例子:

  def move_example_block(example_description, source_file,destination_file)
    lines = File.readlines("#{Dir.pwd}/spec/api/#{source_file}_spec.rb")
    desired_block = lines.join[/it "should get test data for build" do(.*)end/m]
    temp = desired_block.freeze
    puts temp
    filename = "#{Dir.pwd}/spec/api/#{source_file}_spec.rb"
    text = File.read(filename)
    puts = text.gsub(/it "#{example_description}" do(.*)end/m, "end")
    File.open(filename, "w") { |file| file << puts }

    filename = "#{Dir.pwd}/spec/api/#{destination_file}_spec.rb"
    text = File.read(filename)
    puts = text.gsub(/end/, temp)
    File.open(filename, "w") { |file| file << puts }
  end
file1.rb具有以下功能:

RSpec.describe 'Get Test  Data' do

  it "should get test data for build" do |example|
    log_start_test("#{example.description}")
    get_test_data
    log_complete_test("#{example.description}")
  end

end
我想找到
it“应该获得构建的测试数据”do | example |
,然后剪切这段代码:

 it "should get test data for build" do |example|
    log_start_test("#{example.description}")
    get_test_data
    log_complete_test("#{example.description}")
  end
并将其粘贴到另一个文件。 到目前为止,我已经能够使用以下内容找到所需的字符串:

    File.open("#{Dir.pwd}/spec/api/test_data_search_spec.rb") do |f|
      f.each_line do |line|
        if line =~ /do |example|/
          puts "Found root #{line}"
        end
      end
    end

只是无法找出精确的正则表达式来找到所需的块,然后如何从文件中剪切并粘贴到另一个文件中?任何想法都很好。

正则表达式不适合解析代码


您可以将其用作问题的现有解决方案。

谢谢@phoet。这对于特定的方法来说是可行的,但我更希望移动rspec示例代码块。但以下是我最后使用的示例:

  def move_example_block(example_description, source_file,destination_file)
    lines = File.readlines("#{Dir.pwd}/spec/api/#{source_file}_spec.rb")
    desired_block = lines.join[/it "should get test data for build" do(.*)end/m]
    temp = desired_block.freeze
    puts temp
    filename = "#{Dir.pwd}/spec/api/#{source_file}_spec.rb"
    text = File.read(filename)
    puts = text.gsub(/it "#{example_description}" do(.*)end/m, "end")
    File.open(filename, "w") { |file| file << puts }

    filename = "#{Dir.pwd}/spec/api/#{destination_file}_spec.rb"
    text = File.read(filename)
    puts = text.gsub(/end/, temp)
    File.open(filename, "w") { |file| file << puts }
  end
def move_example_块(example_说明、源文件、目标文件)
lines=File.readlines(“#{Dir.pwd}/spec/api/#{source_File}\u spec.rb”)
所需的_block=lines.join[/it“应该获取构建的测试数据”do(.*)end/m]
温度=所需的块冻结
使温度升高
filename=“#{Dir.pwd}/spec/api/#{source_file}\u spec.rb”
text=File.read(文件名)
puts=text.gsub(/it“#{example_description}”do(.*)end/m,“end”)
打开(文件名,“w”){| File | File