how to delete a line of a text file effectively and easily

U

uncutstone

I want to find a easy way to delete a line of a text file . something
like
File.foreach(filename){ |line|
# remove this line if match some condition
# do other thing
}
but since file is not randomly accessible, it seems no easy way to do
this.

somebody has some advice. Thanks in advance.
 
R

Robert Klemme

uncutstone said:
I want to find a easy way to delete a line of a text file . something
like
File.foreach(filename){ |line|
# remove this line if match some condition
# do other thing
}
but since file is not randomly accessible, it seems no easy way to do
this.

somebody has some advice. Thanks in advance.

11:06:09 [~]: cat x
aaa
bbb
ccc
11:06:10 [~]: ruby -ni.bak -e 'puts $_ unless /b+/' x
11:06:24 [~]: cat x
aaa
ccc

If you want this to be done as part of a ruby script, you might want to
open the file in mode "aw" and then copy data inside the file. If it's
small you can also suck the whole file in in one go and write it again.

11:08:45 [~]: cat x
aaa
bbb
ccc
11:08:49 [~]: ruby -e 'content=File.readlines("x").delete_if {|l| /b+/
=~ l}; File.open("x", "w"){|io| io.puts content}'
11:10:25 [~]: cat x
aaa
ccc

Kind regards

robert
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top