如何使用 sed 更改我的配置文件,具有灵活的键和值? [英] How do I use sed to change my configuration files, with flexible keys and values?
问题描述
我想搜索这个表达式的配置文件:central.database".然后我想将与central.database"关联的设置更改为SQLTEST".
I want to search a configuration file for this expression: "central.database". I then want to change the setting associated with "central.database" to "SQLTEST".
配置文件的布局最初如下所示:
The layout of the config file would look like this initially:
central.database = SQLFIRSTTEST
这就是我想要的 sed 替换后的样子:
This is what i want it to look like after the sed replacement:
central.database = SQLTEST
我在 bash 脚本中执行此操作,欢迎提供任何建议、建议或替代解决方案!
I am doing this in a bash script, any suggestions, recommendations or alternative solutions are welcome!
(实际上 central.database
和 SQLTEST
都来自这里的 bash 变量.)
(Actually both central.database
and SQLTEST
come from bash variables here.)
我当前的代码(第三次尝试):
My current code (third attempt):
sshRetValue=$(ssh -p "35903" -i $HOME/sshids/idrsa-1.old ${1} <<EOF
sed -i "s/^($CENTRAL_DB_NAMEs*=s*).*$/1$CENTRAL_DB_VALUE/" /home/testing.txt;
echo $?
EOF
)
错误信息:
Pseudo-terminal will not be allocated because stdin is not a terminal.
sed: -e expression #1, char 58: unknown option to `s'
-bash: line 3: EOF: command not found
推荐答案
这是一个示例表达式:
sed -i 's/^(central.databases*=s*).*$/1SQLTEST/' file.cfg
如果你想匹配带有 /
的东西,你可以使用另一个分隔符:
If you want to match stuff with /
in it, you can use another delimiter:
sed -i 's#^(cent/ral.data/bases*=s*).*$#1SQL/TEST#' file.cfg
或者使用变量扩展:
VAL="SQLTEST"
sed -i "s/^(central.databases*=s*).*$/1$VAL/" file.cfg
在你的例子中:
sshRetValue=`sed -i "s/^(1$CENTRAL_DB_NAMEs*=s*).*$/1$CENTRAL_DB_VALUE/" /home/testing.txt`;
$CENTRAL_DB_NAME 之前有一个无效的 1.此外, sed 不打印它的返回值.这是检查返回值的首选方法:
There's a 1 before $CENTRAL_DB_NAME that's invalid. Also, sed doesn't print it's return value. This is the preferred way to check return values:
sed -i "s/^($CENTRAL_DB_NAMEs*=s*).*$/1$CENTRAL_DB_VALUE/" /home/testing.txt;
sed_return_value=$?
并最终通过管道传输到 ssh(未测试):
And ultimately piping to ssh (not tested):
sed_return_value=$(ssh server <<EOF
sed -i "s/^($CENTRAL_DB_NAMEs*=s*).*$/1$CENTRAL_DB_VALUE/" /home/testing.txt;
echo $?
EOF
)
-i 用于替换输入文件中的数据.否则 sed 写入标准输出.
The -i is for replacing data in the input file. Otherwise sed writes to stdout.
正则表达式是它们自己的领域.在 stackoverflow 答案中不可能对它们进行深入解释,除非有一些特定的功能让您望而却步.
Regular expressions are a field of their own. It would be impossible to explain them in depth in a stackoverflow answer, unless there is some specific function that's eluding you.
这篇关于如何使用 sed 更改我的配置文件,具有灵活的键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!