从文件中的每一行删除尾随的白空间



我正在使用ruby,我想在文件中每行末尾删除尾随的白空间。

做到这一点的一种方法,逐行迭代并将其保存在另一个文件中,然后用旧文件替换新文件。

  temp_file = Tempfile.new("temp")
  f.each_line do |line|
    new_line = line.rstrip
    temp_file.puts  new_line
  end

,但这不是我想要的。我想使用我们通常在C,C 中使用的方法,而无需使用任何临时文件,将文件指针移动到新线路的前面并覆盖它。

我们如何在Ruby ??

中执行此操作

这是修改已定位文件内容的一种方法。

# a.rb
File.open "#{__dir__}/out1.txt", 'r+' do |io|
  r_pos = w_pos = 0
  while (io.seek(r_pos, IO::SEEK_SET); io.gets)
    r_pos = io.tell
    io.seek(w_pos, IO::SEEK_SET)
    # line read in by IO#gets will be returned and also assigned to $_.
    io.puts $_.rstrip
    w_pos = io.tell
  end
  io.truncate(w_pos)
end

这是文件的输出。

[arup@Ruby]$ cat out1.txt
 foo 
    biz
 bar
[arup@Ruby]$ ruby a.rb
[arup@Ruby]$ cat out1.txt
 foo
    biz
 bar
[arup@Ruby]$

您可以使用以下内容:

file_name = 'testFile.txt'
input_content = File.open(file_name).read
output_content = []
file.each_line do |line|
  line.gsub!("n",'').strip!
  output_content << line
end
File.open(file_name,'w').write(output_content.join("n"))

最新更新