L
Li Chen
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
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