How to write some value to a text file in ruby based on position

核能气质少年 提交于 2020-01-04 09:13:14

问题


I need some help is some unique solution. I have a text file in which I have to replace some value based on some position. This is not a big file and will always contain 5 lines with fixed number of length in all the lines at any given time. But I have to specficaly replace soem text in some position only. Further, i can also put in some text in required position and replace that text with required value every time. I am not sure how to implement this solution. I have given the example below.

Line 1 - 00000 This Is Me 12345 trying
Line 2 - 23456 This is line 2 987654
Line 3 - This is 345678 line 3 67890

Consider the above is the file I have to use to replace some values. Like in line 1, I have to replace '00000' with '11111' and in line 2, I have to replace 'This' with 'Line' or any require four digit text. The position will always remain the same in text file.

I have a solution which works but this is for reading the file based on position and not for writing. Can someone please give a solution similarly for wrtiting aswell based on position

Solution for reading the file based on position :

def read_var file, line_nr, vbegin, vend 
    IO.readlines(file)[line_nr][vbegin..vend] 
end 

puts read_var("read_var_from_file.txt", 0, 1, 3) #line 0, beginning at 1, ending at 3 
#=>308 

puts read_var("read_var_from_file.txt", 1, 3, 6) 

#=>8522 

I have also tried this solution for writing. This works but I need it to work based on position or based on text present in the specific line.

Explored solution to wirte to file :

open(Dir.pwd + '/Files/Try.txt', 'w') { |f|
  f << "Four score\n"
  f << "and seven\n"
  f << "years ago\n"
}

回答1:


I made you a working sample anagraj.

in_file = "in.txt"
out_file = "out.txt"

=begin
=>contents of file in.txt
00000 This Is Me 12345 trying 
23456 This is line 2 987654 
This is 345678 line 3 67890 
=end

def replace_in_file in_file, out_file, shreds
  File.open(out_file,"wb") do |file|
    File.read(in_file).each_line.with_index do |line, index| 
      shreds.each do |shred|
        if shred[:index]==index
          line[shred[:begin]..shred[:end]]=shred[:replace]
        end
      end
      file << line
    end
  end
end    


shreds = [
    {index:0, begin:0, end:4, replace:"11111"},
    {index:1, begin:6, end:9, replace:"Line"}
]

replace_in_file in_file, out_file, shreds

=begin
=>contents of file out.txt
11111 This Is Me 12345 trying 
23456 Line is line 2 987654 
This is 345678 line 3 67890 
=end


来源:https://stackoverflow.com/questions/12382956/how-to-write-some-value-to-a-text-file-in-ruby-based-on-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!