Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit each line in a file in Ruby

Tags:

file

io

ruby

line

I'm trying to find a simple way of editing each line in a file, and I'm having some trouble understanding how to use the File class to do so.

The file I want to edit has several hundred lines with comma separated values in each line. I'm only interested in the first value in each line, and I want to delete all values after the first one. I tried to do the following:

File.open('filename.txt', 'r+') do |file|
  file.each_line { |line| line = line.split(",")[0] }
  file.write
  file.close
end

Which doesn't work because File.write method requires the contents to be written as an argument.

Could someone enlighten me as to how I could achieve the desired effect?

like image 917
phor2 Avatar asked Mar 27 '11 22:03

phor2


2 Answers

The one of the better solutions(and safest) is to create a temporary file using TempFile, and move it to the original location(using FileUtils) once you are done:

   require 'fileutils'
   require 'tempfile'

    t_file = Tempfile.new('filename_temp.txt')
    File.open("filename.txt", 'r') do |f|
      f.each_line{|line| t_file.puts line.split(",")[0].to_s }
    end
    t_file.close
    FileUtils.mv(t_file.path, "filename.txt")
like image 162
Mike Lewis Avatar answered Sep 19 '22 14:09

Mike Lewis


Another way to modify the file inplace is to use the -i switch

ruby -F"," -i.bak -ane 'puts $F[0]' file
like image 44
kurumi Avatar answered Sep 19 '22 14:09

kurumi