我想用新行替换文件中的一行,例如:
文件:
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/