2

我需要一些帮助是一些独特的解决方案。我有一个文本文件,我必须根据某个位置替换一些值。这不是一个大文件,在任何给定时间,所有行都将始终包含 5 行,长度固定。但我必须仅在某个位置专门替换某些文本。此外,我还可以在所需位置放置一些文本,并每次都用所需值替换该文本。我不确定如何实施此解决方案。我已经给出了下面的例子。

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

考虑上面是我必须用来替换一些值的文件。与第 1 行一样,我必须将 '00000' 替换为 '11111',在第 2 行中,我必须将 'This' 替换为 'Line' 或任何需要四位数字的文本。该位置在文本文件中将始终保持不变。

我有一个可行的解决方案,但这是基于位置读取文件而不是写入。有人可以根据位置给出类似的解决方案吗

基于位置读取文件的解决方案:

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 

我也尝试过这种写作解决方案。这可行,但我需要它根据位置或特定行中存在的文本来工作。

探索了写入文件的解决方案:

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

1 回答 1

0

我给你做了一个工作样本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
于 2012-09-12T08:53:34.297 回答