简体   繁体   English

如何使用sed替换文本文件中声明的变量值

[英]How to use sed to replace variable value declared in a text file

I would like to edit the /etc/environment file to change the MY_VARIABLE from VALUE_01 to VALUE_02 .我想编辑/etc/environment文件以将MY_VARIABLEVALUE_01更改为VALUE_02

Here is the context of the /etc/environment file:这是/etc/environment文件的上下文:

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
JAVA_HOME="/usr/java/jdk8/jdk1.8.0_92-1"
MY_VARIABLE=VALUE_01

Ideally I would like to use sed command to edit it, for example (please note it is not working command):理想情况下,我想使用sed命令来编辑它,例如(请注意它不是工作命令):

sed -e 'MY_VARIABLE=VALUE_02' -i /etc/environment

How can I achieve it?我怎样才能实现它?

sed -- 's/MY_VARIABLE=.*/MY_VARIABLE=VALUE_02/' /etc/environment

Once you check it works, add the -i option:检查它是否有效后,添加-i选项:

sed -i -- 's/MY_VARIABLE=.*/MY_VARIABLE=VALUE_02/' /etc/environment

You will probably need root access.您可能需要 root 访问权限。

Instead of trying to use sed -i and hoping your version of sed implements that option and working out if it takes a mandatory argument or not (I have a feeling you're not using GNU sed like the linux tag suggests you should be), just use ed to edit files in scripts.而不是尝试使用sed -i并希望您的sed版本实现该选项并确定它是否需要强制参数(我感觉您没有像linux标签建议的那样使用 GNU sed ),只需使用ed来编辑脚本中的文件。

ed -s /etc/environment <<EOF
/^MY_VARIABLE=/c
MY_VARIABLE=VALUE_02
.
w
EOF

c hanges the first line starting with MY_VARIABLE= to the given new text, and w rites the file back to disk. çhanges开始的第一行MY_VARIABLE=给定的新文本,和W仪式将文件恢复到磁盘。

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

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