[英]Find and Replace Define(Key,Value) in SED Linux
Currently I'm trying to create a bash script for replacing new values I generated. 目前我正在尝试创建一个bash脚本来替换我生成的新值。
These values were stored in constants.php
: 这些值存储在
constants.php
:
-----------constant.php : start-------------------
:
define('PASS1', 'ABCD');
define('PASS2', '1234');
:
-----------constant.php : end---------------------
After running script, (using sed
) it should update the values of PASS1
and PASS 2
separately: 运行脚本后, (使用
sed
)它应该分别更新PASS1
和PASS 2
的值:
-----------constant.php : start-------------------
:
define('PASS1', 'WXYZ');
define('PASS2', '0987');
:
-----------constant.php : end---------------------
Is there a way I can find the KEY eg 'PASS1'
and replace the values after the comma? 有没有办法可以找到KEY,例如
'PASS1'
并替换逗号后的值?
You can specify the occurrence with sed
so sed "/PASS1/s/'[^']*'/'WXYZ'/2"
matches any lines containing PASS1
and does the following substitution s/'[^']*'/'WXYZ'/2
which: 您可以使用
sed
指定事件,因此sed "/PASS1/s/'[^']*'/'WXYZ'/2"
匹配包含PASS1
任何行并执行以下替换s/'[^']*'/'WXYZ'/2
其中:
s/ # Substitute
' # Match a single quote
[^']* # Match anything not a single quote
' # Match the closing single quote
/ # Replace with
'WXYZ' # The literal value
/2 # The 2 here matches the second quoted string, not the first.
# First key
$ sed "/PASS1/s/'[^']*'/'WXYZ'/2" file
define('PASS1', 'WXYZ');
define('PASS2', '1234');
# Second key
$ sed "/PASS2/s/'[^']*'/'0978'/2" file
define('PASS1', 'ABCD');
define('PASS2', '0978');
# In one go
$ sed "/PASS1/s/'[^']*'/'WXYZ'/2;/PASS2/s/'[^']*'/'0978'/2" file
define('PASS1', 'WXYZ');
define('PASS2', '0978');
You need replacement rules similar to this: 您需要与此类似的替换规则:
/'PASS1'/ s/, *'[^']*'/, 'WXYZ'/
Which finds a line containing the quoted PASS1 and replaces the next argument with the correct password. 找到包含引用的PASS1的行,并用正确的密码替换下一个参数。 Writing such rules is tedious and error prone, so I prefer letting sed write them for me.
编写这样的规则是单调乏味且容易出错的,所以我更喜欢让sed为我编写它们。 So if the file
key-value.txt
contains: 因此,如果文件
key-value.txt
包含:
PASS1 WXYZ
PASS2 0987
You can generate the replacement rules with: 您可以使用以下命令生成替换规则:
<key-value.txt sed "s:\(.*\) \(.*\):/\1/ s/, *'[^']*'/, '\2'/:"
Output: 输出:
/'PASS1'/ s/, *'[^']*'/, 'WXYZ'/
/'PASS2'/ s/, *'[^']*'/, '0987'/
Pipe this into a second sed to make the actual replacement: 将此管道插入第二个sed以进行实际更换:
<key-value.txt sed "s:\(.*\) \(.*\):/\1/ s/, *'[^']*'/, '\2'/:" | sed -f - constants.php
Use the -i
switch with the second sed to change constants.php "in-place". 使用
-i
开关和第二个sed来“就地”更改constants.php。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.