escape replacement string 'read' from user

2019-09-07 00:20发布

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

The problem is that the user may enter a value that has special meaning to sed, for example:

abc:abc

In this case, the colon character used in the sed statement, so causes an error.

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?


Note this question is similar to, but different from: https://stackoverflow.com/questions/23186445/escape-replacement-string-from-bash-source-file

标签: regex bash sed
1条回答
在下西门庆
2楼-- · 2019-09-07 00:53

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//:/\\:}"

This would transform abc:abc into abc\:abc and abc:def:ghi into abc\:def\:ghi.

Moreover, you want to use:

read -r identity

instead. That would ensure that any backslashes in the user input do not escape any characters.

查看更多
登录 后发表回答