简体   繁体   English

通过 shell 脚本创建 sed 命令 - 引号和 sed

[英]sed command creation via shell script - quotes and sed

I'm implementing a template renderer in shell script.我在 shell 脚本中实现了一个模板渲染器。 The template variables are represented in a template by @VAR_NAME@ and their values are defined in a separate shell script.模板变量在模板中由@VAR_NAME@ 表示,它们的值在单独的 shell 脚本中定义。

Sample code:示例代码:

# template variables values
CONTACT_EMAIL="myemail"
CONTACT_NAME="myname"
VARS="CONTACT_EMAIL CONTACT_NAME"

TEMPLATE_FILEPATH="mytemplate.txt"

# template renderer
set -x
SEDARGS=
for VAR in $VARS; do
     SEDARGS+=" -e \"s,@$VAR@,${!VAR},\""
done
sed -r $SEDARGS $TEMPLATE_FILEPATH

sed command executed by shell and printed by it because of "set -x":由于“set -x”而由shell执行并由它打印的sed命令:

+ sed -r -e '"s,@CONTACT_EMAIL@,myemail,"' -e '"s,@CONTACT_NAME@,myname,"' mytemplate.txt 

sed output: sed 输出:

sed: -e expression #1, char 1: unknown command: `"'

I know the single quotes around each sed expression are causing this non-intuitive error message, but I do not know why they are added.我知道每个 sed 表达式周围的单引号导致此非直观错误消息,但我不知道为什么添加它们。

What is wrong?怎么了?

You have embedded quotes inside your SEDARGS variable.您在SEDARGS变量中嵌入了引号。 These are NOT removed when the command is executed.执行命令时不会删除这些。 To remove them, you need to call the interpreter again, which you can do using eval .要删除它们,您需要再次调用解释器,您可以使用eval For example:例如:

eval sed -r $SEDARGS $TEMPLATE_FILEPATH

You may need to play around that some more (adding quotes, etc.).您可能需要多玩一些(添加引号等)。

The single quotes aren't part of the actual arguments.单引号不是实际参数的一部分。 They get added by your shell for the output caused by set -x only.它们由您的 shell 添加,用于仅由set -x引起的输出。

Why would the shell do that?为什么壳会这样做? So that you can use that output to re-run exactly what was executed during the script execution.这样您就可以使用该输出准确地重新运行在脚本执行期间执行的内容。 As you correctly noticed, they are needed to protect the " that came from SEDARGS content (ie, the inner ones, in your script escaped as \\" ).当你正确地注意到,他们需要保护"从来到SEDARGS内容(即,内部的,在你的脚本转义为\\" )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM