我想用新行替换文件中的一行,例如:
文件:
test
test
test
testing
test
Run Code Online (Sandbox Code Playgroud)
来源:
def remove_line(line)
if line == line
#remove line including whitespace
File.open('test.txt', 'a+') { |s| s.puts('removed successfully') }
end
end
Run Code Online (Sandbox Code Playgroud)
因此,预期的输出将是这样的:
remove_line('testing')
test
test
test
removed successfully
test
Run Code Online (Sandbox Code Playgroud)
现在我做了一些研究,只能找到添加一个空行,我想我可以运行它并删除所有空行,然后附加到文件中,但必须有一种更简单的方法来替换行用另一个字符串?
首先,打开文件并保存实际内容。然后,替换字符串并将完整内容写回文件。
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
Run Code Online (Sandbox Code Playgroud)
或者,不进行全局替换:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4074 次 |
| 最近记录: |