File edit

I have a 40meg postscript file that I need to change the header on. Is
it possible to change the third line/xxx charactor without loading the
entire file into an array.

fout = File.new(“file2.ps”)
linenum = 1
File.open(“file.ps”) do |f|
f.each_line do |l|
if linenum == 3 then
# change line
end
fout.puts l
linenum += 1
end
end
fout.close

···

-----Original Message-----
From: Nick Massaro [mailto:nmassaro@co.jefferson.co.us]
Sent: Friday, August 16, 2002 11:04 AM
To: ruby-talk ML
Subject: file edit

I have a 40meg postscript file that I need to change the header on. Is
it possible to change the third line/xxx charactor without loading the
entire file into an array.

This should be equivalent, and easier to read.

File.open(“dst.ps”) do |dst|
File.open(“src.ps”) do |src|
for line in src
if src.lineno == 3
# Change line.
end
dst.puts l
end
end
end

Not tested, though.

You still have to read and write every line in the file. The important thing
is that you’re not reading the whole line into the file at once.

The original question probably means “Can I change a file in place?”, so that a
one-line change doesn’t involve processing 40M. For a general one-line change
to a text file, sadly no, unless you have a wierd filesystem. However, binary
files can be changed in place. See the ri help for IO.seek and IO.write. To
go to the third line, fifth character, and replace the next three characters
with “XXX”, you would do something like this:

File.open(“file.ps”, “rw”) do |file|
2.times { file.gets } # Skip first two lines.
file.seek(5, IO::SEEK_CUR) # Skip next 5 chars.
file.write(“XXX”) # Overwrite next three.
end

Again, untested. Potential issues:

  • “rw” falg may be incorrect (“r+”?)
  • may need to seek 4 instead of 5
  • may need to open in binary mode (probably not, though)
  • I may be barking up the wrong tree entirely.

Regards,
Gavin

···

----- Original Message -----
From: “Steve Tuckner” STUCKNER@MULTITECH.COM
To: “ruby-talk ML” ruby-talk@ruby-lang.org
Sent: Saturday, August 17, 2002 2:21 AM
Subject: RE: file edit

fout = File.new(“file2.ps”)
linenum = 1
File.open(“file.ps”) do |f|
f.each_line do |l|
if linenum == 3 then

change line

end
fout.puts l
linenum += 1
end
end
fout.close

-----Original Message-----
From: Nick Massaro [mailto:nmassaro@co.jefferson.co.us]
Sent: Friday, August 16, 2002 11:04 AM
To: ruby-talk ML
Subject: file edit

I have a 40meg postscript file that I need to change the header on. Is
it possible to change the third line/xxx charactor without loading the
entire file into an array.

puts “Whoops”
puts (<<EOF).sub(/into the file/, “into memory”)

···

----- Original Message -----
From: “Gavin Sinclair” gsinclair@soyabean.com.au

You still have to read and write every line in the file. The important thing
is that you’re not reading the whole line into the file at once.

EOF

:Gavin