ruby - 在 Ruby 中使用 '+' 文件 IO 模式替换文件中的一行

标签 ruby file file-io

这里是 Ruby 初学者!

我知道 Ruby 的 File.open 方法具有某些模式,例如 r,w,a,r+,w+,a+ 和互补的 b。我完全理解 r、w 和 a 模式的使用。但我似乎无法理解如何使用带有“+”符号的那些。任何人都可以为我提供一些链接,其中有示例以及使用它的解释吗?

它可以用来读取一行并用等量的内容就地编辑/替换它吗?如果是,那又如何?

示例数据文件:a.txt

aaa
bbb
ccc
ddd

演示.rb

file = File.open "a.txt","r+"
file.each do |line|
  line = line.chomp
  if(line=="bbb")then
  file.puts "big"
  end
end
file.close

我正在尝试用“big”替换“bbb”,但我得到了这个:- 在 Notepad++ 中

aaa
bbb
big

ddd

在记事本中

aaa
bbb
bigddd

最佳答案

这个文档是从另一个答案里拿来的,所以不是我的,解决方案是我的

r  Read-only mode. The file pointer is placed at the beginning of the file. This is the default mode. 
r+ Read-write mode. The file pointer will be at the beginning of the file. 
w  Write-only mode. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. 
w+ Read-write mode. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a  Write-only mode. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. 
a+ Read and write mode. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

编辑:这里是你的样本的解决方案,大部分时间整个字符串被 gsubbed 并写回文件但是'infile'替换而不重写整个文件也是可能的 您应该谨慎替换为相同长度的字符串。

File.open('a.txt', 'r+') do |file|
  file.each_line do |line|
    if (line=~/bbb/)
      file.seek(-line.length-3, IO::SEEK_CUR)
      file.write 'big'
    end
  end
end 

=>
aaa
big
ccc
ddd

这是一种更传统的方式,尽管比大多数其他解决方案更简洁

File.open(filename = "a.txt", "r+") { |file| file << File.read(filename).gsub(/bbb/,"big") } 

EDIT2:我现在意识到这还可以更短

File.write(f = "a.txt", File.read(f).gsub(/bbb/,"big"))

关于ruby - 在 Ruby 中使用 '+' 文件 IO 模式替换文件中的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10171714/

相关文章:

java - 在 Java 中创建 UTF-8 文件

ruby - 从模块内部调用 sinatra halt?

ruby-on-rails - Rails 服务器不通过命令 "Rails s"启动

C++ popen() 的输出到一个字符串

c# - 为什么递归算法会添加重复文件?

Java FileInputStream ObjectInputStream 到达文件 EOF 的结尾

php - 跟踪点 : insert or update?

html - 在 (i18n) yml 中插入 HTML 特殊字符

algorithm - 给定文件名列表,返回具有相同内容的文件列表列表 - 面试题

matlab - 在 MATLAB 中从 CSV 文件中读取日期和时间