From: Robert Klemme Date: 2007-06-14T02:20:06+09:00 Subject: Re: why writing the file is partial On 13.06.2007 18:58, Li Chen wrote: > Hi all, > > Thank you for your valuable inputs for my previous post. > > Right now I encounter another odd situation. I want to search some > strings and replace them all in place. ButI can partially update/replace > part of them. I wonder if any experts there can explain it. > > Li > > And here are my codes: > > my_direrctory="C:\\flow\\test" > > pat=/2\.000000\\\$P1G\\2\.000000/ > sub='1.000000\$P1G\\\1.000000' > > Dir.chdir(my_direrctory) > Dir.foreach(my_direrctory) do |filename| #return a file name > next if filename=~/^\./ # skip . and .. > my_file_path=my_direrctory+"\\"+filename #get absolute file name > File.open( my_file_path,"r+") do |file| #pass a file to the block > file.each_line do |line| > if pat.match(line) > line.gsub!(pat,sub) #replace the line in place > file.print line #write/update the file > end > end > end > end > > #####input file format### > test.001 > xxx\2.000000\$P1G\2.000000\xxx > xxx\2.000000\$P1G\2.000000\xxx > xxx\2.000000\$P1G\2.000000\xxx > xxx\2.000000\$P1G\2.000000\xxx > > > ### the updated file### > test.001 > xxx\2.000000\$P1G\2.000000\xxx > xxx\1.000000\$P1G\1.000000\xxx > xxx\2.000000\$P1G\2.000000\xxx > xxx\1.000000\$P1G\1.000000\xxx > Reading and writing one file at the time is a dangerous thing to do - especially if pattern and replacement can have different lengths. If you want to do it properly, then you need to #seek before you switch from reading to writing and back AFAIK. But I'd use a temporary file, this is much safer. Then you can even do it in a one liner: ruby -i.bak -pe 'gsub /pattern/, "replacement"' your_file1 your_file2 Kind regards robert