From: Jason Roelofs Date: 2007-06-11T22:41:13+09:00 Subject: Re: why gsub! doesn't work in my script ------=_Part_30439_3020880.1181569274793 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Backslash ( \ ) is the escape character. If you want to match \ itself, you need to escape it ( \\ ). So try these regex's: r1_obj=Regexp.escape('1.000000\\$P1G\\1.000000') #pattern r2_obj=Regexp.escape('2.000000\\$P1G\\2.000000') #replacement Jason On 6/11/07, Li Chen wrote: > > Hi all, > > I want to search one pattern in a file line by line and replace it with > new pattern one. But it doesn't work. I cannot change the old pattern > into the new one using gsub! Is there any problem with my script? > > Thanks, > > Li > > > > > ################Ruby script############## > > #create a regular expression and its replacement > > r1_obj=Regexp.escape('1.000000\$P1G\1.000000') #pattern > r2_obj=Regexp.escape('2.000000\$P1G\2.000000') #replacement > > > DATA.each_line do |line| > if line.match(r1_obj) > line.gsub!(r1_obj, r2_obj) # > puts line > end > end > > > > > __END__ > > test1.001 > K:\flow\test\test1.001 > xxx\1.000000\$P1G\1.000000\xxx > yyyy\1.000000\$P1G\1.000000\xxx > test1.002 > K:\flow\test\test1.002 > xxx\1.000000\$P1G\1.000000\xxx > yyyy\1.000000\$P1G\1.000000\xxx > test1.003 > K:\flow\test\test1.003 > xxx\1.000000\$P1G\1.000000\xxx > yyyy\1.000000\$P1G\1.000000\xxx > > ####screen output########### > > xxx\1.000000\$P1G\1.000000\xxx > yyyy\1.000000\$P1G\1.000000\xxx > xxx\1.000000\$P1G\1.000000\xxx > yyyy\1.000000\$P1G\1.000000\xxx > xxx\1.000000\$P1G\1.000000\xxx > yyyy\1.000000\$P1G\1.000000\xxx > > -- > Posted via http://www.ruby-forum.com/. > > ------=_Part_30439_3020880.1181569274793--