takuma
takuma

Reputation: 17

How to add new line in a file

I want to add newline character below. But the result is wrong. Teach me what is wrong.

test.txt(before)

------------------
2014-09
2014-10
2014-11
------------------

test.txt(after)

------------------
2014-09
2014-10

2014-11
------------------

I make a ruby script below, but the result is wrong.

f = File.open("test.txt","r+")
f.each{|line|
  if line.include?("2014-10")
    f.puts nil 
  end
}
f.close

the result

------------------
2014-09
2014-10

014-11
------------------

Upvotes: 1

Views: 2050

Answers (2)

Patrick Oscity
Patrick Oscity

Reputation: 54674

Reading and writing a file at the same time can get messy, same thing with other data structures like arrays. You should build a new file as you go along.

Some notes:

  • you should use the block form of File.open because it will stop you from forgetting to call f.close
  • puts nil is the same as puts without arguments
  • single quotes are preferred over double quotes when you don’t need string interpolation
  • you should use do ... end instead of { ... } for multi-line blocks
  • File.open(...).each can be replaced with File.foreach
  • the intermediate result can be stored in a StringIO object which will respond to puts etc.

Example:

require 'stringio'

file = 'test.txt'
output = StringIO.new

File.foreach(file) do |line|
  if line.include? '2014-10'
    output.puts
  else
    output << line
  end
end

output.rewind

File.open(file, 'w') do |f|
  f.write output.read
end

Upvotes: 1

Benji
Benji

Reputation: 611

To solve your problem, the easiest way is to create a new file to output your new text into. To do you'll need to open the input file and the output file and iterate each line of the file check the condition and put desired line into the output file.

Example

require 'fileutils'

File.open("text-output.txt", "w") do |output|
  File.foreach("text.txt") do |line|
    if line.include?("2014-10")
      output.puts line + "\n"
    else
      output.puts line
    end
  end
end

FileUtils.mv("text-output.txt", "text.txt")

Easy way

File.write(f = "text.txt", File.read(f).gsub(/2014-10/,"2014-10\n"))

Upvotes: 2

Related Questions