# Find and replace

**URL:** <https://www.ruby-forum.com/t/find-and-replace/234762>\
**Category:** Ruby\
**Created:** [March 27, 2015, 8:22pm UTC](https://www.ruby-forum.com/t/find-and-replace/234762 "2015-03-27T20:22:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![addis\_a](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/c4cdca/32.png) [@addis\_a](https://www.ruby-forum.com/u/addis_a)\
**Post date:** [March 27, 2015, 8:22pm UTC](https://www.ruby-forum.com/t/find-and-replace/234762/1 "2015-03-27T20:22:55Z")

</div>

I have a text file that contains file paths as follows:

> **[11961lbl.pdf](https://www.accessdata.fda.gov/drugsatfda_docs/label/1998/11961lbl.pdf)**
>
> 56.49 KB

I want to replace the string “drug” by “med” wherever it occurs.

I used something like the following:

gsub!(/(drug)/,‘medication’) if contents.include? ‘drug’

(/(drug)/ is supposed to be a regular expression, but, I may be writing  
it wrongly.

Do you know what I can do to perform such task?

Thanks.

---

<div class="post-metadata">

**Author:** ![swengineer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/97f17d/32.png) [@swengineer](https://www.ruby-forum.com/u/swengineer)\
**Post date:** [March 29, 2015, 4:11pm UTC](https://www.ruby-forum.com/t/find-and-replace/234762/2 "2015-03-29T16:11:38Z")

</div>

SW Engineer wrote in post #1171014:

> I have a text file that contains file paths as follows:
> 
> [http://www.accessdata.fda.gov/drugsatfda\_docs/label/1998/11961lbl.pdf](http://www.accessdata.fda.gov/drugsatfda_docs/label/1998/11961lbl.pdf)

That is not a file path but a URL.

> I want to replace the string “drug” by “med” wherever it occurs.
> 
> I used something like the following:
> 
> gsub!(/(drug)/,‘medication’) if contents.include? ‘drug’

The check with “if” is superfluous as #gsub will only replace if there  
are matches. An additional check will only make it slower.

> (/(drug)/ is supposed to be a regular expression, but, I may be writing  
> it wrongly.

The expression is OK (apart from brackets which are not needed here). On  
what object are you invoking #gsub!?

> Do you know what I can do to perform such task?

If you have the file contents in a variable called “contents” then you  
can simply do

contents.gsub!(/drugs/, ‘medication’)

A simpler solution would be to use sed on the command line:

sed ‘s#drugs#medication#g’ file

You can even do that in place

sed -i.bak ‘s#drugs#medication#g’ file

Cheers

robert
