Adding specific lines to a file with Ruby - ruby

Im trying to edit a file with a ruby scriopt to add a html tag eg at the beginning of the file and line breaks eg. at the end of each line.
Cannot find a clear example to do this.
Any help will be much appreciated.
Thanks

Here is example code that does what you need(you need to call the modify_file function):
def add_tag(tag, str)
return "<#{tag}>\n#{str}\n</#{tag}>"
end
def modify_file(filename)
content = ""
File.open(filename){|file| content = file.read}
content.gsub(/\n/, "</br>\n")
content = add_tag("html", content)
File.open(filename, "w") {|file| file.write(content)}
end

Related

Ruby blank line in file won't remove

I must've browsed every solution on StackOverflow, nothing seems to be removing the blank line's from text file which looks like this:
google
yahoo
facebook
reddit
Amongst other sources, I've tried:
File.foreach("file.txt") { |line|
line.gsub(/^$\n/, '')
}
and
replace = text.gsub /^$\n/, ''
File.open("file.txt", "w") { |file| file.puts replace }
However, these aren't working. I'm tearing my hair out, it seems that there is no native Nokogiri method, and regular expressions aren't working either.
How about you check if it is empty instead?
out = File.new("out.txt", "w")
File.foreach("file.txt") { |line|
out.puts line unless line.chomp.empty?
}
I use below one liner to delete all blank lines from a file
file = "/tmp/hello.log"
File.write(file, File.read(file).gsub(/\n+/,"\n"))
Change the gsub a little bit and it will work
File.foreach("file.txt"){|line|
line.gsub("\n", '')
}
source_file = '/hello.txt'
new_file = File.new('/hello_new.txt')
File::open(new_file,'w') do |file|
File::open(source_file,'r').each(sep="\n") do |line|
file << line unless line.gsub("\n",'').length == 0
end
end
String#squeeze is nice for this. Here it reduces series of line-ends to a single line-end.
open("out.txt", "w") {|out| open("test.txt") {|in| out << in.read.squeeze("\n")}}

Problems saving a class method into txt

I am new to ruby and make a lot of mistakes, so I hope people who are experienced in ruby can share a bit of knowledge.
I can't figure out how I can make ruby save the text into a txt file that a method all writes.
class generator
def all
puts "i want to save this text into a txt file"
end
end
new_gen = generator.new
new_gen.all
my_file = File.new("Story.txt", "a+")
my_file.puts("all")
my_file.puts("\n")
my_file.close
I tried everything, but the txt file either has the "all" in it or it's completely blank. Any ideas? I also tried my_file.puts(all) and my_file.puts(new_gen.all).
If you want Generator to do the writing you could pass it an IO object.
class Generator
def initialize(io)
#io = io
end
def all
#io.puts "i want to save this text into a txt file"
end
end
# write to STDOUT
gen = Generator.new(STDOUT)
gen.all
# write to file
File.open("Story.txt", "a+") do |file|
gen = Generator.new(file)
gen.all
end
You method should simply return a string. Puts displays the string, does not return it. So change the class to:
class generator
def all
"i want to save this text into a txt file" # optionally add a return
end
end
new_gen = generator.new
new_gen.all
Then use the last version you tried: my_file.puts(new_gen.all)
Try this:
class Generator
def all
"i want to save this text into a txt file"
end
end
gen = Generator.new
f = File.new("Story.txt", "a+")
f.puts gen.all
f.close

Script that saves a series of pages then tries to combine them but only combines one?

Here's my code..
require "open-uri"
base_url = "http://en.wikipedia.org/wiki"
(1..5).each do |x|
# sets up the url
full_url = base_url + "/" + x.to_s
# reads the url
read_page = open(full_url).read
# saves the contents to a file and closes it
local_file = "my_copy_of-" + x.to_s + ".html"
file = open(local_file,"w")
file.write(read_page)
file.close
# open a file to store all entrys in
combined_numbers = open("numbers.html", "w")
entrys = open(local_file, "r")
combined_numbers.write(entrys.read)
entrys.close
combined_numbers.close
end
As you can see. It basically scrapes the contents of the wikipedia articles 1 through 5 and then attempts to combine them nto a single file called numbers.html.
It does the first bit right. But when it gets to the second. It only seem's to write in the contents of the fifth article in the loop.
I can't see where im going wrong though. Any help?
You chose the wrong mode when opening your summary file. "w" overwrites existing files while "a" appends to existing files.
So use this to get your code working:
combined_numbers = open("numbers.html", "a")
Otherwise with each pass of the loop the file contents of numbers.html are overwritten with the current article.
Besides I think you should use the contents in read_page to write to numbers.html instead of reading them back in from your freshly written file:
require "open-uri"
(1..5).each do |x|
# set up and read url
url = "http://en.wikipedia.org/wiki/#{x.to_s}"
article = open(url).read
# saves current article to a file
# (only possible with 1.9.x use open too if on 1.8.x)
IO.write("my_copy_of-#{x.to_s}.html", article)
# add current article to summary file
open("numbers.html", "a") do |f|
f.write(article)
end
end

How can I copy the contents of one file to another using Ruby's file methods?

I want to copy the contents of one file to another using Ruby's file methods.
How can I do it using a simple Ruby program using file methods?
There is a very handy method for this - the IO#copy_stream method - see the output of ri copy_stream
Example usage:
File.open('src.txt') do |f|
f.puts 'Some text'
end
IO.copy_stream('src.txt', 'dest.txt')
For those that are interested, here's a variation of the IO#copy_stream, File#open + block answer(s) (written against ruby 2.2.x, 3 years too late).
copy = Tempfile.new
File.open(file, 'rb') do |input_stream|
File.open(copy, 'wb') do |output_stream|
IO.copy_stream(input_stream, output_stream)
end
end
As a precaution I would recommend using buffer unless you can guarantee whole file always fits into memory:
File.open("source", "rb") do |input|
File.open("target", "wb") do |output|
while buff = input.read(4096)
output.write(buff)
end
end
end
Here my implementation
class File
def self.copy(source, target)
File.open(source, 'rb') do |infile|
File.open(target, 'wb') do |outfile2|
while buffer = infile.read(4096)
outfile2 << buffer
end
end
end
end
end
Usage:
File.copy sourcepath, targetpath
Here is a simple way of doing that using ruby file operation methods :
source_file, destination_file = ARGV
script = $0
input = File.open(source_file)
data_to_copy = input.read() # gather the data using read() method
puts "The source file is #{data_to_copy.length} bytes long"
output = File.open(destination_file, 'w')
output.write(data_to_copy) # write up the data using write() method
puts "File has been copied"
output.close()
input.close()
You can also use File.exists? to check if the file exists or not. This would return a boolean true if it does!!
Here's a fast and concise way to do it.
# Open first file, read it, store it, then close it
input = File.open(ARGV[0]) {|f| f.read() }
# Open second file, write to it, then close it
output = File.open(ARGV[1], 'w') {|f| f.write(input) }
An example for running this would be.
$ ruby this_script.rb from_file.txt to_file.txt
This runs this_script.rb and takes in two arguments through the command-line. The first one in our case is from_file.txt (text being copied from) and the second argument second_file.txt (text being copied to).
You can also use File.binread and File.binwrite if you wish to hold onto the file contents for a bit. (Other answers use an instant copy_stream instead.)
If the contents are other than plain text files, such as images, using basic File.read and File.write won't work.
temp_image = Tempfile.new('image.jpg')
actual_img = IO.binread('image.jpg')
IO.binwrite(temp_image, actual_img)
Source: binread,
binwrite.

Ruby: How to replace text in a file?

The following code is a line in an xml file:
<appId>455360226</appId>
How can I replace the number between the 2 tags with another number using ruby?
There is no possibility to modify a file content in one step (at least none I know, when the file size would change).
You have to read the file and store the modified text in another file.
replace="100"
infile = "xmlfile_in"
outfile = "xmlfile_out"
File.open(outfile, 'w') do |out|
out << File.open(infile).read.gsub(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
end
Or you read the file content to memory and afterwords you overwrite the file with the modified content:
replace="100"
filename = "xmlfile_in"
outdata = File.read(filename).gsub(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
File.open(filename, 'w') do |out|
out << outdata
end
(Hope it works, the code is not tested)
You can do it in one line like this:
IO.write(filepath, File.open(filepath) {|f| f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)})
IO.write truncates the given file by default, so if you read the text first, perform the regex String.gsub and return the resulting string using File.open in block mode, it will replace the file's content in one fell swoop.
I like the way this reads, but it can be written in multiple lines too of course:
IO.write(filepath, File.open(filepath) do |f|
f.read.gsub(//<appId>\d+<\/appId>/, "<appId>42</appId>"/)
end
)
replace="100"
File.open("xmlfile").each do |line|
if line[/<appId>/ ]
line.sub!(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
end
puts line
end
The right way is to use an XML parsing tool, and example of which is XmlSimple.
You did tag your question with regex. If you really must do it with a regex then
s = "Blah blah <appId>455360226</appId> blah"
s.sub(/<appId>\d+<\/appId>/, "<appId>42</appId>")
is an illustration of the kind of thing you can do but shouldn't.

Resources