I have a simple text file with content:
patent-inv
I’m going to replace patent-inv with part1\\part2
I did it in such way:
source_file = IO.read("#{Rails.root}/my_userdata/1.txt")
source_file.gsub!('<<<patent-inv>>>', "part1\\\\part2")
File.open("#{Rails.root}/my_userdata/2.txt", "wb") {|f| f.write source_file }
But in file I got:
part1\part2
I tried several ways, but I got the same result:
source_file.gsub!('<<<patent-inv>>>', "part1\\\\part2") => "part1\part2"
source_file.gsub!('<<<patent-inv>>>', "part1\\\part2") => "part1\part2"
source_file.gsub!('<<<patent-inv>>>', "part1\\part2") => "part1\part2"
Could Anyone help me find out this strange behavior?
The following works for me. Have you tried it in the terminal? It could be unescaped when you output the result.
You can see how the output varies between
putsandpEDIT Here is the output displayed as you want it.
We know that 4 backslashes when changed equals 2 backslashes when unescaped. So 4 backslashes need to be generated AFTER the substitution for it to be displayed correctly.