I want to replace a line in a file with a new line, example being:
File:
test
test
test
testing
test
Source:
def remove_line(line)
if line == line
#remove line including whitespace
File.open('test.txt', 'a+') { |s| s.puts('removed successfully') }
end
end
So the expected output of this would be something like this:
remove_line('testing')
test
test
test
removed successfully
test
Now I've done some research and have only been able to find adding a blank line, I guess I could run through it and remove all blank lines and just append to the file, but there has to be an easier way to replace a line with another string?
First, open the file and save the actual content. Then, replace the string and write the full content back to file.
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
Or, instead of replacing globally:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With