1

In Unix (running MacOS High Sierra), I've seen a few different search/replace (over several files) methods, e.g.:

perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt

or using sed or grep, etc. The problem is, how do I escape my search strings properly? For example, if I need to replace http://my.site/dir with http://new.my.site/dir, obviously I can't include forward slashes in my search string without escaping.

marked as duplicate by Kusalananda, Jeff Schaller, DopeGhoti, αғsнιη, Rui F Ribeiro May 21 '18 at 21:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

If it is specifically this command, note that with Perl for the s/// operator you can choose other delimiters than / which then makes your life far easier as you do not have to escape anything.

Hence the following will work:

perl -pi -w -e 's!http://my.site/dir!http://new.my.site/dir!g;' *.txt

You can use any other character than ! if you fancy it, as long as it does not appear neither in source nor replacement string. Also since the whole "script" is under ' its content is not parsed by the shell, so you are also safe from shell interpolation of stuff like $ and others.

See https://perldoc.perl.org/perlop.html#Quote-and-Quote-like-Operators for all the details.

Not the answer you're looking for? Browse other questions tagged or ask your own question.