Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace line in text file with a new line

Tags:

file

ruby

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?

like image 812
JasonBorne Avatar asked Sep 07 '25 04:09

JasonBorne


1 Answers

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
like image 73
user3097405 Avatar answered Sep 10 '25 00:09

user3097405