逃避替换字符串从用户的“读” [英] escape replacement string 'read' from user
问题描述
我有一个sed脚本所在的替换字符串来自于用户的输入,例如
I have a sed script where the replacement string comes from user input, e.g.
echo -n "Enter identity? "
read identity
sed -i "s:^export identity=.*:export identity='$identity':g" $CFG_FILE
的问题是,用户可以输入具有特殊意义的sed一个值,例如
The problem is that the user may enter a value that has special meaning to sed, for example:
abc:abc
在此情况下,在sed的语句中使用的结肠字符,所以会导致错误。
In this case, the colon character used in the sed statement, so causes an error.
有没有办法让用户输入任意值,但如果数值有特殊含义的sed那么它就会逃走?
Is there a way to allow the user to enter any value, but if a value has special meaning to sed then it gets escaped?
请注意这个问题是相似,但不同:<一href=\"http://stackoverflow.com/questions/23186445/escape-replacement-string-from-bash-source-file\">escape替换字符串从bash的'源'文件
Note this question is similar to, but different from: escape replacement string from bash 'source' file
推荐答案
由于您使用的是变量替换,你需要逃脱重新presents分隔符的字符。外壳使用参数扩展:
Since you are using the variable in the replacement, you need to escape the character that represents the delimiter. Use shell parameter expansion:
identity="${identity//:/\\:}"
这会的转换的 ABC:ABC
到 ABC \\:ABC
和 ABC:DEF:GHI
到 ABC \\:DEF \\:GHI
此外,要使用:
read -r identity
来代替。这将确保在用户输入的任何反斜杠不要逃避任何字符。
instead. That would ensure that any backslashes in the user input do not escape any characters.
这篇关于逃避替换字符串从用户的“读”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!