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?
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")
Another way to modify the file inplace is to use the -i
switch
ruby -F"," -i.bak -ane 'puts $F[0]' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With