Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple search and replace without regex

Tags:

text

bash

perl

I've got a file with various wildcards in it that I want to be able to substitute from a (Bash) shell script. I've got the following which works great until one of the variables contains characters that are special to regexes:

VERSION="1.0" perl -i -pe "s/VERSION/${VERSION}/g" txtfile.txt    # No problems here  APP_NAME="../../path/to/myapp" perl -i -pe "s/APP_NAME/${APP_NAME}/g" txtfile.txt  # Error! 

So instead I want something that just performs a literal text replacement rather than a regex. Are there any simple one-line invocations with Perl or another tool that will do this?

like image 904
the_mandrill Avatar asked Nov 01 '11 18:11

the_mandrill


1 Answers

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

like image 117
Borodin Avatar answered Sep 25 '22 10:09

Borodin