Ruby blank line in file won't remove - ruby

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")}}

Related

How to append a text to file succinctly

Instead of writing
File.open("foo.txt", "w"){|f| f.write("foo")}
We can write it
File.write("foo.txt", "foo")
Is there simpler way to write this one?
File.open("foo.txt", "a"){|f| f.write("foo")}
This has been answered in great depth already:
can you create / write / append a string to a file in a single line in Ruby
File.write('some-file.txt', 'here is some text', File.size('some-file.txt'), mode: 'a')
f = File.open('foo.txt', 'a')
f.write('foo')
f.close
Yes. It's poorly documented, but you can use:
File.write('foo.txt', 'some text', mode: 'a+')
You can use << instead of .write:
File.open("foo.txt", "a") { |f| f << "foo" }
Although this was answered with multiple options, I have always felt that if Ruby has File.write path, content, it should also have File.append path, content, especially since the existing append syntax is not very pleasant.
So, whenever I need to append, I usually add this extension:
class File
class << self
def append(path, content)
File.open(path, "a") { |f| f << content }
end
end
end
# Now it feels intuitive:
File.write "note.txt", "hello\n"
File.append "note.txt", "world\n"

Adding specific lines to a file with 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

Ruby read/write to file in 1 line of code

I am kind of a newbie to Ruby, I am working out some katas and I stuck on this silly problem. I need to copy the content of 1 file to a new file in 1 line of code
First try:
File.open(out, 'w').write(File.open(in).read)
Nice, but it's wrong I need to close the files:
File.open(out, 'w') { |outf| outf.write(File.open(in).read) }
And then of course close the read:
File.open(out, 'w') { |outf| File.open(in) { |inf| outf.write(outf.read)) } }
This is what I come up with, but it does not look like 1 line of code to me :(
Ideas?
Regards,
Ruby 1.9.3 and later has a
File.write(name, string, [offset], open_args)
command that allows you to write a file directly. name is the name of the file, string is what you want to write, and the other arguments are above my head.
Some links for it: https://github.com/ruby/ruby/blob/ruby_1_9_3/NEWS , http://bugs.ruby-lang.org/issues/1081 (scroll to the bottom).
There are many ways. You could simply invoke the command line for example:
`cp path1 path2`
But I guess you're looking for something like:
File.open('foo.txt', 'w') { |f| f.write(File.read('bar.txt')) }
You can do the following:
File.open(out_file, "w") {|f| f.write IO.read(in_file)}
You can try:
IO.binwrite('to-filename', IO.binread('from-filename'))
Check the ruby docs:
IO::binwrite & IO::binread

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.

How to prevent quote signs in File.readlines

For example I have file file_name with such content:
Just some text,
nothing more
Then I run kind of this code:
lines = File.open(file_name, "r").readlines
# do something do with lines
File.open(file_name, "w").write(lines)
I'll get this text
"Just some text,"
"nothing more"
How to prevent " sign here? I want text without quotes. Thanks
If you are using ruby 1.9.2, Array#to_s works like Array#inspect. Try this instead (some style tweaks thrown in):
lines = File.readlines(file_name)
File.open(file_name, 'w') { |f| f.write(lines.join) }
If you are only concerned with the quotes enclosing each line
okay, let's try that again
lines.gsub(/^"|"$/, '')
should work

Resources