From: dblack@... Date: 2007-01-03T19:50:27+09:00 Subject: Re: Delete line from file Hi -- On Wed, 3 Jan 2007, Robert Klemme wrote: > On 03.01.2007 00:11, Jules wrote: >> Given a line number, what is the best way to delete this line from a >> file? > > $ cat x > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > > $ sed -ni -e '5 b;p' x > > robert@fussel /cygdrive > $ cat x > 1 > 2 > 3 > 4 > 6 > 7 > 8 > 9 > 10 > > Or did you mean with Ruby? > > $ ruby -n -i.bak -e 'puts $_ unless $. == 5' x > > $ cat x > 1 > 2 > 3 > 4 > 6 > 7 > 8 > 9 > 10 > >> And given an array of line numbers, what is the best way to delete >> these lines from a file? > > $ ruby -n -i.bak -e 'puts $_ unless [1,3,4].include? $.' x > > robert@fussel /cygdrive/c/Temp > $ cat x > 2 > 5 > 6 > 7 > 8 > 9 > 10 > > $ diff -u x.bak x > --- x.bak 2007-01-03 11:03:20.281250000 +0100 > +++ x 2007-01-03 11:03:46.437500000 +0100 > @@ -1,7 +1,4 @@ > -1 > 2 > -3 > -4 > 5 > 6 > 7 > > Inside a script? > > robert@fussel /cygdrive/c/Temp > $ ./del.rb x > > robert@fussel /cygdrive/c/Temp > $ diff -u x.bak x > --- x.bak 2007-01-03 11:09:29.437500000 +0100 > +++ x 2007-01-03 11:09:31.468750000 +0100 > @@ -2,7 +2,6 @@ > 2 > 3 > 4 > -5 > 6 > 7 > 8 > > robert@fussel /cygdrive/c/Temp > $ cat del.rb > #!ruby > > f = ARGV.shift or raise "Need file name" > fb = f + ".bak" > > File.rename(f, fb) > > File.open(f, "w") do |out| > File.foreach(fb) {|line| out.puts line unless $. == 5} > end > > > Plenty to choose from... :-) For the script version you can also do: #!/usr/local/bin/ruby -ni.bak puts $_ unless $. == 5 (or some variant thereof). David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)