search and replace text in files

P

phil.swenson

I need to search a file for text "InstallDir=" + newline character and
replace it with something like: InstallDir=C\:\\mws71 + newline

My own experimentation with this had problems with writing the back-
slashes to the file (it's a requirement of the format to have the back-
slashes as in my example). The string had the back-slashes in it but
they didn't get persisted to the file correctly.

Are there any libraries that perform a search and replace?

thanks
phil
 
S

Suraj Kurapati

Phil said:
I need to search a file for text "InstallDir=" + newline character and
replace it with something like: InstallDir=C\:\\mws71 + newline
=> "InstallDir=C\\:\\mws71\n"
My own experimentation with this had problems with writing the back-
slashes to the file (it's a requirement of the format to have the back-
slashes as in my example). The string had the back-slashes in it but
they didn't get persisted to the file correctly.

In a single-quoted string, one backslash outputs one backslash.
In a double-quoted string, two backslashes outputs one backslash.
=> "\\ "
=> "\\ "
Are there any libraries that perform a search and replace?

String#gsub
 
B

Brian Candler

=> "InstallDir=C\\:\\mws71\n"


In a single-quoted string, one backslash outputs one backslash.

Except where followed by a single quote or another backslash.

irb(main):001:0> '\\'.length
=> 1
irb(main):002:0> '\''.length
=> 1
irb(main):003:0> '\n'.length
=> 2
 
P

phil.swenson

Are there any libraries that perform a search and replace?
String#gsub


I meant on a file... I was looking for something like
File.search_and_replace(file_name, regex_search, replace_string)

But I guess I can simply pull a file into a string and then do a gsub
and write the file out.

Thanks,
phil
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top