William James
1/3/2007 9:21:00 PM
dblack@wobblini.net wrote:
> Hi --
>
> On Thu, 4 Jan 2007, William James wrote:
>
> >
> > dblack@wobblini.net wrote:
> >> Hi --
> >>
> >> On Wed, 3 Jan 2007, William James wrote:
> >>
> >>>
> >>> Jules wrote:
> >>>> Hi,
> >>>>
> >>>> Given a line number, what is the best way to delete this line from a
> >>>> file?
> >>>>
> >>>> And given an array of line numbers, what is the best way to delete
> >>>> these lines from a file?
> >>>>
> >>>> Thanks,
> >>>>
> >>>> Jules
> >>>
> >>> lines = IO.readlines('junk1')
> >>> [1,3,5].each{|n| lines.slice!(n) }
> >>
> >> That's going to have a side-effect problem:
> >>
> >> irb(main):004:0> a = %w{ a b c d e f }
> >> => ["a", "b", "c", "d", "e", "f"]
> >> irb(main):005:0> [1,3,5].each {|e| a.slice!(e) }
> >> => [1, 3, 5]
> >> irb(main):006:0> a
> >> => ["a", "c", "d", "f"]
> >
> > True.
> >
> > a = %w(zero one two three four five)
> > [1,3,5].each{|i| a[i]=nil}
> > a.compact!
>
> That's OK if you don't have any nils in the array you want to keep.
> Reversing the index list should be pretty glitch-proof, I think.
ARGV.unshift 'junk2'
$-i = ".bak"
while gets do print unless [1,3].include?($.) end
Since these are lines from a file, there won't be any nils.
Here's a pretty short way to delete lines with backup:
ARGV.unshift 'junk2'
$-i = ".bak"
while gets do print unless [1,3].include?($.) end