开发者

how to modify a text file in ruby

I have a file named ama.txt and the content of the file is like this:

name      age   hobby       sex

amit      45    music       male

sumit开发者_StackOverflow中文版     35    cricket     female

Now I can open the file like this:

File.open("ama.txt").each do

end

How can I modify the hobby column of the file?


The general pattern for something like this is roughly as follows:

  1. Open the original file for reading and a new file for writing. Read the original line by line.
  2. Skip any lines that aren't relevant (you want to skip your header line and the blanks, for example)
  3. Deal with the individual lines however you need. Here you probably want something like cols = line.split(/\s+/) and then you want to edit cols[2], though I don't know if the changes fit a pattern or what.
  4. Once you have the edits made, print the edited line out to the new file.
  5. Once you're done with reading the original and writing the changed lines to the new file, close both files.
  6. Change the original's name to something like 'original_name' + '.bak' and the new file's name to 'original_name'.
  7. Done.

Ruby, like most scripting languages, has a lot of built-in ways to make some of these steps go quicker, but that's the basic pattern. Dmitry is potentially right that a CSV reader would help you here, but I can't see how well-formatted (or not) your data is, so I'm not even going to get into that.

Finally, and not to be rude, but it doesn't seem that you know Ruby especially well. Why is Ruby a requirement? Do you know another scripting language? How well do you know Ruby? In general, people here will help you with things, but not simply write code for you.

To answer Amit's question about step 4: If you have a new file open for writing, you will have a filehandle - a variable in your program pointing to the open file. You can write to that file by using the filehandle as a receiver for puts. This looks weird at first, since puts looks like a function normally, but it is a method call in Ruby. Try this in irb or a short Ruby script:

fh = File.open('test.txt', 'w')
fh.puts "hello, world"
fh.close

Another short example:

#!/usr/bin/env ruby
out_file = File.open('output.txt', 'w')

File.open('input.txt', 'r').each do |line|
  out_file.print line.sub('foo', 'bar')
end

out_file.close
# no need to close the input file since the block version closes it for us
# automagically

# Maybe better to put the whole thing in a double block, though you may
# find this harder to follow at first
File.open('output.txt', 'w') do |out_file|
  File.open('input.txt', 'r').each do |line|
    out_file.print line.sub('foo', 'bar')
  end
end


File.readlines("ama.txt").each do |line|
  row = line.strip.split('\t') # use your delimiter symbol
  row[2] = ... # hobby column
end

Or just use fastercsv gem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜