开发者

Reading a text file and writing to another text file in Ruby

开发者 https://www.devze.com 2023-04-03 20:30 出处:网络
I want to take a text file, foo.txt that is a list of 10 digit numbers, each on their own line. If a number meets a certain set of parameters, I want that line written to bar.txt.

I want to take a text file, foo.txt that is a list of 10 digit numbers, each on their own line. If a number meets a certain set of parameters, I want that line written to bar.txt.

What is an easy way to开发者_如何学JAVA do this in straight up Ruby? I'm new to file parsing in Ruby and just need a little help to get started.


In an app you could do something like so:

File.open("output.txt", "w") do |out|
  IO.readlines("input.txt").each do |line|
     if (line =~ /^1/)
          out.puts(line)
     end
  end
end

If you want to open the input as you did the output you could use "r" instead of "w".

The readlines method will read in the whole file at once so for big files it's not the best idea but for small ones it's not a big deal and is easy. Note how the blocks take care of closing the handles for you.


Sorry I can't resist the code golf here.

Given the file foo.txt that looks like this:

3588888932
4783748387
3434934343
4344232322
4343343439
1111132333

you can read this file and output to standard output all lines that contain the digit 9 with the following commandline incantation:

$ ruby -e 'ARGF.each {|line| puts line if line =~ /9/}' < foo.txt

This outputs

3588888932
3434934343
4343343439

Of course if you need to write to another file, you can say

$ ruby -e 'ARGF.each {|line| puts line if line =~ /9/}' < foo.txt > bar.txt

Generally, filtering of lines from a file is something that is best done via standard input (here I used ARGF), but it is of course also possible to use Ruby's file methods in case this task needs to be performed as part of a larger Ruby application.

The common approach here is

File.open("foo.txt", "r") do |f|
    while (line = f.gets)
        puts line if line =~ /9/
    end
end

this writes to standard output, so to write to bar.txt you can redirect. A nice thing about Ruby here is that the file, since it is a block parameter, is automatically closed when the block exits.

You can also write to a file by opening it within a block. To read from foo.txt and write to bar.txt, see Paul's answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消