从 shell 脚本编辑属性文件中的属性值
标题说明了一切。我需要将我不知道的属性值替换为不同的值。 我正在尝试这个:
#!/bin/bash
sed -i "s/myprop=[^ ]*/myprop=$newvalue/g" file.properties
我得到 sed: -e expression #1, char 19:unknown option to
s'`
我认为问题是 $newvalue
是一个字符串它代表一个目录,因此它会弄乱 sed。
我能做些什么 ?
The title says all. i need to replace a property value whom i don't know to a different value.
i'm trying this:
#!/bin/bash
sed -i "s/myprop=[^ ]*/myprop=$newvalue/g" file.properties
i get sed: -e expression #1, char 19: unknown option to
s'`
I think the problem is that $newvalue
is a string that represents a directory so it messes up sed.
What can I do ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的属性文件是用
=
符号分隔的,那么您可以使用
awk
只需知道 即可修改 param value参数名称。例如,如果我们要修改属性文件中的param2
,我们可以执行以下操作 -现在,上面的
one-liner
需要您硬编码 参数的新值。如果您在 shell 脚本中使用它并且需要从变量获取新值,则情况可能并非如此。在这种情况下,您可以执行以下操作 -
在此我们创建一个
awk
变量newval
并使用包含新参数值的脚本变量 ($var) 对其进行初始化。If your property file is delimited with
=
sign like this -then you can use
awk
do modifiy the param value by just knowing the param name. For example, if we want to modify theparam2
in your property file, we can do the following -Now, the above
one-liner
requires you to hard code the new value of param. This might not be the case if you are using it in a shell script and need to get the new value from a variable.In that case, you can do the following -
In this we create an
awk
variablenewval
and initialize it with your script variable ($var) which contains the new parameter value.sed
可以使用/
以外的字符作为分隔符,尽管/
是最常见的。当处理路径名之类的东西时,使用管道(|
)之类的东西通常会很有帮助。sed
can use characters other than/
as the delimiter, even though/
is the most common. When dealing with things like pathnames, it's often helpful to use something like pipe (|
) instead.我发现一个叫Kongchen的函数。他编写了一个函数脚本来更改属性值,它对我来说效果很好:
检查一下:
https://gist.github.com/kongchen/6748525
I found a function from someone named Kongchen. He wrote a function script to change property values and it worked fine for me:
Check it out:
https://gist.github.com/kongchen/6748525