Deleting a line in a file

J

Justin To

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

Thanks!
 
M

Marc Heiler

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 :)
 
J

Justin To

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

File:
a
b
c
d

program: delete(b)

File:
a
<-- empty space
c
d

should be...

File:
a
c
d

Thanks!
 
M

Marc Heiler

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

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
 
R

Reid Thompson

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

Thanks!

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

Jimmy Kofler

Justin said:
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:
http://www.fepus.net/ruby1line.txt


Cheers,

j.k.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,665
Latest member
salkete

Latest Threads

Top