ruby - 用新行替换文本文件中的行

标签 ruby file

我想用新行替换文件中的一行,例如:

文件:

test
test
test
testing
test

来源:

def remove_line(line)
  if line == line
    #remove line including whitespace
    File.open('test.txt', 'a+') { |s| s.puts('removed successfully') }
  end
end

所以预期的输出应该是这样的:

remove_line('testing')
test
test
test
removed successfully
test

现在我已经做了一些研究并且只能找到添加一个空行,我想我可以运行它并删除所有空行并只附加到文件中,但是必须有一种更简单的方法来用另一个字符串替换一行?

最佳答案

首先,打开文件并保存实际内容。然后,替换字符串并将完整内容写回文件。

def remove_line(string)
  # save the content of the file
  file = File.read('test.txt')
  # replace (globally) the search string with the new string
  new_content = file.gsub(string, 'removed succesfully')
  # open the file again and write the new content to it
  File.open('test.txt', 'w') { |line| line.puts new_content }
end

或者,不是全局替换:

def remove_line(string)
  file = File.read('test.txt')
  new_content = file.split("\n")
  new_content = new_content.map { |word| word == string ? 'removed succesfully' : word }.join("\n")
  File.open('test.txt', 'w') { |line| line.puts new_content }
end

关于ruby - 用新行替换文本文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36669202/

相关文章:

ruby-on-rails - Savon + Rails 2 如何修改XML的请求结构

java - 从Java中的文本文件中读取数据作为数组

c - 当标准输入设置为 C 中的文件时如何从键盘读取

java - 如何在启动时从用户收集系统时间信息

android - 哪个更快? Android 中的 SharedPreference 或文件

python - Python中递归遍历所有目录,直到找到某个文件

Ruby 类实例变量与类变量

ruby - 点运算符与范围解析运算符与 Ruby 中的模块

ruby - 数据/文件更改时重新加载中间人

ruby - 在 ruby​​ 1.8.6 (each_char) 中遍历字符串的每个字符