how to modify a text file in ruby -


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

 < Code> Name Age Hobby Sex Amit 45 Music Male Amount 35 Cricket Women  

Now I can open the file like this:

  File.open (" Ama .txt "). Each task ending  

How do I modify the Hobby column of the file?

The general pattern for something like this is as follows:

  1. Open original file for reading and a new file to write.
  2. Skip any line that is not relevant (you want to leave your header line and blank, for example)
  3. Deal with personal lines though you need . Here you probably want something like cols = line.split (/ \ s + /) and then you want to edit cols [2] , though I do not know That
  4. once you make the edits, print the edited line on new file .
  5. Close both files, once you read the original and write the converted lines in the new file.
  6. Rename the original to name the new file for 'original_name' + '.bak' and 'original_name'.
  7. Done.

Ruby, like most scripting languages, there are many built-in methods to sharpen some of these steps, but this is the basic pattern. Dimitri is probable right that a CSV reader will help you, but I can not see how well your data is formatted (or not), so I'm not going into it too.

Finally, it should not be harsh, but it does not seem that you know Ruby very well, why is Ruby a requirement? Do you know other scripting languages? How well do you know Ruby? In general, the people here will help you, but will not write the code just for you.

To answer Amit's question about Step 4: If you have a new file that is open for writing, pointing to an open file, a variable in your program. You can write that file by using the FileHandle as a receiver for puts . It looks awkward already, because puts normally looks like a function, but it is is it is irb or less ruby Try in the script:

  fh = File.open ('test.txt', 'w') fh.puts "hello, world" Fh.close  
< P> Another short example:

  #! / Usr / bin / env ruby ​​out_file = File.open ('output.txt', 'W') File.open ('input.txt', 'r'). Every do Line | | Out_file.print line sub ('foo', 'bar') end-out_file There is no need to turn off the # # input file because the block version closes it for us # automatically # complete the whole thing in a double block, even though you have to follow # in the file first Can achieve this difficult search. Open ('output.txt', 'w') | Out_file | File.open ('input.txt', 'r'). Do each. Line | Out_file.print line.sub ('foo', 'bar') ending  

Comments