> 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-forum.com/.
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.
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/File.html
although this documentation isn't the easiest to follow.
Cheyne Li wrote:
> Hi,there
>
> If I have file and has a line is "aaa=100", and need to replace it as
> "aaa=4".
> Is there a way to do it without iterating each line and find the match,
> then replace it? Thank in advance
ruby -i -pe'gsub(/aaa=100/,"aaa=4")' somefile
Regards,
Park Heesob