Search code examples
perlbashtext

Simple search and replace without regex


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?


Solution

  • 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.