问题描述
在我的 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?
注意: KEYWORD
是一个没有匹配等的哑子字符串.它不是由用户提供的.
NOTE: The KEYWORD
is a dumb substring with no matches etc. It is not supplied by user.
推荐答案
警告:这不考虑换行符.有关更深入的答案,请参阅 this SO-question 来可靠地转义正则表达式元字符.(谢谢,Ed Morton 和 Niklas Peter)
Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter)
请注意,逃避一切是一个坏主意.Sed 需要对许多字符进行转义以获得它们的特殊含义.例如,如果您对替换字符串中的数字进行转义,它将变成反向引用.
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.
正如 Ben Blank 所说,替换字符串中只有三个字符需要转义(转义自己,正斜杠代表语句结束,& 代表全部替换):
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):
ESCAPED_REPLACE=$(printf '%s
' "$REPLACE" | sed -e 's/[/&]/\&/g')
# Now you can use ESCAPED_REPLACE in the original sed statement
sed "s/KEYWORD/$ESCAPED_REPLACE/g"
如果您需要对 KEYWORD
字符串进行转义,以下是您需要的:
If you ever need to escape the KEYWORD
string, the following is the one you need:
sed -e 's/[]/$*.^[]/\&/g'
并且可以用于:
KEYWORD="The Keyword You Need";
ESCAPED_KEYWORD=$(printf '%s
' "$KEYWORD" | sed -e 's/[]/$*.^[]/\&/g');
# Now you can use it inside the original sed statement to replace text
sed "s/$ESCAPED_KEYWORD/$ESCAPED_REPLACE/g"
请记住,如果您使用 /
以外的字符作为分隔符,则需要将上述表达式中的斜线替换为您正在使用的字符.有关解释,请参阅 PeterJCLaw 的评论.
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.
已由于之前未考虑到的某些极端情况,上述命令已更改数次.查看编辑历史以了解详细信息.
Edited: Due to some corner cases previously not accounted for, the commands above have changed several times. Check the edit history for details.
这篇关于为 sed 替换模式转义字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!