[英]How to use sed to replace a config file's variable?
I've been looking online for this answer and cannot seem to find it.我一直在网上寻找这个答案,但似乎找不到。
I have a config file that contains:我有一个配置文件,其中包含:
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE5
VAR6=VALUE6
And I want to change VAR5
's value from VALUE5
to VALUE10
.我想将VAR5
的值从VALUE5
为VALUE10
。 Unfortunately, I do not know the value of VALUE5
so I cannot search for it.不幸的是,我不知道VALUE5
的值,所以我无法搜索它。 So basically I need to use sed (or whatever) to replace the value of VAR5
to another value.所以基本上我需要使用 sed (或其他)将VAR5
的值VAR5
为另一个值。
You can try this sed:你可以试试这个 sed:
sed -i.bak 's/^\(VAR5=\).*/\1VALUE10/' file
It gives:它给:
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE10
VAR6=VALUE6
Even though the answer has been added to the question.即使答案已添加到问题中。 I spent some time on how it works, I would like add some facts and my version of the answer,我花了一些时间研究它是如何工作的,我想添加一些事实和我的答案版本,
sed -i 's,^\(THISISMYVARIABLE[ ]*=\).*,\1'THISISMYVALUE',g' config.cfg
Explanation:解释:
sed 's/find_this/replace_with/'
, we are saying sed to search and replace.作为sed 's/find_this/replace_with/'
,我们说 sed 来搜索和替换。 Also remember there are multiple other delimiters that we can use instead of /
.还要记住,我们可以使用多个其他分隔符来代替/
。 Here ,
is used.这里,
被使用。^\\(THISISMYVARIABLE[ ]*=\\).*
.在这里我们找到匹配^\\(THISISMYVARIABLE[ ]*=\\).*
。 This means we are grouping the match THISISMYVARIABLE[ ]*=
.这意味着我们将匹配THISISMYVARIABLE[ ]*=
分组。 ( [ ]*
to cover if there are any spaces after the key) ( [ ]*
覆盖键后是否有空格)\\1
is a back-reference.在替换部分\\1
是一个反向引用。 We are referencing the first group in the regular expression that we used for match.我们正在引用我们用于匹配的正则表达式中的第一组。You can say:你可以说:
sed '/^VAR5=/s/=.*/=VALUE10/' filename
To make in the change to the file in-place , use the -i
option:要就地更改文件,请使用-i
选项:
sed -i '/^VAR5=/s/=.*/=VALUE10/' filename
sed '/\(^VAR5=\).*/ s//\1VALUE10/' YourFile
Under AIX/KSH在 AIX/KSH 下
$ cat sample.txt
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE5
VAR6=VALUE6
$ sed '/\(^VAR5=\).*/ s//\1VALUE10/' sample.txt
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE10
VAR6=VALUE6
and for replacement in file并在文件中替换
cat <> YourFile | sed '/\(^VAR5=\).*/ s//\1VALUE10/'
$ cat <> sample.txt | sed '/\(^VAR5=\).*/ s//\1VALUE10/'
$ cat sample.txt
VAR1=VALUE1
VAR2=VALUE2
VAR3=VALUE3
VAR4=VALUE4
VAR5=VALUE10
VAR6=VALUE6
To be POSIX (on sed
part, not cat
) compliant (sed --posix
on gnu sed and natively traditionnal sed on non linux system)符合 POSIX(在sed
部分,而不是cat
)兼容(在 gnu sed 上为 sed --posix
在非 Linux 系统上为本地传统 sed)
Try the following尝试以下
sed -r 's/^(VAR5=).*/\\1REPLACEMENT/' sed -r 's/^(VAR5=).*/\\1REPLACEMENT/'
The value of VAR5 will be replaced with REPLACEMENT. VAR5 的值将替换为 REPLACEMENT。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.