无需正则表达式即可轻松搜索和替换 [英] Simple search and replace without regex

查看:62
本文介绍了无需正则表达式即可轻松搜索和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有各种通配符的文件,我希望能够从一个(bash)shell脚本中替换它.在变量之一包含正则表达式专用字符之前,我有以下几种方法可以很好地发挥作用:

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!

因此,我希望只执行文字替换而不是正则表达式的东西.是否可以使用perl或其他工具进行任何简单的单行调用?

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?

推荐答案

有关以下内容:

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.

这篇关于无需正则表达式即可轻松搜索和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆