[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Is there a easy way to find and replay a match

Tor Erik Linnerud

5/28/2008 10:21:00 PM


> If I have file and has a line is "aaa=100", and need to replace it as
> "aaa=4".

> puts File.read('somefile')
foo
aaa=100
bar

> puts File.read('somefile').sub('aaa=100', 'aaa=4')
foo
aaa=4
bar

Tor Erik
--
Posted via http://www.ruby-....

4 Answers

Cheyne Li

5/28/2008 11:18:00 PM

0

I need "aaa=4" in the file instead of just print out

Tor Erik Linnerud wrote:
>
>> If I have file and has a line is "aaa=100", and need to replace it as
>> "aaa=4".
>
>> puts File.read('somefile')
> foo
> aaa=100
> bar
>
>> puts File.read('somefile').sub('aaa=100', 'aaa=4')
> foo
> aaa=4
> bar
>
> Tor Erik

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

David Masover

5/29/2008 12:49:00 AM

0

On Wednesday 28 May 2008 18:18:09 Cheyne Li wrote:
> I need "aaa=4" in the file instead of just print out

No offense, but this was pretty much handed to you. You should be able to get
the rest of the way yourself...

> >> print File.read('somefile').sub('aaa=100', 'aaa=4')

string = File.read('somefile').sub('aaa=100','aaa=4')
open('somefile','w'){|f| f.write string}

By the way: DON'T do it this way in a real program. It's not at all safe.
Learn about temporary files and file IO.

Tor Erik Linnerud

5/29/2008 1:07:00 AM

0

Cheyne Li wrote:
> I need "aaa=4" in the file instead of just print out

File.open('somefile', 'r+') do |file|
content = file.read.sub('aaa=100', 'aaa=4')
file.seek(0)
file.write(content)
}

Read more about File at
http://www.ruby-doc.org/core/classes...

although this documentation isn't the easiest to follow.

Tor Erik
--
Posted via http://www.ruby-....

Cheyne Li

5/29/2008 9:44:00 PM

0

Thanks a lot, it really helped. But I don't know why if i use regular
expression to match the pattern "aaa=.*", it's not working with sub, but
gsub.


Tor Erik Linnerud wrote:
> Cheyne Li wrote:
>> I need "aaa=4" in the file instead of just print out
>
> File.open('somefile', 'r+') do |file|
> content = file.read.sub('aaa=100', 'aaa=4')
> file.seek(0)
> file.write(content)
> }
>
> Read more about File at
> http://www.ruby-doc.org/core/classes...
>
> although this documentation isn't the easiest to follow.
>
> Tor Erik

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