Simple search and replace without regex Simple search and replace without regex bash bash

Simple search and replace without regex


The 'proper' way to do this is to escape the contents of the shell variables so that they aren't seen as special regex characters. You can do this in Perl with \Q, as in

s/APP_NAME/\Q${APP_NAME}/g

but when called from a shell script the backslash must be doubled to avoid it being lost, like so

perl -i -pe "s/APP_NAME/\\Q${APP_NAME}/g" txtfile.txt

But I suggest that it would be far easier to write the entire script in Perl


Use the following:

perl -i -pe "s|APP_NAME|\\Q${APP_NAME}|g" txtfile.txt

Since a vertical bar is not a legal character as part of a path, you are good to go.


I don't particularly like this answer because there should be a better way to do a literal replace in Perl. \Q is cryptic. Using quotemeta adds extra lines of code.

But... You can use substr to replace a portion of a string.

#!/usr/bin/perlmy $name = "Jess.*";my $sentence = "Hi, my name is Jess.*, dude.\n";my $new_name = "Prince//";my $name_idx = index $sentence, $name;if ($name_idx >= 0) {    substr($sentence, $name_idx, length($name), $new_name);}print $sentence;

Output:

Hi, my name is Prince//, dude.