逃离字符串一个sed替换模式 [英] Escape a string for a sed replace pattern
问题描述
在我的bash脚本我有一个外部的字符串,我应在sed模式中使用(从用户收到)。
In my bash script I have an external (received from user) string, which I should use in sed pattern.
REPLACE="<funny characters here>"
sed "s/KEYWORD/$REPLACE/g"
我怎样才能逃避 $ REPLACE
字符串,所以它会通过 SED
被安全地接受为一个文本替换?
How can I escape the $REPLACE
string so it would be safely accepted by sed
as a literal replacement?
注意:的关键字
是一个愚蠢的字符串没有匹配等,这是不是由用户提供的
NOTE: The KEYWORD
is a dumb substring with no matches etc. It is not supplied by user.
推荐答案
警告:这确实的不的考虑换行。为了更深入的回答,请参阅这个所谓的问题,而不是。 (感谢,埃德·莫顿和放大器;尼克拉斯·彼得)
Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter)
需要注意的是逃避一切是一个坏主意。桑达需要的字符转义为获得的其特殊的意义。例如,如果你逃跑的替换字符串一个数字,它会变成到一个反向引用。
Note that escaping everything is a bad idea. Sed needs many characters to be escaped to get their special meaning. For example, if you escape a digit in the replacement string, it will turn in to a backreference.
作为本空白说,目前只有三个需要在替换字符串转义字符(转义自己,向前for语句和与放大器的结束斜线;对于全部替换):
As Ben Blank said, there are only three characters that need to be escaped in the replacement string (escapes themselves, forward slash for end of statement and & for replace all):
sed -e 's/[\/&]/\\&/g'
如果你需要逃避关键字
字符串,以下是你需要的:
If you ever need to escape the KEYWORD
string, the following is the one you need:
sed -e 's/[]\/$*.^|[]/\\&/g'
的附录:的记住,如果你使用的不是 /
作为分隔符,你需要替换前pressions斜线以外的字符上述王氏人物所使用。见解释PeterJCLaw的评论。
Addendum: Remember, if you use a character other than /
as delimiter, you need replace the slash in the expressions above wih the character you are using. See PeterJCLaw's comment for explanation.
的修正1 KEYWORD变种:的增加了两个字符Peter.O提到的,和'('和')
Fix 1 for KEYWORD variant: Added the two characters Peter.O mentioned, and '(' and ')'.
的修正2 KEYWORD变种:的删除'('和')'了。不知道什么时候我加入他们我在想什么。谢谢,杰西。
Fix 2 for KEYWORD variant: Removed '(' and ')' again. Don't know what I was thinking when I added them. Thanks, Jesse.
这篇关于逃离字符串一个sed替换模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!