bash 从 shell 脚本编辑属性文件中的属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8607057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:23:56  来源:igfitidea点击:

Edit a property value in a property file from shell script

bashshellsed

提问by Michael

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 tos'`

我明白sed: -e expression #1, char 19: unknown option to

I think the problem is that $newvalueis a string that represents a directory so it messes up sed.

我认为问题在于它$newvalue是一个表示目录的字符串,因此它弄乱了 sed。

What can I do ?

我能做什么 ?

采纳答案by Dan Fego

sedcan 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.

sed可以使用除/分隔符以外的字符,尽管/是最常见的。在处理路径名之类的事情时,使用管道 ( |) 之类的东西通常会有所帮助。

回答by jaypal singh

If your property file is delimited with =sign like this -

如果您的属性文件用这样的=符号分隔-

param1=value1
param2=value2
param3=value3

then you can use awkdo modifiy the param valueby just knowing the param name. For example, if we want to modify the param2in your property file, we can do the following -

那么你可以通过只知道参数名称来使用awk修改参数值。例如,如果我们要修改您的属性文件中的 ,我们可以执行以下操作 -param2

awk -F"=" '/param2/{="new value";print;next}1' filename > newfile

Now, the above one-linerrequires you to hard codethe 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.

现在,以上one-liner要求您对param 的新值进行硬编码。如果您在 shell 脚本中使用它并且需要从变量中获取新值,则情况可能并非如此。

In that case, you can do the following -

在这种情况下,您可以执行以下操作 -

awk -F"=" -v newval="$var" '/param2/{=newval;print;next}1' filename > newfile

In this we create an awkvariable newvaland initialize it with your script variable ($var) which contains the new parameter value.

在此,我们创建一个awk变量newval并使用包含新参数值的脚本变量 ($var) 对其进行初始化。

回答by Michael Hegner

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

看看:https: //gist.github.com/kongchen/6748525