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

Remove trailing white-spaces from each line in a file

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

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

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

但这不是我想要的。 我想使用我们在C,C++中常用的方法,而不使用任何临时文件,即通过换行将文件指针移动到行的前面并覆盖它。

我们如何在 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"))

这是一种就地修改文件内容的方法。

# 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]$