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.

0

1 Answer 1

1

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.

1
  • Thanks! never knew this Mar 17, 2022 at 7:07

Not the answer you're looking for? Browse other questions tagged .