How to delete a line in a file if....?

Thanks Daniel. This looks like it would work. But I had in mind to delete a line in an open file, then save the whole file, rather than do conditional saving line-by-line to an out file. Maybe these are really the same thing but just look different.

Any other ideas out there?

Most appreciative.

-ke

···

-----Original Message-----
From: Daniel Bretoi [mailto:lists@debonair.net]
Sent: Sunday, July 14, 2002 3:39 PM
To: ruby-talk@ruby-lang.org
Subject: Re: How to delete a line in a file if…?

Is something like this what you mean? (I didn’t debug this btw)
fh = File.open(“file”,“r”);
out = File.open(“file_result”,“w”);
fh.each { |line|
out.puts line unless line =~ /unwantedstring/
}
fh.close; out.close;

On Mon, Jul 15, 2002 at 07:07:55AM +0900, Kurt Euler wrote:

All-

Please advise as to how I can delete a line in a file in which a given string appears.

I tried using the delete_if method in the following code, but it failed. (I suspect that delete_if might be an array method rather than a file method. In the code below, “content2” is a file, not an array.)

if FileTest.exist?(“input_installs/#{field[5]}” )
install_file = ''
File.open("./input_installs/#{field[5]}") { |f| install_file = f.read }
content2.gsub!(/<install_template.txt>/, install_file)
content2.delete_if { |l| l =~ “uncompress” }
else
(blah blah…)

For the present, I’d prefer to avoid using arrays, so I need a way to search a file and delete any line in which a certain string (eg “uncompress”) occurs.

Thanks!

-Kurt


P.S. Only personal email to this email please.

Tussman’s Law:
Nothing is as inevitable as a mistake whose time has come.

Kurt Euler keuler@portal.com writes:

Thanks Daniel. This looks like it would work. But I had in mind to
delete a line in an open file, then save the whole file, rather than
do conditional saving line-by-line to an out file. Maybe these are
really the same thing but just look different.

Think of a file as simply a stream of characters on disk, with
newline sequences separating the lines.

aaaaabbbbbbbbbbbbccccccddddddddddddd

If there is no higher-level structure, how would you do about deleting
the line containing the b’s? The simplest way is to copy the file,
skipping the line to be deleted. (An alternative on some operating
systems might be to compress the file in place, but that has a
secondary problem: crash in the middle and your file is corrupt).

Some operating systems (such as Multics) had line-oriented files,
which allowed you to delete lines on disk files. Unix and DOS don’t.

Cheers

Dave