如何将信息从一个文本文件重定向到另一个文本文件

时间:2014-07-18 19:52:10

标签: ruby

使用一个文本文件中的给定字符串获取一行文本并将其发送到另一个文本文件的最佳方法是什么?

目前有这个:

def redirect_file
    File.readlines('file_name.txt') do |line|
        case test
        when line.include?("my_string_phrase")
            <Want to send the line(s) with my_string_phrase to a separate document>
        when line.include?("my_string_phrase2")
            <Want to send the line(s) with my_string_phrase2 to a separate document>
    end
end

编辑:需要一个案例陈述,抱歉。

4 个答案:

答案 0 :(得分:1)

我将使用::foreach::open方法编写此代码。

def redirect_file(input_file, output_file)
  File.open(output_file, 'wb') do |file|
    File.foreach(input_file) do |line|
      if line.include?("my_string_phrase")
        file.puts line
      end
    end
  end
end

答案 1 :(得分:1)

def redirect_file
  file1 = File.open('file1.txt', 'w')

  File.readlines('file_name.txt') do |line|
    if line.include?("my_string_phrase")
      file1.puts line
    end
  end

  file1.close
end

答案 2 :(得分:0)

可能有点hackish但是,打开文件在文件外面写,然后使用两者。

File.open("test.txt", "w+") do |f|
  File.readlines('file_name.txt') do |line|
    if line.include?("my_string_phrase")
      F.puts(line)
  end
end

另一种选择是构建一个你想要读取的行数组,然后将它们写在一个单独的块中,这样它就会更清晰,更可重用。它有使用更多内存的缺点。

  a = Array.new
  File.readlines('file_name.txt') do |line|
    if line.include?("my_string_phrase")
      a.push(line)
  end
  File.open("test.txt", "w+") do |f|
     a.each{ |i| f.puts(i)}
  end  

答案 3 :(得分:0)

只需打开目标文件并将选定的行写入其中。这些方面应该有用:

def redirect_file
    File.open('destination.txt', 'w+') do |dest|
        File.readlines('file_name.txt') do |line|
            dest.write(line) if line.include?("my_string_phrase")
        end
    end
end

顺便说一句,请注意“#34;重定向”这个词的通常含义。在I / O环境中,与您询问的内容有所不同。

相关问题