File

I’m trying to figure out how to use File.

I want to read each line, process it, print that to another file, and then
rename the output file. This is how I’d do it in Perl:

open ORIG, “<$filename”;
open TEMP, “>.$$.tmp”;

while () {
s/

//g;
s/</pre>/</code>/g;
print TEMP
}
close ORIG;
close TEMP;

rename “.$$.tmp”, “$filename”;

I can do the REGEX part:

line.gsub!(/

/, ‘’)
line.gsub!(/</pre>/, ‘
’)

But I need help with File.

Thanks,
Daniel.

I want to read each line, process it, print that to another file, and then
rename the output file.

Something like this will do…

lines = File.readlines(‘in.txt’)

File.open(‘out.txt’, ‘w+’) do |fout|
lines.each do |ln|
ln.gsub!(…)
fout.puts ln
end
end

File.rename(‘out.txt’, ‘out.txt’)

I’m trying to figure out how to use File.

I want to read each line, process it, print that to another file, and then
rename the output file. This is how I’d do it in Perl:

[…]

For any question that begins like that, the answer is “Read ‘The Ruby Way’”.
You’ll be glad you did.

Cheers,
Gavin

···

From: “Daniel Carrera” dcarrera@math.umd.edu

Hi,

···

At Sat, 7 Dec 2002 04:52:16 +0900, Daniel Carrera wrote:

I want to read each line, process it, print that to another file, and then
rename the output file. This is how I’d do it in Perl:

open ORIG, “<$filename”;
open TEMP, “>.$$.tmp”;

while () {
s/

//g;
s/</pre>/</code>/g;
print TEMP
}
close ORIG;
close TEMP;

rename “.$$.tmp”, “$filename”;

$ ruby -pi -e “gsub!(%r[<(/?)pre>], ‘<\1code>’)” filename


Nobu Nakada

Thanks for the help.

File.rename is behaving strangely. The file name ended up have an extra
non-printing character at the end. Instead of naming the file “filename”
it names it “filename^J”.

I don’t know what character “^J” is.

I’m on a SPARC computer (in case that matters).

I got the probram working by just doing mv old.txt #{filename}, but I
thought I’d mention this apparent bug.

Daniel.

···

I want to read each line, process it, print that to another file, and then
rename the output file.

Something like this will do…

lines = File.readlines(‘in.txt’)

File.open(‘out.txt’, ‘w+’) do |fout|
lines.each do |ln|
ln.gsub!(…)
fout.puts ln
end
end

File.rename(‘out.txt’, ‘out.txt’)

Thanks for the help.

File.rename is behaving strangely. The file name ended up have an extra
non-printing character at the end. Instead of naming the file “filename”
it names it “filename^J”.

I don’t know what character “^J” is.

J is the tenth letter of the English alphabet, so ^J is ASCII character #10,
which Ruby tells me (10.chr) is “\n”. 13.chr is “\r”.

Maybe a chomp! is in order.

Gavin

···

From: “Daniel Carrera” dcarrera@math.umd.edu

J is the tenth letter of the English alphabet, so ^J is ASCII character #10,
which Ruby tells me (10.chr) is “\n”. 13.chr is “\r”.

Maybe a chomp! is in order.

Gavin

Thanks. That explains it all. Yes, I did need a chomp!.

Daniel.