Deleting a line in a file

Hi, how do I delete a line in a file and remove the empty space
afterward?

Thanks!

···

--
Posted via http://www.ruby-forum.com/.

There are many ways to solve this.
One I use often (which is not very elegant but rather easy) is to use
File.readlines on your file, find the line in that array to kill it, and
save the array to a file finally again.

BTW what do you mean with "empty space"? I guess it will be easy if you
make a small file as example :slight_smile:

···

--
Posted via http://www.ruby-forum.com/.

grep -v "character string unique to line to be removed" file > tmpfile
mv tmpfile file

···

On Thu, 2008-06-26 at 02:49 +0900, Justin To wrote:

Hi, how do I delete a line in a file and remove the empty space
afterward?

Thanks!

Justin To wrote:
Hi, how do I delete a line in a file and remove the empty space
afterward?

Thanks!

Some additional in-place file editing options on Unix:

/bin/ed -s file.txt <<< $'/b/d\nw' # delete first line containing "b"

/bin/ed -s file.txt <<< $'g/b/d\nw' # delete all lines containing "b"
/usr/bin/sed -i "" -e '/b/d' file.txt

/bin/ed -s file.txt <<< $'2,2d\nw' # delete second line
/usr/bin/sed -i "" -e '2,2d' file.txt

More on the ed text editor here:
http://bash-hackers.org/wiki/doku.php?id=howto:edit-ed

Using Ruby from the command line:

ruby -p -i -e 'm ||= 0; m == 1 ? $_ : $_.sub!(/^.*2.*$/m, "") || $_; m =
1 unless $~.nil?' file.txt
ruby -p -i -e '$_.sub!(/^.*b.*$/m, "")' file.txt
ruby -p -i -e '$_.sub!(/^.*$/m, "") if $. == 2' file.txt

For more information on selective deletion of certain lines see:

Cheers,

j.k.

···

--
Posted via http://www.ruby-forum.com/\.

BTW what do you mean with "empty space"? I guess it will be easy if you
make a small file as example :slight_smile:

File:
a
b
c
d

program: delete(b)

File:
a
  <-- empty space
c
d

should be...

File:
a
c
d

Thanks!

···

--
Posted via http://www.ruby-forum.com/\.

This should get you started. There are probably 1000 ways but well,
someone else can do that :slight_smile:

The test_file had this content:
a
b
c
d

The new_file has
a
b
d

class DeleteLine
  def initialize(read_this_file = 'test_file')
    @file = File.readlines(read_this_file)
    delete_line 3
    save_to
  end
  def delete_line(which_line = 1)
    @file.delete_at(which_line-1) # we may count first line as 1, second
line as 2 etc.. otherwise remove the -1 part
  end
  def save_to(this_file = 'new_file')
    File.open(this_file, 'w+') {|f| f.write @file.join() }
  end
end

DeleteLine.new

···

--
Posted via http://www.ruby-forum.com/.